package cn.estsh.i3plus.core.apiservice.controller.busi;

import cn.estsh.i3plus.core.api.iservice.busi.IPersonnelService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysFileService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysRoleService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.EncryptTool;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.model.platform.UserDetailModel;
import cn.estsh.i3plus.pojo.model.platform.UserDetailPagerModel;
import cn.estsh.i3plus.pojo.model.platform.UserRolePagerModel;
import cn.estsh.i3plus.pojo.platform.bean.*;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Description :
 * @Reference :
 * @Author : Adair Peng
 * @CreateDate : 2018-12-24 14:02
 * @Modify:
 **/
@RestController
@Api(description = "系统用户管理服务")
@RequestMapping(PlatformConstWords.BASE_URL +"/personnel")
public class PersonnelController  extends CoreBaseController {

    public static final Logger LOGGER = LoggerFactory.getLogger(PersonnelController.class);

    @Autowired
    private IPersonnelService personnelService;

    @Autowired
    private ISysFileService fileService;

    @Autowired
    private ISysRoleService sysRoleService;

    @PostMapping(value="/user-detail/insert")
    @ApiOperation(value="添加用户信息",notes="返回内容添加用户信息")
    public ResultBean insertUserDetailModel(UserDetailModel model) {
        try {
            SysUser user = model.getSysUser();
            SysUserInfo info = model.getSysUserInfo();

            checkUserDetailModel(model, false);
            personnelService.checkSysUserPassword(model.getUserLoginPassword());
            personnelService.checkSysUserOnly(user);

            if(StringUtils.isBlank(info.getUserJoinDate())){
                info.setUserJoinDate(TimeTool.getToday());
            }

            info.setUserInfoStatus(CommonEnumUtil.USER_INFO_STATUS.INCUMBENT.getValue());
            info.setUserLoginNum(0);
            info.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
            ConvertBean.modelInitialize(info, AuthUtil.getSessionUser());

            user.setUserType(CommonEnumUtil.USER_TYPE.USER.getValue());
            user.setUserStatus(CommonEnumUtil.USER_STATUS.ENABLE.getValue());
            user.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
            user.setUserLoginNum(0);
            ConvertBean.modelInitialize(user, AuthUtil.getSessionUser());

            SysDepartment infoDepartment = personnelService.getSysDepartmentById(Long.parseLong(model.getInfoDepartmentId()));
            if(infoDepartment == null){
                ValidatorBean.checkNotNull(infoDepartment,"用户主部门不存在");
            }
            SysOrganize infoOrganize = personnelService.getSysOrganizeById(infoDepartment.getOrganizeId());
            SysPosition position = personnelService.getSysPositionById(Long.parseLong(model.getInfoPositionId()));
            if(infoDepartment == null){
                ValidatorBean.checkNotNull(position,"用户主岗位存在");
            }

            SysDepartment userDepartment = personnelService.getSysDepartmentById(Long.parseLong(model.getUserDepartmentId()));
            if(userDepartment == null){
                ValidatorBean.checkNotNull(userDepartment,"账号主部门不存在");
            }
            SysOrganize userOrganize = personnelService.getSysOrganizeById(userDepartment.getOrganizeId());

            info.setDepartmentId(infoDepartment.getId());
            info.setDepartmentNameRdd(infoDepartment.getName());
            info.setOrganizeId(infoOrganize.getId());
            info.setOrganizeNameRdd(infoOrganize.getName());
            info.setOrganizeCode(infoOrganize.getOrganizeCode());
            info.setPositionId(position.getId());
            info.setPositionNameRdd(position.getName());
            personnelService.saveSysUserInfo(info);

            user.setDepartmentId(userDepartment.getId());
            user.setDepartmentNameRdd(userDepartment.getName());
            user.setOrganizeId(userOrganize.getId());
            user.setOrganizeNameRdd(userOrganize.getName());
            user.setOrganizeCode(userOrganize.getOrganizeCode());
            user.setUserInfoId(info.getId());
            refreshSysUserPassword(user);
            personnelService.saveSysUser(user);

            info.setUserId(user.getId());
            personnelService.saveSysUserInfo(info);

            // 关系 刷新
            refreshRef(user, info, model);

            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value="/user-detail/update")
    @ApiOperation(value="添加用户信息",notes="返回内容添加用户信息")
    public ResultBean updateUserDetailModel(UserDetailModel model) {
        try {
            SysUser user = model.getSysUser();
            SysUserInfo info = model.getSysUserInfo();

            checkUserDetailModel(model, true);
            personnelService.checkSysUserPassword(model.getUserLoginPassword());
            personnelService.checkSysUserOnly(user);

            SysUserInfo userInfo = personnelService.getSysUserInfoById(info.getId());

            SysDepartment infoDepartment = personnelService.getSysDepartmentById(Long.parseLong(model.getInfoDepartmentId()));
            if(infoDepartment == null){
                ValidatorBean.checkNotNull(infoDepartment,"用户主部门不存在");
            }
            SysOrganize infoOrganize = personnelService.getSysOrganizeById(infoDepartment.getOrganizeId());
            SysPosition position = personnelService.getSysPositionById(Long.parseLong(model.getInfoPositionId()));
            if(infoDepartment == null){
                ValidatorBean.checkNotNull(position,"用户主岗位存在");
            }

            SysDepartment userDepartment = personnelService.getSysDepartmentById(Long.parseLong(model.getUserDepartmentId()));
            if(userDepartment == null){
                ValidatorBean.checkNotNull(userDepartment,"账号主部门不存在");
            }
            SysOrganize userOrganize = personnelService.getSysOrganizeById(userDepartment.getOrganizeId());

            userInfo.setDepartmentId(infoDepartment.getId());
            userInfo.setDepartmentNameRdd(infoDepartment.getName());
            userInfo.setOrganizeId(infoOrganize.getId());
            userInfo.setOrganizeNameRdd(infoOrganize.getName());
            userInfo.setOrganizeCode(infoOrganize.getOrganizeCode());
            userInfo.setPositionId(position.getId());
            userInfo.setPositionNameRdd(position.getName());
            userInfo.setName(info.getName());
            userInfo.setUserEmpNo(info.getUserEmpNo());
            userInfo.setUserJoinDate(info.getUserJoinDate());
            userInfo.setUserResignationDate(info.getUserResignationDate());
            userInfo.setUserCardType(info.getUserCardType());
            userInfo.setUserCardNumber(info.getUserCardNumber());
            userInfo.setUserSchool(info.getUserSchool());
            userInfo.setUserSchoolProfession(info.getUserSchoolProfession());
            userInfo.setUserSchoolLeaveDate(info.getUserSchoolLeaveDate());
            userInfo.setUserSchoolEducation(info.getUserSchoolEducation());
            userInfo.setUserSex(info.getUserSex());
            userInfo.setUserBirthplace(info.getUserBirthplace());
            userInfo.setUserRace(info.getUserRace());
            userInfo.setUserMarriage(info.getUserMarriage());
            userInfo.setUserEmergencyContact(info.getUserEmergencyContact());
            userInfo.setUserEmergencyPhone(info.getUserEmergencyPhone());
            userInfo.setUserFamilyAddress(info.getUserFamilyAddress());
            userInfo.setUserBornDate(info.getUserBornDate());
            userInfo.setUserHobby(info.getUserHobby());
            userInfo.setUserPoliticalStatus(info.getUserPoliticalStatus());
            userInfo.setUserGrade(info.getUserGrade());
            userInfo.setUserEmployeeType(info.getUserEmployeeType());

            user.setDepartmentId(userDepartment.getId());
            user.setDepartmentNameRdd(userDepartment.getName());
            user.setOrganizeId(userOrganize.getId());
            user.setOrganizeNameRdd(userOrganize.getName());

            // 关系 刷新
            refreshRef(user, userInfo, model);
            // 更新 密码
            refreshSysUserPassword(user);

            personnelService.saveSysUser(user);
            personnelService.saveSysUserInfo(userInfo);

            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value="/user/update")
    @ApiOperation(value="添加用户信息",notes="返回内容添加用户信息")
    public ResultBean updateUserModel(UserDetailModel model) {
        try {
            checkUserModel(model);
            SysUser user = personnelService.getSysUserById(Long.parseLong(model.getUserId()));
            initUser(model,user);
            personnelService.checkSysUserPassword(model.getUserLoginPassword());
            personnelService.checkSysUserOnly(user);

            SysDepartment userDepartment = personnelService.getSysDepartmentById(Long.parseLong(model.getUserDepartmentId()));
            if(userDepartment == null){
                ValidatorBean.checkNotNull(userDepartment,"账号主部门不存在");
            }
            SysOrganize userOrganize = personnelService.getSysOrganizeById(userDepartment.getOrganizeId());

            user.setDepartmentId(userDepartment.getId());
            user.setDepartmentNameRdd(userDepartment.getName());
            user.setOrganizeId(userOrganize.getId());
            user.setOrganizeNameRdd(userOrganize.getName());

            // 关系 刷新
            refreshRef(user, null, model);
            personnelService.saveSysUser(user);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/user-info/get-detail/{id}")
    @ApiOperation(value = "获取用户信息", notes = "查询根据ID查询用户相关所有信息")
    public ResultBean getUserInfoById(@PathVariable("id") String id){
        try {
            // 数据校验
            ValidatorBean.checkNotNull(id, "用户id 不能为空");
            Map<String,Object> resultMap = new HashMap<>();


            SysUserInfo info = personnelService.getSysUserInfoById(Long.parseLong(id));
            ValidatorBean.checkNotNull(info,"用户不存在");
            SysUser user = personnelService.getSysUserById(info.getUserId());
            ValidatorBean.checkNotNull(user,"账号不存在");

            List<SysRefUserInfoDepartment> refUserInfoDepartmentList = personnelService.findSysRefUserInfoDepartmentById(info.getId());
            List<SysRefUserPosition> refUserPositionList = personnelService.findSysRefUserPositionById(info.getId());
            List<SysRefUserDepartment> refUserDepartmentList = personnelService.findSysRefUserDepartmentById(user.getId());
            List<SysRefUserRole> refUserRoleList = personnelService.findSysRefUserRoleById(user.getId());
            SysFile image = info.getUserImageId() != null ? fileService.getSysFileById(info.getUserImageId()) : null;

            resultMap.put("user",user);
            resultMap.put("refUserInfoDepartmentList",refUserInfoDepartmentList);
            resultMap.put("refUserPositionList",refUserPositionList);
            resultMap.put("refUserDepartmentList",refUserDepartmentList);
            resultMap.put("refUserRoleList",refUserRoleList);
            resultMap.put("image",image);

            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultMap(resultMap);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/user/get-detail/{id}")
    @ApiOperation(value = "获取账号信息", notes = "查询根据ID查询账号相关所有信息")
    public ResultBean getUserById(@PathVariable("id") String id){
        try {
            // 数据校验
            ValidatorBean.checkNotNull(id, "用户id 不能为空");
            Map<String,Object> resultMap = new HashMap<>();


            SysUser user = personnelService.getSysUserById(Long.parseLong(id));

            List<SysRefUserDepartment> refUserInfoDepartmentList = personnelService.findSysRefUserDepartmentById(user.getId());
            List<SysRefUserRole> refUserRoleList = personnelService.findSysRefUserRoleById(user.getId());

            resultMap.put("refUserDepartmentList",refUserInfoDepartmentList);
            resultMap.put("refUserRoleList",refUserRoleList);

            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultMap(resultMap);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ResultBean.fail(e).setCode(ImppExceptionEnum.SYSTEM_EXCEPTION.getCode());
        }
    }

    @DeleteMapping(value="/user-info/delete/{id}")
    @ApiOperation(value="删除用户信息",notes="根据用户信息id删除信息")
    public ResultBean deleteSysUserInfo(@PathVariable("id") String id){
        try {
            //条件验证
            ValidatorBean.checkNotNull(id,"id为空");

            SysUserInfo info = personnelService.getSysUserInfoById(Long.parseLong(id));
            if(info != null){
                personnelService.deleteSysUserInfo(new Long[]{info.getId()},getSessionUser().getUserName());
                personnelService.deleteSysUser(new Long[]{info.getUserId()},getSessionUser().getUserName());

                return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else{
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/user-info/batch-delete")
    @ApiOperation(value = "根据id批量删除", notes = "根据id批量删除")
    public ResultBean deleteSysUserInfoByIds(String[] ids){
        try{
            ids = ConvertBean.modelSafeArrayNumber(ids,true);
            if(ids.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的用户信息。")
                        .build();
            }

            List<SysUserInfo> list = personnelService.findSysUserInfoByIds(StringTool.getArrayLong(ids));

            if(list != null && list.size() > 0){
                Long[] infoIds = new Long[list.size()];
                Long[] userIds = new Long[list.size()];

                for (int i = 0; i < list.size(); i++) {
                    infoIds[i] = list.get(i).getId();
                    userIds[i] = list.get(i).getUserId();
                }

                personnelService.deleteSysUserInfo(infoIds,getSessionUser().getUserName());
                personnelService.deleteSysUser(userIds,getSessionUser().getUserName());

                return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else{
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value="/user/delete/{id}")
    @ApiOperation(value="删除账号信息",notes="根据账号信息id删除信息")
    public ResultBean deleteSysUser(@PathVariable("id") String id){
        try {
            //条件验证
            ValidatorBean.checkNotNull(id,"id为空");

            SysUser user = personnelService.getSysUserById(Long.parseLong(id));
            if(user != null){
                personnelService.deleteSysUserInfo(new Long[]{user.getUserInfoId()},getSessionUser().getUserName());
                personnelService.deleteSysUser(new Long[]{user.getId()},getSessionUser().getUserName());

                return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else{
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ResultBean.fail(e).setCode(ImppExceptionEnum.BUSINESS_EXCEPTION_DATA_ERROR.getCode());
        }
    }

    @DeleteMapping(value = "/user/batch-delete")
    @ApiOperation(value = "根据id批量删除", notes = "根据id批量删除")
    public ResultBean deleteSysUserByIds(String[] ids){
        try{
            ids = ConvertBean.modelSafeArrayNumber(ids,true);
            if(ids.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的用户信息。")
                        .build();
            }

            List<SysUser> list = personnelService.findSysUserByIds(StringTool.getArrayLong(ids));

            if(list != null && list.size() > 0){
                Long[] infoIds = new Long[list.size()];
                Long[] userIds = new Long[list.size()];

                for (int i = 0; i < list.size(); i++) {
                    infoIds[i] = list.get(i).getUserInfoId();
                    userIds[i] = list.get(i).getId();
                }

                personnelService.deleteSysUserInfo(infoIds,getSessionUser().getUserName());
                personnelService.deleteSysUser(userIds,getSessionUser().getUserName());

                return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else{
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/query-ref-department")
    @ApiOperation(value = "查询角色的所有角色权限关系", notes = "查询角色的所有角色权限关系")
    public ResultBean queryRefDepartment(@RequestBody UserDetailModel model) {
        try {
            List<Long> idList = new ArrayList<>();
            model.setUserDepartmentIdList(new ArrayList<String>(Arrays.asList(new String[]{"1072037153732694016"})));

            List<SysRefUserDepartment> refs = personnelService.querySysRefUserDepartmentByUserDetailModel(model);
            if(refs != null && refs.size() > 0){
                for (SysRefUserDepartment ref : refs) {
                    idList.add(ref.getUserId());
                }
            }

            List<SysUser> result = personnelService.querySysUserByUserDetailModelOrIds(model, idList);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(result);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/pager/query-ref-department")
    @ApiOperation(value = "查询角色的所有角色权限关系", notes = "查询角色的所有角色权限关系")
    public ResultBean queryPagerRefDepartment(@RequestBody UserDetailPagerModel model) {
        try {
            List<Long> idList = new ArrayList<>();
            List<SysRefUserDepartment> refs = personnelService.querySysRefUserDepartmentByUserDetailModel(model.getUserDetailModel());
            if(refs != null && refs.size() > 0){
                for (SysRefUserDepartment ref : refs) {
                    idList.add(ref.getUserId());
                }
            }

            ListPager<SysUser> result = personnelService.querySysUserPagerByUserDetailModelOrIds(model.getUserDetailModel(), model.getPager(), idList);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultObject(result);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PostMapping(value = "/role/get-role-list")
    @ApiOperation(value = "根据条件分页查询用户角色信息", notes = "根据条件分页查询用户角色信息")
    public ResultBean queryPagerByRoleInfo(@RequestBody UserRolePagerModel model){
        try {
            ListPager<SysRole> listPager = sysRoleService.querySysRole(model.getSysRole(), model.getPager());
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setListPager(listPager);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ResultBean.fail(e).setCode(ImppExceptionEnum.SYSTEM_EXCEPTION.getCode());
        }
    }

    @PostMapping(value = "/pager/get-user-list")
    @ApiOperation(value = "根据条件分页查询用户信息", notes = "根据条件分页查询用户信息")
    public ResultBean queryPagerByUserInfo(@RequestBody UserDetailPagerModel model){
        try {
            ListPager<SysUserInfo> listPager = personnelService.querySysUserInfo(model.getUserDetailModel(), model.getPager());
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setListPager(listPager);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ResultBean.fail(e).setCode(ImppExceptionEnum.SYSTEM_EXCEPTION.getCode());
        }
    }

    /**
     * 数据必填校验
     * @param model
     * @param isCheckId
     * @throws Exception
     */
    public void checkUserDetailModel(UserDetailModel model,boolean isCheckId)throws Exception{
        if(isCheckId){
            ValidatorBean.beginValid(model)
                    .notNull("userInfoId", model.getUserInfoId())
                    .notNull("userId", model.getUserId());
        }else {
            ValidatorBean.beginValid(model).notNull("userLoginPassword", model.getUserLoginPassword());
        }

        ValidatorBean.beginValid(model)
                .notNull("infoName", model.getInfoName())
                .notNull("infoEmpNo", model.getInfoEmpNo())
                .notNull("infoPositionId", model.getInfoPositionId())
                .notNull("infoDepartmentId", model.getInfoDepartmentId())
                .notNull("userDepartmentId", model.getUserDepartmentId())
                .notNull("userLoginName", model.getUserLoginName())
                .notNull("userEmail", model.getUserEmail())
                .notNull("userPhone", model.getUserPhone());
    }

    /**
     * 数据必填校验
     * @param model
     * @throws Exception
     */
    public void checkUserModel(UserDetailModel model)throws Exception{
        ValidatorBean.beginValid(model)
                .notNull("userInfoId", model.getUserInfoId())
                .notNull("userId", model.getUserId())
                .notNull("infoName", model.getInfoName())
                .notNull("infoEmpNo", model.getInfoEmpNo())
                .notNull("userDepartmentId", model.getUserDepartmentId())
                .notNull("userLoginName", model.getUserLoginName())
                .notNull("userEmail", model.getUserEmail())
                .notNull("userPhone", model.getUserPhone());
    }

    /**
     * 用户信息初始化
     * @param model
     * @param user
     * @throws Exception
     */
    public void initUser(UserDetailModel model ,SysUser user)throws Exception{
        if(user != null && model != null){
            user.setUserLoginName(model.getUserLoginName());
            user.setDepartmentId(Long.parseLong(model.getUserDepartmentId()));
            user.setUserEmail(model.getUserEmail());
            user.setUserPhone(model.getUserPhone());

            if(!StringUtils.isAnyBlank(model.getUserLoginPassword())){   // 使用新密码
                user.setUserLoginPassword(EncryptTool.hexMD5(model.getUserLoginPassword()));
            }
        }
    }

    /**
     * 关系刷新
     * @param user
     * @param info
     * @param model
     */
    public void refreshRef(SysUser user,SysUserInfo info,UserDetailModel model){
        if(user != null){
            // 刷新账号 部门关系
            personnelService.refreshRefSysUserDepartment(user.getId(), StringTool.getArrayLong(model.getUserDepartmentIdList()));
            // 刷新账号 角色关系
            personnelService.refreshRefSysUserRole(user.getId(),StringTool.getArrayLong(model.getUserRoleIdList()));
        }

        if(info != null){
            // 刷新用户 部门关系
            personnelService.refreshUpdateRefSysUserInfoDepartment(info.getId(),StringTool.getArrayLong(model.getInfoDepartmentIdList()));
            // 刷新用户 岗位关系
            personnelService.refreshRefSysUserInfoPosition(info.getId(),StringTool.getArrayLong(model.getInfoPositionIdList()));
        }
    }

    /**
     * 更新用户密码
     * @param user
     */
    public void refreshSysUserPassword(SysUser user)throws Exception{
        if(user != null){
            if(user.getId() != null){ // 更新密码
                if(!StringUtils.isAnyBlank(user.getUserLoginPassword())){   // 使用新密码
                    user.setUserLoginPassword(EncryptTool.hexMD5(user.getUserLoginPassword().trim()));
                }else{  //使用旧密码
                    SysUser sysUser = personnelService.getSysUserById(user.getId());
                    user.setUserLoginPassword(sysUser.getUserLoginPassword());
                }
            }else { // 创建密码
                user.setUserLoginPassword(EncryptTool.hexMD5(user.getUserLoginPassword().trim()));
            }
        }
    }
}
