package com.zcloud.service.system.impl;

import com.alibaba.fastjson.JSONObject;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.User;
import com.zcloud.mapper.datasource.system.UsersMapper;
import com.zcloud.service.corp.CorpInfoService;
import com.zcloud.service.system.*;
import com.zcloud.util.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 说明：用户服务接口实现类
 * 作者：luoxiaobao
 * 官网：www.qdkjchina.com
 */
@Service
@Transactional //开启事物
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private DictionariesCorpService dictionariesCorpService;
    @Autowired
    private FHlogService FHLOG;
    @Autowired
    private CorpInfoService corpInfoService;

    /**
     * 通过用户名获取用户信息
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData findByUsername(PageData pd) throws Exception {
        return usersMapper.findByUsername(pd);
    }

    public PageData findByName(PageData pd) throws Exception {
        return usersMapper.findByName(pd);
    }

    /**
     * 通过用户ID获取用户信息
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData findById(PageData pd) throws Exception {
        return usersMapper.findById(pd);
    }

    /**
     * 通
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> listUserAndDept(PageData pd) throws Exception {
        return usersMapper.listUserAndDept(pd);
    }

    /**
     * 获取获取部门账号
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> listUserbyDep(PageData pd) throws Exception {
        return usersMapper.listUserbyDep(pd);
    }

    /**
     * 用户列表
     *
     * @param page
     * @return
     * @throws Exception
     */
    public List<PageData> userlistPage(Page page) throws Exception {
        return usersMapper.userlistPage(page);
    }

    public List<PageData> listAll(PageData pd) throws Exception {
        return usersMapper.listAll(pd);
    }

    /**
     * 用户列表
     *
     * @param page
     * @return
     * @throws Exception
     */
    public List<PageData> userSelectlistPage(Page page) throws Exception {
        return usersMapper.userSelectlistPage(page);
    }

    /**
     * 通过用户ID获取用户信息和角色信息
     *
     * @param USER_ID
     * @return
     * @throws Exception
     */
    public User getUserAndRoleById(String USER_ID) throws Exception {
        return usersMapper.getUserAndRoleById(USER_ID);
    }

    /**
     * 保存用户IP
     *
     * @param pd
     * @throws Exception
     */
    public void saveIP(PageData pd) throws Exception {
        usersMapper.saveIP(pd);
    }

    /**
     * 通过邮箱获取数据
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData findByEmail(PageData pd) throws Exception {
        return usersMapper.findByEmail(pd);
    }

    /**
     * 通过编码获取数据
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData findByNumbe(PageData pd) throws Exception {
        return usersMapper.findByNumbe(pd);
    }

    /**
     * 列出某角色下的所有用户
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> listAllUserByRoldId(PageData pd) throws Exception {
        return usersMapper.listAllUserByRoldId(pd);
    }

    /**
     * 用户列表(全部)
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> listAllUser(PageData pd) throws Exception {
        return usersMapper.listAllUser(pd);
    }

    /**
     * 查询部门下用户
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> listUserByDept(PageData pd) throws Exception {
        return usersMapper.listUserByDept(pd);
    }

    /**
     * 用户列表(弹窗选择用)
     *
     * @param page
     * @return
     * @throws Exception
     */
    public List<PageData> listUsersBystaff(Page page) throws Exception {
        return usersMapper.userBystafflistPage(page);
    }

    /**
     * 保存用户
     *
     * @param pd
     * @throws Exception
     */
    public void saveUser(PageData pd) throws Exception {
        usersMapper.saveUser(pd);
    }

    /**
     * 保存用户系统皮肤
     *
     * @param pd
     * @throws Exception
     */
    public void saveSkin(PageData pd) throws Exception {
        usersMapper.saveSkin(pd);
    }

    /**
     * 修改用户
     *
     * @param pd
     * @throws Exception
     */
    public void editUser(PageData pd) throws Exception {
        usersMapper.editUser(pd);
    }

    public void editUserState(PageData pd) throws Exception {
        usersMapper.editUserState(pd);
    }

    /**
     * 通过USERID查监管端用户
     *
     * @param pd
     * @throws Exception
     */
    @Override
    public PageData findByRegulatoryId(PageData pd) throws Exception {
        return usersMapper.findByRegulatoryId(pd);
    }

    public PageData findByIdForEmis(PageData pd) throws Exception {
        return usersMapper.findByIdForEmis(pd);
    }

    @Override
    public String changeOrUpdUserCardNo(PageData nowuser) throws Exception {
        PageData oldUser = usersMapper.findById(nowuser);
        // 此人原来无卡号
        // 先判断人员新的定位卡号是否有变化，没变化直接可以修改
        if (oldUser.getString("CARDNO") != null && oldUser.getOrDefault("CARDNO", "").equals(nowuser.getString("CARDNO"))) {
            return Const.CAN_CHENG_USER;
        }
        // 有变化看库里是否有人在用这个新卡号
        PageData getCordNo = new PageData();
        getCordNo.putAll(nowuser);
        getCordNo.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        PageData usedCardNo = usersMapper.findByCardNo(getCordNo);
        // 卡号被本系统中他人使用了
        if (usedCardNo != null) {
            return Const.CARD_ALREADY_BEEN_USED + usedCardNo.getString("NAME");
        }
        PageData cardNumberPeople = PLSUtil.getCardNumberPeople(nowuser);
        // 这个新卡号其他系统中绑定人了
        if (cardNumberPeople != null) {
            return "人员定位系统中" + Const.CARD_ALREADY_BEEN_USED + cardNumberPeople.getString("name");
        }
        return Const.CAN_CHENG_USER;
    }

    @Override
    public List<PageData> getUserCardNoAll(PageData departPd) {
        return usersMapper.getUserCardNoAll(departPd);
    }

    @Override
    public PageData getUserByCardNo(PageData pageData) {
        return usersMapper.getUserByCardNo(pageData);
    }

    @Override
    public void removeCardNoUser(PageData pageData) {
        usersMapper.removeCardNoUser(pageData);
    }

    @Override
    public void editUserCardNoByPid(PageData pageData) {
        usersMapper.editUserCardNoByPid(pageData);
    }

    @Override
    public void editUserWorkName(PageData pageData) {
        usersMapper.editUserWorkName(pageData);
    }

    @Override
    public void removeUserWorkName(PageData pageData) {
        usersMapper.removeUserWorkName(pageData);
    }

    @Override
    public int hasUserUseWord(PageData query) {
        return  usersMapper.hasUserUseWord(query);
    }


    @Override
    public ReturnMap saveUserNew(PageData pd) throws Exception {
        // 设置基本信息
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        pd.put("WORKSTATUS", "1");
        pd.put("WORKPERIOD", "1");
//        pd.put("RIGHTS", "788664966448");

        // 获取 corpInfo 信息
        PageData corpInfo = corpInfoService.findById(pd);

        if ("0".equals(corpInfo.getString("PERSONNEL_POSITION"))) {
            try {
                if (!PLSUtil.hasCardNumber(pd)) {
                    return ReturnMap.error(pd.getString("CARDNO") + " 定位卡已经存在");
                }
            } catch (Exception e) {

                return ReturnMap.ok().put("webSiteStatus", "1");
            }
            PageData response = PLSUtil.saveUser(pd);
            if ("200".equals(response.getString("code"))) {
                pd.put("PLS_ID", response.getString("data"));
                if (Tools.isEmpty(pd.getString("CARDNO"))) {
                    pd.put("CARDNO", null);
                }
            } else {
                return ReturnMap.error(response.getString("msg"));
            }
        }

        // 检查用户头像
        if (pd.get("USERAVATARURL") != null && !pd.getString("USERAVATARURL").equals("")) {
            String USERAVATARURL64 = ImageAnd64Binary.zipBase64(pd.getString("USERAVATARURL"));
            try {
                FaceUtil.compareFace(pd.getString("USERAVATARURL"), pd.getString("USERAVATARURL"));
            } catch (Exception e) {
                throw new Exception("人脸图像不符合要求，请重新上传");
            }
        }

        // 处理 LEARNERCATEGORYSTATUS
        if ("input".equals(pd.getString("LEARNERCATEGORYSTATUS"))) {
            pd.put("DICTTYPE", "APPLICABLE_PERSONNEL");
            PageData lc = dictionariesCorpService.saveSelf(pd);
            pd.put("LEARNERCATEGORY", lc.getString("DICTIONARIES_ID"));
        }

        // 设置用户的基本信息
        pd.put("USER_ID", Warden.get32UUID());
        pd.put("LAST_LOGIN", "");
        pd.put("IP", "");
        pd.put("STATUS", "0");
        pd.put("ISMAIN", "0");
        pd.put("SKIN", "pcoded-navbar navbar-image-3, navbar pcoded-header navbar-expand-lg navbar-light header-dark");
        pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), "666666").toString());

        // 检查用户是否已存在
        if (usersMapper.findByUsername(pd) == null) {
            if ("true".equals(pd.getString("ISSTUDENT"))) {
                // 处理职务、头衔、工种相关逻辑
                if ("select".equals(pd.getString("letDutiesType"))) {
                    pd.put("DUTIES", pd.getString("DUTIES"));
                } else {
                    PageData dicPd = new PageData();
                    dicPd.put("PARENT_ID", "09e36ac01e9540f8bc84eab1c1a78754");
                    dicPd.put("BIANMA", "zhiwu");
                    dicPd.put("NAME", pd.getString("DUTIESValue"));
                    dicPd = dictionariesCorpService.saveByZidongxinzeng(dicPd);
                    pd.put("DUTIES", dicPd.getString("DICTIONARIES_ID"));
                }

                if ("select".equals(pd.getString("letTitleType"))) {
                    pd.put("TITLE", pd.getString("TITLE"));
                } else {
                    PageData dicPd = new PageData();
                    dicPd.put("PARENT_ID", "945a6b10e59946078b500f0fbafa8679");
                    dicPd.put("BIANMA", "zhicheng");
                    dicPd.put("NAME", pd.getString("letTitleValue"));
                    dicPd = dictionariesCorpService.saveByZidongxinzeng(dicPd);
                    pd.put("TITLE", dicPd.getString("DICTIONARIES_ID"));
                }

                if ("select".equals(pd.getString("letTypeOfWorkType"))) {
                    pd.put("TYPE_OF_WORK", pd.getString("TYPE_OF_WORK"));
                } else {
                    PageData dicPd = new PageData();
                    dicPd.put("PARENT_ID", "55484e491a5e442d839c4595380713ec");
                    dicPd.put("BIANMA", "gongzhong");
                    dicPd.put("NAME", pd.getString("letTypeOfWorkValue"));
                    dicPd = dictionariesCorpService.saveByZidongxinzeng(dicPd);
                    pd.put("TYPE_OF_WORK", dicPd.getString("DICTIONARIES_ID"));
                }

                // 保存用户基本信息
                userInfoService.save(pd);
            }

            // 保存用户信息到数据库
            usersMapper.saveUser(pd);
            FHLOG.save(Jurisdiction.getUsername(), "新增用户：" + pd.getString("USERNAME"));
            return ReturnMap.ok();
        }

        return ReturnMap.error("保存失败");
    }


    public void editPassword(PageData pd) throws Exception {
        usersMapper.editPassword(pd);
    }

    /**
     * 删除用户
     *
     * @param pd
     * @throws Exception
     */
    public void deleteUser(PageData pd) throws Exception {
        usersMapper.deleteUser(pd);
    }

    /**
     * 批量删除用户
     *
     * @param pd
     * @throws Exception
     */
    public void deleteAllUser(String[] USER_IDS) throws Exception {
        usersMapper.deleteAllUser(USER_IDS);
    }

    public List<PageData> listUserBYids(String[] USER_IDS) throws Exception {
        return usersMapper.listUserBYids(USER_IDS);
    }

    /**
     * 修改用户小程序权限
     *
     * @param pd
     * @throws Exception
     */
    public void editUserFuns(PageData pd) {
        usersMapper.editUserFuns(pd);
    }

    /**
     * 查询小程序用户
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData findAppUserById(PageData pd) throws Exception {
        return usersMapper.findAppUserById(pd);
    }

    /**
     * 用户同意协议
     *
     * @param pd
     * @throws Exception
     */
    public void agreeProtocol(PageData pd) throws Exception {
        usersMapper.agreeProtocol(pd);
    }

    /**
     * 获取该企业下所有用户，用户判断是否重复
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> findUserNameAll(PageData pd) throws Exception {
        // TODO Auto-generated method stub
        return usersMapper.findUserNameAll(pd);
    }

    /**
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> findAllUser(PageData pd) throws Exception {
        // TODO Auto-generated method stub
        return usersMapper.findAllUser(pd);
    }

    /**
     * 获取账号及部门岗位
     *
     * @param pd
     * @return
     * @throws Exception
     */
    @Override
    public List<PageData> listUserDepPos(PageData pd) throws Exception {
        return usersMapper.listUserDepPos(pd);
    }

    /**
     * 查询公司员工总数
     *
     * @param pd
     * @return
     */
    public int getUserCount(PageData pd) throws Exception {
        return usersMapper.getUserCount(pd);
    }

    /**
     * 查询公司检查过清单的员工总数
     *
     * @param pd
     * @return
     */
    public int getWorkedUserCount(PageData pd) throws Exception {
        return usersMapper.getWorkedUserCount(pd);
    }

    /**
     * 查询用户倒班周期数据
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> getUserWork(PageData pd) throws Exception {
        return usersMapper.getUserWork(pd);
    }

    /**
     * 修改用户倒班周期
     *
     * @param pd
     * @throws Exception
     */
    public void editShiftWork(PageData pd) {
        usersMapper.editShiftWork(pd);
    }

    /**
     * 获取人员Cascader数据(人员ID，姓名，部门ID，部门级别)
     *
     * @param pd
     * @return
     * @throws Exception
     */
    @Override
    public List<PageData> listCascader(PageData pd) throws Exception {
        return usersMapper.listCascader(pd);
    }

    /**
     * 清除在线学习人员分类
     *
     * @param pd
     * @return
     * @throws Exception
     */
    @Override
    public void clearLearnerCategory(PageData pd) throws Exception {
        usersMapper.clearLearnerCategory(pd);
    }

    /**
     * 获取账号及部门岗位
     *
     * @param pd
     * @return
     * @throws Exception
     */
    @Override
    public List<PageData> listUserDepPoslistPage(Page page) throws Exception {
        return usersMapper.listUserDepPoslistPage(page);
    }

    /**
     * 获取账号及部门岗位
     *
     * @param pd
     * @return
     * @throws Exception
     */
    @Override
    public List<PageData> listUserDepPoslist(Page page) throws Exception {
        return usersMapper.listUserDepPoslist(page);
    }

    /**
     * 更新用户pushcid
     *
     * @param pd
     * @throws Exception
     */
    public void updatePushCid(PageData pd) throws Exception {
        usersMapper.updatePushCid(pd);
    }

    /**
     * 修改公司名称时同步修改企业账号
     *
     * @param pd
     * @throws Exception
     */
    public void updateCornUser(PageData pd) throws Exception {
        usersMapper.updateCornUser(pd);
    }

    /**
     * 查询用户名称及部门名称
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData findUserDept(PageData pd) throws Exception {
        return usersMapper.findUserDept(pd);
    }

    /**
     * 用户列表(本部门及所有上级部门领导负责人)
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> listUserLeader(PageData pd) throws Exception {
        List<String> deptArr = new ArrayList<>();
        PageData dept = departmentService.findById(pd);
        deptArr.add(dept.getString("DEPARTMENT_ID"));
        findParentDept(deptArr, dept);
        pd.put("DEPT_IDS", deptArr);
        List<PageData> userList = usersMapper.listUserLeader(pd);
        for (int i = 0; i < userList.size(); i++) {        //申请人为部门负责人 移除
            if (pd.getString("USER_ID").equals(userList.get(i).getString("USER_ID"))) {
                userList.remove(i);
            }
        }
        return userList;
    }

    private void findParentDept(List<String> deptArr, PageData dept) throws Exception {
        if (!"0".equals(dept.getString("PARENT_ID"))) {
            PageData p = new PageData();
            p.put("DEPARTMENT_ID", dept.getString("PARENT_ID"));
            PageData parent = departmentService.findById(p);
            deptArr.add(parent.getString("DEPARTMENT_ID"));
            if (!"0".equals(parent.getString("PARENT_ID"))) {
                findParentDept(deptArr, parent);

            }
        }
    }

    /**
     * 获取账号及部门岗位
     *
     * @param page
     * @return
     * @throws Exception
     */
    public List<PageData> listUserlistPage(Page page) throws Exception {
        return usersMapper.listUserlistPage(page);
    }

    @Override
    public List<PageData> selectUserListByUserIds(PageData pd) {
        return	usersMapper.selectUserListByUserIds(pd);
    }



}
