package com.zcloud.controller.system;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.PageData;
import com.zcloud.logs.LogAnno;
import com.zcloud.plugins.websocketFace.FaceServerPool;
import com.zcloud.service.system.*;
import com.zcloud.util.*;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 说明：app用户处理
 * 作者：guoyuepeng
 * 官网：www.qdkjchina.com
 */
@Controller
@RequestMapping("/app/user")
public class AppUsersController extends BaseController {

    @Autowired
    private UsersService usersService;
    @Autowired
    private FHlogService FHLOG;
    //        @Autowired
//        private RoleService roleService;
//        @Autowired
//        private DepartmentService departmentService;
    @Autowired
    private ImgFilesService imgfilesService;
    @Autowired
    private PostService postService;
    @Autowired
    private PhotoService photoService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private Smb smb;

    /**
     * 修改用户密码()
     */
    @RequestMapping(value = "/editUserPwd")
    @ResponseBody
    @LogAnno(menuType = "手机", menuServer = "用户处理", instructionsOperate = "用户处理", instructionsType = "修改用户密码")
    public Object editUserPwd() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String userName = pd.getString("USERNAME");
        String userOldPwd = pd.getString("PASSWORD");
        String nowPwd = new SimpleHash("SHA-1", userName, pd.getString("NOWPASSWORD")).toString();//加密新密码
        pd = usersService.findByUsername(pd);

