package com.fufan.mtsaas.modules.sysmgr.syuser.service.impl;

import com.fufan.mtsaas.modules.sysmgr.syuser.bo.request.*;
import com.fufan.mtsaas.modules.sysmgr.syuser.dao.SYusergroupDao;
import com.fufan.mtsaas.modules.sysmgr.syuser.model.SYusergroup;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fufan.mtsaas.modules.base.log.bo.request.LogSaveRequest;
import com.fufan.mtsaas.modules.base.log.service.TSysLogSvc;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.sysmgr.sydept.dao.SYDeptDao;
import com.fufan.mtsaas.modules.sysmgr.sydept.model.SYDept;
import com.fufan.mtsaas.modules.sysmgr.syuser.model.SYuser;
import com.fufan.mtsaas.modules.base.company.dao.TCompanyDao;
import com.fufan.mtsaas.modules.base.company.dao.TCompanyPurchaseDao;
import com.fufan.mtsaas.modules.base.company.model.TCompany;
import com.fufan.mtsaas.modules.base.company.model.TCompanyPurchase;
import com.fufan.mtsaas.modules.sysmgr.syuser.model.SYuserInfo;
import com.github.pagehelper.ISelect;
import com.fufan.mtsaas.config.RedissonCommand;
import com.fufan.mtsaas.constant.RedisKeyConstant;
import com.fufan.mtsaas.modules.sysmgr.sygroup.dao.SYgroupDeptDao;
import com.fufan.mtsaas.modules.sysmgr.sygroup.dao.SYgroupHDao;
import com.fufan.mtsaas.modules.sysmgr.sygroup.model.SYgroupH;
import com.fufan.mtsaas.modules.sysmgr.syuser.bo.reponse.RoleSelectResponse;
import com.fufan.mtsaas.modules.sysmgr.syuser.dao.SYuserDao;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupDeptInfo;
import com.fufan.mtsaas.modules.sysmgr.syuser.bo.response.UserResponse;
import com.fufan.mtsaas.modules.sysmgr.syuser.service.SYuserSvc;
import com.fufan.mtsaas.tools.AESTool;
import com.fufan.mtsaas.util.DateFormatTool;
import com.fufan.mtsaas.util.ParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.fufan.mtsaas.cache.Cache.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Liby
 * @since 2019-08-14
 */
@Service("SYuserSvcImpl")
@Slf4j
@Primary
public class SYuserSvcImpl extends ServiceImpl<SYuserDao, SYuser> implements SYuserSvc {
    @Autowired
    private SYuserDao entitymDao;
    @Autowired
    private SYgroupDeptDao entitygpDao;
    @Autowired
    private TCompanyDao tCompanyDao;
    @Value("${DEPTCODE_FLAG}")
    private String DEPTCODE_FLAG;
    @Value("${DEFAULT_TOP_DEPCODE}")
    private String DEFAULT_TOP_DEPCODE;
    @Autowired
    private TCompanyPurchaseDao tCompanyPurchaseDao;
    @Autowired
    private SYgroupHDao sYgroupHDao;
    @Autowired
    private RedissonCommand redissonCommand;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private TSysLogSvc tSysLogSvc;
    @Autowired
    private SYDeptDao syDeptDao;
    @Autowired
    private SYusergroupDao sYusergroupDao;
//
//    @Autowired
//    private MSempInfoDao mSempInfoDao;

    @Value("${COMPANY_CD}")
    private String COMPANY_CD;
    @Value("${COMPANY_ID}")
    private String COMPANY_ID;

    /**
     * 查询组-部门数据权限
     * 2019-11-05
     *
     * @param map
     * @return
     */
    @Override
    public String queryDeptInfo(Map<String, String> map) {
        String depInfo = "";
        String groupInfo = "";
        Map<String, String> mapData = new HashMap<>();
        String CompanyID = ParamUtil.getParamfromMap(map, "CompanyID");
        String UserID = ParamUtil.getMetadatafromMap(map, "user");
        Page page = new Page();

        if (DEPTCODE_FLAG.equalsIgnoreCase("0")) {
            return null;
        }

        if (Objects.isNull(CompanyID)) {
            CompanyID = COMPANY_CD;
        }


        List<SYuser> entitys;

        ParamUtil.setPage(map, page);
        entitys = entitymDao.selectList(page, mapData);
        if (entitys != null && entitys.size() > 0) {
            groupInfo = entitys.get(0).getUserGroupID();
        } else {
            groupInfo = "XXX";
        }

        List<SYGroupDeptInfo> entityDept;
        mapData = new HashMap<>();
        mapData.put("CompanyID", CompanyID);
        mapData.put("GroupID", groupInfo);
        entityDept = entitygpDao.selectList(page, mapData);
        for (SYGroupDeptInfo dpInfo : entityDept) {
            if (!depInfo.contains("'" + dpInfo.getDepCode() + "'")) {
                depInfo = depInfo + ",'" + dpInfo.getDepCode() + "'";
            }
        }

        if (depInfo.length() > 0) {
            depInfo = depInfo.substring(1);
//            depInfo = depInfo.substring(2);
//            depInfo = depInfo.substring(0, depInfo.length() - 1);
        } else {
            depInfo = "'XXX'";
        }

        return depInfo;
    }