        if (pd.getString("PASSWORD").equals(new SimpleHash("SHA-1", userName, userOldPwd).toString())) {    //密码验证成功
            PageData updateUserPd = new PageData();
            updateUserPd.put("USER_ID", pd.get("USER_ID"));
            updateUserPd.put("PASSWORD", nowPwd);
            usersService.editPassword(updateUserPd);
            FHLOG.save(userName, "从app修改密码中修改" + userName + "的密码");                //记录日志
        } else {
            errInfo = "usererror";
            FHLOG.save(userName, "尝试登录系统失败,用户名密码错误,无权限");
        }
        /**
         * 1.验证原始密码是否正确
         * 2.密码加密
         * 3.修改数据库
         * 4.增加日志
         */
        map.put("result", errInfo);
        return map;

    }

    /**
     * 用户头像
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getUserPhoto")
    @ResponseBody
    @LogAnno(menuType = "手机", menuServer = "用户处理", instructionsOperate = "用户处理", instructionsType = "用户头像")
    public Object getList() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        PageData pd = new PageData();
        pd = this.getPageData();
        String errInfo = "success";

        pd.put(Const.SESSION_USERNAME, pd.getString("USERNAME"));
        PageData pdPhoto;
        pdPhoto = photoService.findById(pd);
        map.put("userPhoto", null == pdPhoto ? "assets/images/user/avatar-2.jpg" : pdPhoto.getString("PHOTO2"));//用户头像
        map.put("result", errInfo);
        return map;
    }

    /**
     * 用户人脸
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/editUserFace")
    @ResponseBody
    @LogAnno(menuType = "手机", menuServer = "用户处理", instructionsOperate = "用户处理", instructionsType = "用户人脸")
    public Object editUserFace() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        if (pd.get("USERAVATARURL") != null && !pd.getString("USERAVATARURL").equals("")) {
            System.out.println("USERAVATARURL原长度：" + pd.getString("USERAVATARURL").length());
            String USERAVATARURL64 = ImageAnd64Binary.zipBase64(pd.getString("USERAVATARURL"));
            System.out.println("USERAVATARURL压缩长度：" + USERAVATARURL64.length());
            try {
                FaceUtil.compareFace(pd.getString("USERAVATARURL"), pd.getString("USERAVATARURL"));
            } catch (Exception e) {
                map.put("result", "error");
                map.put("msg", "人脸图像不符合要求 请重新上传!");
                return map;
            }
        }

        PageData user;
        user = usersService.findById(pd);
        user.put("USERAVATARPREFIX", pd.getString("USERAVATARPREFIX"));
        user.put("USERAVATARURL", pd.getString("USERAVATARURL"));
        usersService.editUser(user);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 用户人脸
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/compareFace")
    @ResponseBody
    @LogAnno(menuType = "手机", menuServer = "用户处理", instructionsOperate = "用户处理", instructionsType = "用户人脸")
    public Object compareFace() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = this.getPageData();
        PageData user = usersService.findById(pd);
        if (Tools.isEmpty(user.getString("USERAVATARURL"))) {
            map.put("result", "error");
            map.put("msg", "用户未录入人脸信息,无法验证");
            return map;
        }
        try {
            String confidence = FaceUtil.compareFace(pd.getString("USERAVATARURL"), new String((byte[]) user.get("USERAVATARURL"), StandardCharsets.UTF_8));
            if (Double.valueOf(confidence) < 75) {
                map.put("result", "error");
                map.put("msg", "与本人不符");
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", "error");
            map.put("msg", "未检测到人脸或用户未录入人脸信息，请确认。");
            return map;
        }
        map.put("result", errInfo);
        return map;
    }

    /**
     * 用户人脸
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/compareFaceForH5")
    @ResponseBody
    @LogAnno(menuType = "手机", menuServer = "用户处理", instructionsOperate = "用户处理", instructionsType = "用户人脸")
    public Object compareFaceForH5() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        PageData user = usersService.findById(pd);
        if (user.get("USERAVATARURL") == null || user.get("USERAVATARURL") == "") {
            map.put("result", "error");
            map.put("msg", "用户未录入人脸信息,无法验证");
            return map;
        }
        try {
            String confidence = FaceUtil.compareFace(pd.getString("USERAVATARURL"), new String((byte[]) user.get("USERAVATARURL"), StandardCharsets.UTF_8));
            if (Double.valueOf(confidence) < 75) {
                map.put("result", "error");
                map.put("msg", "与本人不符");
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", "error");
            map.put("msg", "未检测到人脸");
            return map;
        }
        JSONObject result = new JSONObject();
        result.element("type", "success");
        WebSocket conn = FaceServerPool.getWebSocketByUser(user.getString("USER_ID"));
        FaceServerPool.sendMessageToUser(conn, result.toString());
        map.put("result", errInfo);
        return map;
    }

    /**
     * 查询公司所有用户
     *
     * @param page
     * @throws Exception
     */
    @RequestMapping(value = "/listUserByCorp")
    @ResponseBody
    @LogAnno(menuType = "手机", menuServer = "用户处理", instructionsOperate = "用户处理", instructionsType = "查询公司所有用户")
    public Object listUserByCorp() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("NOMAIN", "1");
        List<PageData> userList = usersService.listUserDepPos(pd);    //列出Post列表
        map.put("userList", userList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 获取用户的签字信息
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/geUserInfoSign")
    @ResponseBody
    @LogAnno(menuType = "手机", menuServer = "用户处理", instructionsOperate = "用户处理", instructionsType = "获取用户的签字信息")
    public Object geUserInfoSign() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String userSign = "";
        PageData userInfo = userInfoService.findById(pd); // 获取用户详情信息
        if (null != userInfo) {
            userSign = userInfo.getString("USER_SIGN_FILE_PATH");
        }
        map.put("IMGURL", userSign);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 保存用户签字信息
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/updateUserSign")
    @ResponseBody
    @Transactional
    @LogAnno(menuType = "手机", menuServer = "用户处理", instructionsOperate = "用户处理", instructionsType = "保存用户签字信息")
    public Object editStatus(@RequestParam(value = "FFILE", required = false) MultipartFile[] files) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        String msg = "";
        PageData pd = new PageData();
        pd = this.getPageData();
        PageData user = usersService.findById(pd);
        if (null == user) {
            errInfo = "error";
            msg = "未找到用户信息，请刷新后再次尝试！";
        }

        if (files != null && files.length > 0) {
            MultipartFile file = files[0];
//                 保存文件
            File tempFile = new File(file.getOriginalFilename());
            FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);

            String ffile = DateUtil.getDays();
            String fileName = this.get32UUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            smb.sshSftp(file, fileName, Const.FILEPATH_USER_SIGN + pd.getString("CORPINFO_ID") + "/" + ffile);
            pd.put("USER_SIGN_FILE_PATH", Const.FILEPATH_USER_SIGN + pd.getString("CORPINFO_ID") + "/" + ffile + "/" + fileName);
            pd.put("USER_ID", user.getString("USER_ID"));
            userInfoService.editUserSign(pd);
        }

        map.put("result", errInfo);
        return map;
    }

    /**
     * 去修改用户页面(从系统用户页面修改)
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goEditUser")
    @ResponseBody
    @LogAnno(menuType = "教育培训", menuServer = "档案管理", instructionsOperate = "一人一档", instructionsType = "去修改用户页面(从系统用户页面修改)")
    public Object goEditUser() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
//            if("1".equals(pd.getString("USER_ID"))){return null;}		//不能修改admin用户
//            pd.put("ROLE_ID", Jurisdiction.getVIPLEVEL());
//            List<Role> roleList = roleService.listAllRolesByPId(pd);	//列出所有系统用户角色

//		//获取部门下拉树
//		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//		String ZDEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//		ZDEPARTMENT_ID = "".equals(ZDEPARTMENT_ID)?"0":ZDEPARTMENT_ID;
//		PageData dept = new PageData();
//		dept.put("DEPARTMENT_ID",ZDEPARTMENT_ID);
//		dept=this.departmentService.findById(dept);
//            List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//            PageData dept = new PageData();
//            dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
//            dept=this.departmentService.findByCorpId(dept);
//            String ZDEPARTMENT_ID = dept.getString("DEPARTMENT_ID");
//
//            PageData node = new PageData();
//            node.put("id", dept.get("DEPARTMENT_ID"));
//            node.put("parentId", dept.get("PARENT_ID"));
//            node.put("name", dept.get("NAME"));
//            node.put("icon", "../../../assets/images/user.gif");
//            zdepartmentPdList.add(node);
//            JSONArray arr = JSONArray.fromObject(departmentService.listAllDepartmentToSelect(ZDEPARTMENT_ID,zdepartmentPdList));
//            map.put("zTreeNodes", (null == arr ?"":"{\"treeNodes\":" + arr.toString() + "}"));
//            String depname = null == dept?"请选择":dept.getString("NAME");
//            map.put("depname", null == depname?"请选择":depname);
        pd = usersService.findById(pd);                                //根据ID读取
        pd.put("ISSTUDENT", Boolean.valueOf(pd.getString("ISSTUDENT")));
        PageData shiftDutyPeriod = new PageData();
        shiftDutyPeriod.put("DURATION", pd.get("DURATION"));
        shiftDutyPeriod.put("WORKSTATUS", pd.get("WORKSTATUS"));
        shiftDutyPeriod.put("WORKPERIOD", pd.get("WORKPERIOD"));

//            String ROLE_IDS = pd.getString("ROLE_IDS");					//副职角色ID
//            if(Tools.notEmpty(ROLE_IDS)){
//                String arryROLE_ID[] = ROLE_IDS.split(",");
//                for(int i=0;i<roleList.size();i++){
//                    Role role = roleList.get(i);
//                    String roleId = role.getROLE_ID();
//                    for(int n=0;n<arryROLE_ID.length;n++){
//                        if(arryROLE_ID[n].equals(roleId)){
//                            role.setRIGHTS("1");	//此时的目的是为了修改用户信息上，能看到副职角色都有哪些
//                            break;
//                        }
//                    }
//                }
//            }
        PageData userInfo = userInfoService.findById(pd); // 添加 用户详情 CERTIFICATE_INFORMATION 证书信息
        List<PageData> userCerList = new ArrayList<PageData>();
        if (null != userInfo) {
            PageData userCerPd = new PageData();
            userCerPd.put("TYPE", "18");
            userCerPd.put("FOREIGN_KEY", pd.get("USER_ID"));
            userCerList = imgfilesService.listAll(userCerPd);
            pd.putAll(userInfo);
        }
        pd.put("SEX_NAME", "");
        if (Tools.notEmpty(pd.getString("SEX"))) {
            pd.put("SEX_NAME", pd.getString("SEX").equals("1") ? "男" : "女");
        }
        //获取岗位下拉
        PageData post = new PageData();
//            post.put("DEPARTMENT_ID", ZDEPARTMENT_ID);
        post.put("STATUS", 0);
        List<PageData> postList = this.postService.listAll(post);
        map.put("postList", postList);
        map.put("pd", pd);
        map.put("period", shiftDutyPeriod);
        map.put("periodStr", shiftDutyPeriod.getString("DURATION") + ',' + shiftDutyPeriod.getString("WORKSTATUS") + ',' + shiftDutyPeriod.getString("WORKPERIOD"));
        map.put("userCerList", userCerList);
//            map.put("roleList", roleList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 更新用户pushcid
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updatePushCid")
    @ResponseBody
    public Object updatePushCid() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        usersService.updatePushCid(pd);
        map.put("result", errInfo);
        return map;
    }
}