    @Override
    public Result doQueryUserRole(UserGroupQueryRequest map, RequestPojo requestPojo) {
        log.debug("SYuserSvcImpl.doQueryUserRole parameter: {}", map);
        Result result = new Result();
        //非空验证
        if (Objects.isNull(map.getUserId())) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }
        //分页查询
        Page page = new Page();
        List<SYgroupH> entitys;

        entitys = sYgroupHDao.queryUserRole(page, map);

        page.setTotal((int) entitys.size());
        page.setRecords(entitys);
        result.setResData(page);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

        return result;
    }

    @Override
    public Result doQueryRoleUser(UserGroupQueryRequest map, RequestPojo requestPojo) {
        log.debug("SYuserSvcImpl.doQueryRoleUser parameter: {}", map);
        Result result = new Result();
        //非空验证
        if (Objects.isNull(map.getUserGroupId())) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }
        //分页查询
        Page page = new Page();
        List<SYuserInfo> entitys;

        entitys = entitymDao.queryRoleUser(page, map);

        page.setTotal((int) entitys.size());
        page.setRecords(entitys);
        result.setResData(page);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

        return result;
    }

    /**
     * 查询
     *
     * @param map
     * @return Result.class
     */
    @Override
    public Result doQueryPage(UserQueryRequest map) {
        RequestPojo requestPojo = ParamUtil.doChange();
        Result result = new Result();
        //分页查询
        Page page = new Page();
        log.debug("SYuserSvcImpl.doQueryPage parameter: {}", map);
        Map<String, String> mapData = new HashMap<>();

        String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" + map.getUserID());
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(map.getUserID()) && org.apache.commons.lang3.StringUtils.isEmpty(userRedisId)) {
            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
            page.setTotal(0);
            result.setResData(page);
            return result;
        }
        String Name = map.getUserName();

//        //赋值默认
//        if(StringUtils.isEmpty(CompanyID)){
//            CompanyID = COMPANY_CD;
//        }
//
        mapData.put("CompanyID", requestPojo.getCustId());
        try {
            if (StringUtils.isNotEmpty(map.getUserID())) {
                mapData.put("UserID", AESTool.encrypt(map.getUserID()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Objects.nonNull(map.getId()) && map.getId() != 0) {
            mapData.put("ID", String.valueOf(map.getId()));
        }
        mapData.put("Name", Name);
        mapData.put("EmpNo", map.getEmpNo());
        if (Objects.nonNull(map.getUserGroupID()) && map.getUserGroupID() != 0) {
            mapData.put("userGroupID", String.valueOf(map.getUserGroupID()));
        }
        if (Objects.nonNull(map.getDeptID())) {
            //主数据抓取全部
            SYDept dept = syDeptDao.selectById(map.getDeptID());
            if (!(Objects.nonNull(dept) && dept.getParID().equalsIgnoreCase(DEFAULT_TOP_DEPCODE))) {
                mapData.put("DeptID", String.valueOf(map.getDeptID()));
            }
        }

        List<SYuserInfo> entitys;

        //分页处理 -- 20192021 Liby
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                entitymDao.selectListInfo(page, mapData);
            }
        });

        ParamUtil.setPage(map.getPageSize(), map.getCurrentPage(), page);
        entitys = entitymDao.selectListInfo(page, mapData);
        List<UserResponse> userResponseList = new ArrayList<>();
        for (SYuserInfo sYuser : entitys) {
            UserResponse userResponse = new UserResponse();
            BeanUtils.copyProperties(sYuser, userResponse);
            try {
                if (StringUtils.isNotEmpty(sYuser.getUserID())) {
                    userResponse.setUserID(AESTool.decrypt(sYuser.getUserID()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (Objects.nonNull(sYuser.getPhoneNo())) {
                    userResponse.setPhoneNo(AESTool.decrypt(sYuser.getPhoneNo()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            userResponse.setId(sYuser.getId());
            userResponse.setCompanyName(COMPANY_MAP.get(sYuser.getCompanyID()));
            List<RoleSelectResponse> roleList = new ArrayList<>();
            UserGroupQueryRequest mapQuery = new UserGroupQueryRequest();
            mapQuery.setUserId(Long.valueOf(sYuser.getId()));
            List<SYgroupH> roleEntitys = sYgroupHDao.queryUserRole(page, mapQuery);
            for (SYgroupH item : roleEntitys) {
                RoleSelectResponse role = new RoleSelectResponse();
                role.setRoleId(item.getId());
                role.setGroupName(item.getGroupName());
                roleList.add(role);
            }

            if (org.apache.commons.lang3.StringUtils.isNotEmpty(sYuser.getUserGroupID())) {
                userResponse.setRoleId(Long.valueOf(sYuser.getUserGroupID()));
                userResponse.setRoleName(ROLE_MAP.get(userResponse.getRoleId()));
                Long count = roleList.stream().filter(a -> a.getRoleId().equals(userResponse.getRoleId())).count();
                if (count == 0) {
                    RoleSelectResponse role = new RoleSelectResponse();
                    role.setRoleId(Math.toIntExact(userResponse.getRoleId()));
                    role.setGroupName(userResponse.getGroupName());
                    roleList.add(role);
                }
            }

            userResponse.setRoleList(roleList);

            userResponseList.add(userResponse);
        }
        log.debug("SYuserSvcImpl.doQueryPage entitys: {}", userResponseList);

        page.setTotal((int) total);
        page.setRecords(userResponseList);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);

        return result;
    }

    /**
     * 新增
     *
     * @param entitym
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doSave(SYuser entitym, RequestPojo requestPojo, UserSaveRequest map) {
        String userId = entitym.getUserID();
        log.debug("SYuserSvcImpl.doSave parameter: {}", entitym);
        Result result = new Result();
        //非空验证
//        if(StringUtils.isEmpty(requestPojo.getCustId()) || StringUtils.isEmpty(requestPojo.getStaffId())){
//            result.setResStatus(ResStatus.STATUS_WRONGFUL);
//            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
//            return result;
//        }


        //名称重复验证
//        HashMap mapData = new HashMap();
//        Page page = new Page();
//        mapData.put("CompanyID", entitym.getCompanyID());
//        String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" +requestPojo.getStaffId());
//        mapData.put("id", userRedisId);
//        List<SYuser> model = entitymDao.selectList(page, mapData);
//        if(model != null && model.size() > 0){
//            result.setResStatus(ResStatus.STATUS_EXISTENCE);
//            result.setResMsg(ResStatus.STATUS_EXISTENCE_MSG);
//            return result;
//        }
        // 用户上限验证
        Page pageData = new Page();
        Map<String, String> mapDataUser = new HashMap<>();
        mapDataUser.put("CompanyID", entitym.getCompanyID());
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                entitymDao.selectList(pageData, mapDataUser);
            }
        });
        if (total > 0) {
            TCompanyPurchase tCompanyPurchase = tCompanyPurchaseDao.queryByOrder(entitym.getCompanyID());
            if (tCompanyPurchase.getMaxUser() != null && total > tCompanyPurchase.getMaxUser()) {
                result.setResStatus(ResStatus.STATUS_OVER_USER);
                result.setResMsg(ResStatus.STATUS_OVER_USER_MSG);
                return result;
            }
        }

        //初始默认开启
        if (Objects.isNull(entitym.getVldFG())) {
            entitym.setVldFG("0");
        }

        entitym.setRegisteredPerson(requestPojo.getUserName());
        entitym.setRegisteredDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        entitym.setUpdatedPerson(requestPojo.getUserName());
        entitym.setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        if (StringUtils.isBlank(entitym.getUserGroupID())) {
            entitym.setUserGroupID(null);
        }
        if (StringUtils.isBlank(entitym.getDepID().trim())) {
            entitym.setDepID(null);
        }
        if (StringUtils.isBlank(entitym.getStationID().trim())) {
            entitym.setStationID(null);
        }
        try {
            entitym.setUserID(AESTool.encrypt(entitym.getUserID()));
            entitym.setPhoneNo(entitym.getUserID());
            entitym.setPassword(AESTool.encrypt(entitym.getPassword()));
        } catch (Exception e) {
            log.error("用户信息编码出错" + entitym.getUserID());
        }
        try {
            RLock rLock = redissonCommand.getFairLock(entitym.getUserID());
            if (rLock.tryLock()) {
                try {
                    boolean userExist = stringRedisTemplate.hasKey(RedisKeyConstant.USER_MODIFY_LOCK + ":" + userId);
                    if (userExist) {
                        result.setResStatus(ResStatus.STATUS_USER_EXIT);
                        result.setResMsg(ResStatus.STATUS_USER_EXIT_MSG);
                        return result;
                    }
                    int rec = entitymDao.insertRecords(entitym);

                    //保存角色
                    if (Objects.nonNull(map) && Objects.nonNull(map.getRoleList()) && map.getRoleList().size() > 0) {
                        UserGroupSaveRequest role = new UserGroupSaveRequest();
                        role.setUserId(Long.valueOf(entitym.getId()));
                        List<Long> userGroupIdList = new ArrayList<>();
                        for (RoleSelectResponse item : map.getRoleList()) {
                            userGroupIdList.add(Long.valueOf(item.getRoleId()));
                        }
                        role.setUserGroupIdList(userGroupIdList);

                        this.doSaveRole(role, requestPojo);
                    }

                    log.debug("新增数据返回 {}", rec);
                    result.setResStatus(ResStatus.STATUS_SUCCESS);
                    result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
                    if (rec > 0) {
                        if (Objects.nonNull(userId)) {
                            stringRedisTemplate.opsForValue().set(RedisKeyConstant.USER_MODIFY_LOCK + ":" + userId, entitym.getId() + "");
                        }
                        stringRedisTemplate.opsForValue().set(RedisKeyConstant.USER_MODIFY_LOCK + ":" + entitym.getEmpNo(), entitym.getId() + "");
                    }
                } catch (Exception e) {
                    log.error("Insert 用户 " + e.getLocalizedMessage());
                    result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
                    result.setResMsg("新增数据出错：" + e.getMessage());
                    return result;
                } finally {
                    rLock.unlock();
                }
            }
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(Long.valueOf(entitym.getId()));
                logSaveRequest.setRelatedType("sys");
                logSaveRequest.setLogTitle("新增用户");
                logSaveRequest.setLogContent("用户账户：" + AESTool.decrypt(entitym.getUserID()) + "用户名称:" + entitym.getName());
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("新增");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest, requestPojo);
            } catch (Exception e) {
                log.error(e.getMessage());
            }

        } catch (Exception e) {
            log.error("新增数据出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("新增数据出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }
        return result;

    }

    /**
     * 修改
     *
     * @param entitym
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doUpdate(SYuser entitym, RequestPojo requestPojo, UserSaveRequest map) {
        String userId = entitym.getUserID();
        log.debug("SYuserSvcImpl.doUpdate parameter: {}", entitym);
        Result result = new Result();
        //非空验证
//        if(StringUtils.isEmpty(requestPojo.getCustId()) || StringUtils.isEmpty(requestPojo.getStaffId())){
//            result.setResStatus(ResStatus.STATUS_WRONGFUL);
//            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
//            return result;
//        }

        entitym.setUpdatedPerson(requestPojo.getUserName());
        entitym.setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        if (entitym.getMailAddress() == null) {
            entitym.setMailAddress("");
        }
        try {
            entitym.setUserID(AESTool.encrypt(entitym.getUserID()));
            entitym.setPhoneNo(entitym.getUserID());
        } catch (Exception e) {
            log.error("用户信息编码出错" + entitym.getUserID());
        }
        try {
//            updateById(entitym);
            RLock rLock = redissonCommand.getFairLock(entitym.getUserID());
            if (rLock.tryLock()) {
                try {
                    boolean userExist = stringRedisTemplate.hasKey(RedisKeyConstant.USER_MODIFY_LOCK + ":" + userId);
                    if (userExist && !stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" + userId).equals(String.valueOf(entitym.getId()))) {
                        result.setResStatus(ResStatus.STATUS_USER_EXIT);
                        result.setResMsg(ResStatus.STATUS_USER_EXIT_MSG);
                        return result;
                    }
                    int rec = entitymDao.updateRecords(entitym);

                    //保存角色
                    if (Objects.nonNull(map) && Objects.nonNull(map.getRoleList()) && map.getRoleList().size() > 0) {
                        UserGroupSaveRequest role = new UserGroupSaveRequest();
                        role.setUserId(Long.valueOf(entitym.getId()));
                        List<Long> userGroupIdList = new ArrayList<>();
                        for (RoleSelectResponse item : map.getRoleList()) {
                            userGroupIdList.add(Long.valueOf(item.getRoleId()));
                        }
                        role.setUserGroupIdList(userGroupIdList);

                        this.doSaveRole(role, requestPojo);
                    }

                    if (rec > 0) {
                        if (Objects.nonNull(userId)) {
                            stringRedisTemplate.opsForValue().set(RedisKeyConstant.USER_MODIFY_LOCK + ":" + userId, entitym.getId() + "");
                        }
                        stringRedisTemplate.opsForValue().set(RedisKeyConstant.USER_MODIFY_LOCK + ":" + entitym.getEmpNo(), entitym.getId() + "");
                    }
                } catch (Exception e) {
                    log.error("Update 用户 " + e.getLocalizedMessage());
                } finally {
                    rLock.unlock();
                }
            }
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(Long.valueOf(entitym.getId()));
                logSaveRequest.setRelatedType("sys");
                logSaveRequest.setLogTitle("修改用户");
                logSaveRequest.setLogContent("用户账户：" + AESTool.decrypt(entitym.getUserID()) + "用户名称:" + entitym.getName());
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("修改");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest, requestPojo);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        } catch (Exception e) {
            log.error("修改数据出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("修改数据出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }
        return result;

    }

    /**
     * 删除
     *
     * @param map
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doDelete(UserQueryRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("SYuserSvcImpl.doDelete parameter: {}", map);
        //非空验证
//        String CompanyID = map.getCompanyID();
        String UserID = map.getUserID();

//        try {
//            CompanyID = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("CompanyID").toString();
//            UserID = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("UserID").toString();
//        }catch (Exception e){
//            log.debug("SYuserSvcImpl.doDelete get param parameter is not found.");
//        }

//        if(StringUtils.isEmpty(CompanyID) || StringUtils.isEmpty(UserID)){
//            result.setResStatus(ResStatus.STATUS_WRONGFUL);
//            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
//            return result;
//        }

        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();
//        mapData.put("CompanyID", requestPojo.getCustId());
        String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" + UserID);
        mapData.put("id", userRedisId);
        List<SYuser> entitym = entitymDao.selectList(page, mapData);
        if (entitym == null || entitym.size() == 0) {
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg("数据不存在");
            return result;
        }

        //不能删除自己的用户
        if (UserID.equals(requestPojo.getStaffId())) {
            result.setResStatus(ResStatus.STATUS_NO_DELETE_SELF);
            result.setResMsg(ResStatus.STATUS_NO_DELETE_SELF_MSG);
            return result;
        }
        //不能删除管理员
        TCompany tCompany = new TCompany();
        tCompany.setId(Integer.valueOf(requestPojo.getCustId()));
        TCompany companyData = tCompanyDao.selectOne(tCompany);
        if (org.apache.commons.lang3.StringUtils.isEmpty(companyData.getMainMobile())) {
            result.setResMsg(ResStatus.STATUS_ON_ADMIN_NULL_MSG);
            result.setResStatus(ResStatus.STATUS_ON_ADMIN_NULL);
            return result;
        }
        if (companyData.getMainMobile().equals(UserID)) {
            result.setResMsg(ResStatus.STATUS_NO_DELETE_ADMIN_MSG);
            result.setResStatus(ResStatus.STATUS_NO_DELETE_ADMIN);
            return result;
        }

        try {
            int rec = entitymDao.deleteByPk(Integer.valueOf(userRedisId));
            if (rec > 0) {
                stringRedisTemplate.delete(RedisKeyConstant.USER_MODIFY_LOCK + ":" + UserID);
                stringRedisTemplate.delete(RedisKeyConstant.USER_TOKEN + ":" + entitym.get(0).getCompanyID() + ":" + UserID);
                ;
            }
            log.debug("删除数据返回 {}", rec);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(Long.valueOf(userRedisId));
                logSaveRequest.setRelatedType("sys");
                logSaveRequest.setLogTitle("删除用户");
                logSaveRequest.setLogContent("用户账户：" + AESTool.decrypt(entitym.get(0).getUserID()) + "用户名称:" + entitym.get(0).getName());
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("删除");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest, requestPojo);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } catch (Exception e) {
            log.error("删除数据出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("删除出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }

        return result;

    }

    @Override
    public Result doSaveMap(UserSaveRequest map, RequestPojo requestPojo) {
        Result result = new Result<>();
        RLock rLock = redissonCommand.getFairLock(map.getUserID());
        if (rLock.tryLock()) {
            try {
                boolean userExist = stringRedisTemplate.hasKey(RedisKeyConstant.USER_MODIFY_LOCK + ":" + map.getUserID());
                if (userExist) {
                    result.setResStatus(ResStatus.STATUS_USER_EXIT);
                    result.setResMsg(ResStatus.STATUS_USER_EXIT_MSG);
                    return result;
                }
            } catch (Exception e) {

            } finally {
                rLock.unlock();
            }
        }
        String companyId = requestPojo.getCustId();
        if (org.apache.commons.lang3.StringUtils.isEmpty(map.getCompanyName())) {
            for (Map.Entry<String, String> entry : COMPANY_NAME_MAP.entrySet()) {
                if (entry.getValue().equals(requestPojo.getCustId())) {
                    map.setCompanyName(entry.getKey());
                    break;
                }
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(COMPANY_NAME_MAP.get(map.getCompanyName()))) {
            //判断是否为管理员
//                TCompany tCompany = new TCompany();
//                tCompany.setId(Integer.valueOf(COMPANY_MAP.get(map.getCompanyName())));
//                TCompany companyData = tCompanyDao.selectOne(tCompany);
//                if(!map.getUserID().equals(companyData.getMainMobile())){
//                    result.setResMsg(ResStatus.STATUS_ON_NOT_ADMIN);
//                    result.setResStatus(ResStatus.STATUS_ON_NOT_ADMIN_MSG);
//                    return result;
//                }
            //判断是否为Vj
            if (!requestPojo.getCustId().equals(COMPANY_ID)) {
//                    if(!requestPojo.getCustId().equals(COMPANY_MAP.get(map.getCompanyName()))){
//                        //不是自己公司的用户不能添加
//                        result.setResMsg(ResStatus.STATUS_ON_UPDATE_SELF);
//                        result.setResStatus(ResStatus.STATUS_ON_UPDATE_SELF_MSG);
//                        return result;
//                    }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(map.getRoleId())) {
                    SYgroupH sYgroupH = new SYgroupH();
                    sYgroupH.setId(Integer.valueOf(map.getRoleId()));
                    Map<String, String> mapData = new HashMap<>();
                    mapData.put("ID", map.getRoleId());
                    List<SYgroupH> sYgroupHList = sYgroupHDao.selectList(new Page<>(), mapData);

                    if (sYgroupHList.size() > 0) {
                        SYgroupH sYgroupHData = sYgroupHList.get(0);
                        if (!sYgroupHData.getCompanyID().equals(requestPojo.getCustId())) {
                            //不是vj  管理员只能分配自己的角色
                            result.setResStatus(ResStatus.STATUS_ON_UPDATE_SELF);
                            result.setResMsg(ResStatus.STATUS_ON_UPDATE_SELF_MSG);
                            return result;
                        }
                    } else {
                        result.setResMsg(ResStatus.STATUS_ROLE_NOT_EXIT);
                        result.setResStatus(ResStatus.STATUS_ROLE_NOT_EXIT_MSG);
                        return result;
                    }
                }
            } else {
                //是vj
                companyId = COMPANY_NAME_MAP.get(map.getCompanyName());
                if (org.apache.commons.lang3.StringUtils.isEmpty(companyId)) {
                    result.setResMsg(ResStatus.STATUS_ON_COMPANY_NOT_EXIST);
                    result.setResStatus(ResStatus.STATUS_ON_COMPANY_NOT_EXIST_MSG);
                    return result;
                }
            }
        } else {
            result.setResStatus(ResStatus.STATUS_ON_COMPANY_NOT_EXIST);
            result.setResMsg(ResStatus.STATUS_ON_COMPANY_NOT_EXIST_MSG);
            return result;
        }
        log.info("doSaveMap {}", map);
        SYuser entitym = new SYuser();
        BeanUtils.copyProperties(map, entitym);
        entitym.setCompanyID(companyId);
//        entitym.setUserGroupID(map.getRoleId());
        return this.doSave(entitym, requestPojo, map);
    }

    @Override
    public Result doUpdateMap(UserSaveRequest map, RequestPojo requestPojo) {
        Result result = new Result<>();
        RLock rLock = redissonCommand.getFairLock(map.getUserID());
        if (rLock.tryLock()) {
            try {
                boolean userExist = stringRedisTemplate.hasKey(RedisKeyConstant.USER_MODIFY_LOCK + ":" + map.getUserID());
                if (userExist) {
                    if (!stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" + map.getUserID()).equals(String.valueOf(map.getId()))) {
                        result.setResStatus(ResStatus.STATUS_USER_EXIT);
                        result.setResMsg(ResStatus.STATUS_USER_EXIT_MSG);
                        return result;
                    }
                }
            } catch (Exception e) {

            } finally {
                rLock.unlock();
            }
        }
        String companyId = requestPojo.getCustId();
        if (org.apache.commons.lang3.StringUtils.isEmpty(map.getCompanyName())) {
            for (Map.Entry<String, String> entry : COMPANY_NAME_MAP.entrySet()) {
                if (entry.getValue().equals(requestPojo.getCustId())) {
                    map.setCompanyName(entry.getKey());
                    break;
                }
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(COMPANY_NAME_MAP.get(map.getCompanyName()))) {
            //判断是否为Vj
            if (!requestPojo.getCustId().equals(COMPANY_ID)) {
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(map.getRoleId())) {
                    SYgroupH sYgroupH = new SYgroupH();
                    sYgroupH.setId(Integer.valueOf(map.getRoleId()));
                    Map<String, String> mapData = new HashMap<>();
                    mapData.put("id", map.getRoleId());
                    List<SYgroupH> sYgroupHList = sYgroupHDao.selectList(new Page<>(), mapData);

                    if (sYgroupHList.size() > 0) {
                        SYgroupH sYgroupHData = sYgroupHList.get(0);
                        if (!sYgroupHData.getCompanyID().equals(requestPojo.getCustId())) {
                            //不是vj  管理员只能分配自己的角色
                            result.setResMsg(ResStatus.STATUS_ON_UPDATE_SELF_MSG);
                            result.setResStatus(ResStatus.STATUS_ON_UPDATE_SELF);
                            return result;
                        }
                    } else {
                        result.setResMsg(ResStatus.STATUS_ROLE_NOT_EXIT);
                        result.setResStatus(ResStatus.STATUS_ROLE_NOT_EXIT_MSG);
                        return result;
                    }
                }
            } else {
                //是vj
                companyId = COMPANY_NAME_MAP.get(map.getCompanyName());
                if (org.apache.commons.lang3.StringUtils.isEmpty(companyId)) {
                    result.setResMsg(ResStatus.STATUS_ON_COMPANY_NOT_EXIST);
                    result.setResStatus(ResStatus.STATUS_ON_COMPANY_NOT_EXIST_MSG);
                    return result;
                }
            }

        } else {
            result.setResStatus(ResStatus.STATUS_ON_COMPANY_NOT_EXIST);
            result.setResMsg(ResStatus.STATUS_ON_COMPANY_NOT_EXIST_MSG);
            return result;
        }


        log.info("doUpdateMap {}", map);
        SYuser entitym = new SYuser();
        BeanUtils.copyProperties(map, entitym);
        entitym.setCompanyID(companyId);
//        entitym.setUserGroupID(map.getRoleId());
        entitym.setId(map.getId());

        return this.doUpdate(entitym, requestPojo, map);
    }

    @Override
    public Result doUpdatePass(UserResetPassRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("SYuserSvcImpl.doUpdatePass parameter: {}", map);
        //非空验证
        String CompanyID = COMPANY_ID;
        String UserID = null;

        String Password = map.getPassword();

        if (StringUtils.isEmpty(Password) || Objects.isNull(map.getId())) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();
        mapData.put("CompanyID", String.valueOf(CompanyID));
        String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" + requestPojo.getStaffId());

        mapData.put("id", String.valueOf(map.getId()));
        List<SYuser> entitym = entitymDao.selectList(page, mapData);
        if (entitym == null || entitym.size() == 0) {
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg(ResStatus.STATUS_UNAVAILABLE_MSG);
            return result;
        }

        try {
            SYuser user = entitym.get(0);
            user.setPassword(Password);
            user.setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));

            int rec = entitymDao.updateRecords(user);
            log.debug("更新密码返回 {}", rec);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        } catch (Exception e) {
            log.error("更新密码出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("更新密码出错：" + e.getMessage());
        }

        return result;
    }

    /**
     * 重置密码
     * Liby 2019-12-16
     *
     * @param map
     * @param requestPojo
     * @return
     */
    @Override
    public Result doResetPass(String map, RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("SYuserSvcImpl.doResetPass parameter: {}", map);
        //非空验证
        String CompanyID = ParamUtil.getParamfromObject(map, "CompanyID");
        String UserID = ParamUtil.getParamfromObject(map, "EmpNumber");
        String UserName = ParamUtil.getParamfromObject(map, "UserName");
        String Password = ParamUtil.getParamfromObject(map, "Password");
        String Default = ParamUtil.getParamfromObject(map, "Default");

        if (StringUtils.isEmpty(CompanyID) || StringUtils.isEmpty(UserID)) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();

        List<SYuser> entitym = entitymDao.selectList(page, mapData);
        try {
//            if(Objects.nonNull(entitym) && entitym.size() > 0){
//                int rec = entitymDao.deleteByPk(mapData);
//                log.debug("删除数据返回 {}",rec);
//            }
            SYuser user = new SYuser();
            if (Objects.nonNull(entitym) && entitym.size() > 0) {
                user = entitym.get(0);
            } else {
                user.setUserGroupID("GUEST");
            }
            user.setRegisteredPerson(requestPojo.getUserName());
            user.setRegisteredDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
            user.setUpdatedPerson(requestPojo.getUserName());
            user.setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
            user.setCompanyID(CompanyID);
            user.setUserID(UserID);
            user.setEmpNo(UserID);
            user.setName(UserName);
            if (Objects.nonNull(Default) && Default.equalsIgnoreCase("0")) {
                mapData = new HashMap<>();
                mapData.put("CompanyID", CompanyID);
                mapData.put("EmpNumber", UserID);
//                List<MSempInfoPojo> msentity = mSempInfoDao.selectList(page, mapData);
//                if(Objects.nonNull(msentity) && msentity.size() > 0){
//                    Password = msentity.get(0).getIDNum();
//                    if(Objects.isNull(Password)){
//                        Password = "111111";
//                    }else{
//                        Password = Password.substring(Password.length()-6, Password.length());
//                    }
//                }
            }
            user.setPassword(Password);

            int rec = 0;
            if (Objects.nonNull(entitym) && entitym.size() > 0) {
                rec = entitymDao.updateRecords(user);
                log.debug("更新数据 {}", rec);
            } else {
                rec = entitymDao.insertRecords(user);
                log.debug("插入数据 {}", rec);
            }
//            int rec = entitymDao.insertRecords(user);
//            log.debug("重置密码返回 {}",rec);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        } catch (Exception e) {
            log.error("重置密码出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("重置密码出错：" + e.getMessage());
        }

        return result;
    }

    @Override
    public Result doQueryAllRole(RequestPojo requestPojo) {
        Map<String, String> mapData = new HashMap<>();
        mapData.put("companyID", requestPojo.getCustId());
        List<RoleSelectResponse> roleSelectResponseList = new ArrayList<>();
        Page page = new Page<>();
        List<SYgroupH> sYgroupHList = sYgroupHDao.selectList(page, mapData);
        for (SYgroupH sYgroupH : sYgroupHList) {
            RoleSelectResponse response = new RoleSelectResponse();
            response.setRoleId(sYgroupH.getId());
            response.setGroupName(sYgroupH.getGroupName());
            roleSelectResponseList.add(response);
        }
        page.setRecords(roleSelectResponseList);
        Result result = new Result<>();
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);
        return result;
    }

    @Override
    public Result getUserList(UserQueryRequest map) {
        Result result = new Result();
        //分页查询
        Page page = new Page();
        log.debug("SYuserSvcImpl.doQueryPage parameter: {}", map);
        Map<String, String> mapData = new HashMap<>();

        String userRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" + map.getUserID());
        if (org.apache.commons.lang3.StringUtils.isEmpty(userRedisId)) {
            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
            page.setTotal(0);
            result.setResData(page);
            return result;
        }

        if (Objects.nonNull(map.getDeptID())) {
            mapData.put("DeptID", String.valueOf(map.getDeptID()));
        }

        List<SYuserInfo> entitys = entitymDao.selectListInfo(page, mapData);
        List<UserResponse> userResponseList = new ArrayList<>();
        for (SYuserInfo sYuser : entitys) {
            UserResponse userResponse = new UserResponse();
            BeanUtils.copyProperties(sYuser, userResponse);
            try {
                userResponse.setUserID(AESTool.decrypt(sYuser.getUserID()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            userResponse.setId(sYuser.getId());
            userResponse.setCompanyName(COMPANY_MAP.get(sYuser.getCompanyID()));
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(sYuser.getUserGroupID())) {
                userResponse.setRoleId(Long.valueOf(sYuser.getUserGroupID()));
                userResponse.setRoleName(ROLE_MAP.get(userResponse.getRoleId()));
            }
            userResponseList.add(userResponse);
        }
        log.debug("SYuserSvcImpl.doQueryPage entitys: {}", userResponseList);

        page.setRecords(userResponseList);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);

        return result;
    }

    //保存一个用户关联多个角色
    @Override
    public Result doSaveRole(UserGroupSaveRequest map, RequestPojo requestPojo) {
        log.debug("SYuserSvcImpl.doSaveRole parameter: {}", map);
        Result result = new Result();
        //分页查询
        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();

        if (Objects.isNull(map.getUserId()) || Objects.isNull(map.getUserGroupIdList())) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        SYuser user = entitymDao.selectById(map.getUserId());
        if (Objects.isNull(user)) {
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg(ResStatus.STATUS_UNAVAILABLE_MSG);
            return result;
        }

        int rec = sYusergroupDao.deleteByUserId(map.getUserId());
        for (Long item : map.getUserGroupIdList()) {
            SYusergroup userGroup = new SYusergroup();
            userGroup.setId(-1);
            userGroup.setUserId(map.getUserId());
            userGroup.setUserGroupId(item);
            rec = sYusergroupDao.insert(userGroup);
        }

        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

        return result;
    }

    //保存一个角色关联多个用户
    @Override
    public Result doSaveGroup(GroupUserSaveRequest map, RequestPojo requestPojo) {
        log.debug("SYuserSvcImpl.doSaveGroup parameter: {}", map);
        Result result = new Result();
        //分页查询
        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();

        if (Objects.isNull(map.getUserGroupId()) || Objects.isNull(map.getUserIdList())) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        SYgroupH usergroup = sYgroupHDao.selectById(map.getUserGroupId());
        if (Objects.isNull(usergroup)) {
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg(ResStatus.STATUS_UNAVAILABLE_MSG);
            return result;
        }

        int rec = sYusergroupDao.deleteByUserGroupId(map.getUserGroupId());
        for (Long item : map.getUserIdList()) {
            SYusergroup userGroup = new SYusergroup();
            userGroup.setId(-1);
            userGroup.setUserId(item);
            userGroup.setUserGroupId(map.getUserGroupId());
            rec = sYusergroupDao.insert(userGroup);
        }

        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

        return result;
    }

    @Override
    public Result doUpdatePassword(UserResetPassRequest map, RequestPojo requestPojo) throws Exception {
        Result result = new Result();
        log.debug("SYuserSvcImpl.doUpdatePass parameter: {}", map);
        //非空验证
        String CompanyID = COMPANY_ID;
        String UserID = null;
        String oldPassword = map.getOldPassword();
        String password = map.getPassword();
        SYuser sYuser = entitymDao.selectById(requestPojo.getSysId());
        String oldPasswordEc = AESTool.encrypt(oldPassword);
        if (!oldPasswordEc.equals(sYuser.getPassword())) {
            result.setResStatus("9999");
            result.setResMsg("旧密码不正确！");
            return result;
        }
        sYuser.setPassword(AESTool.encrypt(password));
        Integer updateResult = entitymDao.updateRecords(sYuser);
        log.debug("更新密码返回 {}", updateResult);
        if (updateResult >= 0) {
            Page page = new Page();
            page.setTotal(updateResult);
            result.setResData(page);
            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        } else {
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("更新失败！");
        }
        return result;
    }

    @Override
    public Result isFirstPws(RequestPojo requestPojo) {
        Result result = new Result();
        try {
            String firstPas = "Gssyxjs@.147";
            String firstPasEc = AESTool.encrypt(firstPas);
            SYuser sYuser = entitymDao.selectById(requestPojo.getSysId());
            Page page = new Page();
            if (firstPasEc.equals(sYuser.getPassword())) {
                page.setTotal(0);
            } else {
                page.setTotal(1);
            }
            result.setResData(page);
            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
