package com.zcloud.controller.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.EmployeeData;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.Dictionaries;
import com.zcloud.entity.system.Role;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.check.CheckRecordService;
import com.zcloud.service.check.ListManagerService;
import com.zcloud.service.corp.CorpInfoService;
import com.zcloud.service.notice.NoticeManagementService;
import com.zcloud.service.statistics.ListStatisticsService;
import com.zcloud.service.system.*;
import com.zcloud.util.*;
import net.sf.json.JSONArray;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 说明：系统用户处理类
 * 作者：luoxiaobao
 * 官网：www.qdkjchina.com
 */
@Controller
@RequestMapping("/user")
public class UsersController extends BaseController {

    @Autowired
    private UsersService usersService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UeditorService ueditorService;
    @Autowired
    private NoticeManagementService noticemanagementService;
    @Autowired
    private FHlogService FHLOG;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PostService postService;
    @Autowired
    private CorpInfoService corpInfoService;
    @Resource
    private OfficeService officeService;
    @Autowired
    private ListManagerService listManagerService;
    @Autowired
    private ListStatisticsService listStatisticsService;
    @Autowired
    private CheckRecordService checkrecordService;
    @Autowired
    private DictionariesService dictionariesService;
    @Autowired
    private DictionariesCorpService dictionariesCorpService;
    @Autowired
    private ImgFilesService imgfilesService;

    /**
     * 根据卡号找人信息
     *
     * @param page
     * @return
     * @throws Exception
     */
    @RequestMapping("/getUserByCardNo")
    @ResponseBody
    public Object getUserByCardNo() {
        PageData pageData = getPageData();
        pageData.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        return ReturnMap.ok().put("pd", usersService.getUserByCardNo(pageData));
    }

    /**
     * 用户列表
     *
     * @param page
     * @return
     * @throws Exception
     */
    @RequestMapping("/list")
    // @RequiresPermissions("user:list")
    @ResponseBody
    @LogAnno(menuType = "教育培训", menuServer = "签字信息管理", instructionsOperate = "签字信息管理", instructionsType = "用户列表")
    public Object listUsers(Page page) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();

        /*检索条件*/
        String ROLE_ID = pd.getString("ROLE_ID");                        //角色ID
        String KEYWORDS = pd.getString("KEYWORDS");                        //关键词检索条件
        if (Tools.notEmpty(KEYWORDS)) pd.put("KEYWORDS", KEYWORDS.trim());
        String DEPARTMENT_ID = pd.getString("DEPARTMENT_ID");                        //关键词检索条件
        if (Tools.notEmpty(DEPARTMENT_ID)) pd.put("DEPARTMENT_ID", DEPARTMENT_ID.trim());
        String STARTTIME = pd.getString("STARTTIME");                    //开始时间
        String ENDTIME = pd.getString("ENDTIME");                        //结束时间
        if (Tools.notEmpty(STARTTIME)) pd.put("STARTTIME", STARTTIME + " 00:00:00");
        if (Tools.notEmpty(ENDTIME)) pd.put("ENDTIME", ENDTIME + " 00:00:00");
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        page.setPd(pd);
        pd.put("VIPLEVEL", Jurisdiction.getVIPLEVEL());
        List<PageData> userList = usersService.userlistPage(page);        //列出用户列表
        pd.put("ROLE_ID", Jurisdiction.getVIPLEVEL());
        List<Role> roleList = roleService.listAllRolesByPId(pd);        //列出所有系统用户角色

        map.put("userList", userList);
        map.put("roleList", roleList);
        map.put("ROLE_ID", ROLE_ID);
        map.put("page", page);
        map.put("pd", pd);

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

    /**
     * 用户列表(多选列表使用)
     *
     * @param page
     * @return
     * @throws Exception
     */
    @RequestMapping("/listSelect")
    @ResponseBody
    @LogAnno(menuType = "综合管理", menuServer = "特种设备", instructionsOperate = "设备管理", instructionsType = "用户列表")
    public Object listSelect(Page page) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();

        /*检索条件*/
        String ROLE_ID = pd.getString("ROLE_ID");                        //角色ID
        String KEYWORDS = pd.getString("KEYWORDS");                        //关键词检索条件
        if (Tools.notEmpty(KEYWORDS)) pd.put("KEYWORDS", KEYWORDS.trim());
        String DEPARTMENT_ID = pd.getString("DEPARTMENT_ID");                        //关键词检索条件
        if (Tools.notEmpty(DEPARTMENT_ID)) pd.put("DEPARTMENT_ID", DEPARTMENT_ID.trim());
        String STARTTIME = pd.getString("STARTTIME");                    //开始时间
        String ENDTIME = pd.getString("ENDTIME");                        //结束时间
        if (Tools.notEmpty(STARTTIME)) pd.put("STARTTIME", STARTTIME + " 00:00:00");
        if (Tools.notEmpty(ENDTIME)) pd.put("ENDTIME", ENDTIME + " 00:00:00");
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        page.setPd(pd);
        List<PageData> userList = usersService.userSelectlistPage(page);        //列出用户列表
        map.put("userList", userList);
        map.put("page", page);
        map.put("pd", pd);

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


    /**
     * 去新增用户页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goAddUser")
    @ResponseBody
    @LogAnno(menuType = "双重预防", menuServer = "企业管理", instructionsOperate = "用户管理", instructionsType = "去新增用户页面")
    public Object goAddUser() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("ROLE_ID", Jurisdiction.getVIPLEVEL());
        List<Role> roleList = roleService.listAllRolesByPId(pd);        //列出所有系统用户角色
        PageData cpd = new PageData();
        cpd = this.getPageData();
        cpd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        int allUser = usersService.getUserCount(cpd);
        cpd = corpInfoService.findNumById(cpd);
        map.put("USERS_NUM", cpd);
        map.put("allUser", allUser);
        map.put("roleList", roleList);


        //获取部门下拉树
//		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//		String ZDEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//		ZDEPARTMENT_ID = "".equals(ZDEPARTMENT_ID)?"0":ZDEPARTMENT_ID;
//		PageData dept = new PageData();
//		dept.put("DEPARTMENT_ID",ZDEPARTMENT_ID);
//		dept=this.departmentService.findById(dept);


        List<PageData> zdepartmentPdList = new ArrayList<PageData>();
        PageData dept = new PageData();
        dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        dept = this.departmentService.findByCorpId(dept);
        String ZDEPARTMENT_ID = dept.getString("DEPARTMENT_ID");

        PageData node = new PageData();
        node.put("id", dept.get("DEPARTMENT_ID"));
        node.put("parentId", dept.get("PARENT_ID"));
        node.put("name", dept.get("NAME"));
        node.put("icon", "../../../assets/images/user.gif");
        zdepartmentPdList.add(node);
        JSONArray arr = JSONArray.fromObject(departmentService.listAllDepartmentToSelect(ZDEPARTMENT_ID, zdepartmentPdList));
        map.put("zTreeNodes", (null == arr ? "" : "{\"treeNodes\":" + arr.toString() + "}"));

        //获取岗位下拉
        PageData post = new PageData();
        post.put("DEPARTMENT_ID", ZDEPARTMENT_ID);
        post.put("STATUS", 0);
        List<PageData> postList = this.postService.listAll(post);
        map.put("postList", postList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 去修改用户页面(从系统用户页面修改)
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goEditUser")
    @ResponseBody
    @LogAnno(menuType = "教育培训", menuServer = "档案管理", instructionsOperate = "一人一档", instructionsType = "去修改用户页面(从系统用户页面修改)")
    public Object goEditUser() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        if ("1".equals(pd.getString("USER_ID"))) {
            return null;
        }        //不能修改admin用户
        pd.put("ROLE_ID", Jurisdiction.getVIPLEVEL());
        List<Role> roleList = roleService.listAllRolesByPId(pd);    //列出所有系统用户角色
        pd.put("PARENT_ID", Jurisdiction.getVIPLEVEL());
        pd.put("ISMAIN", "0");
        List<PageData> userlist = roleService.findByPid(pd);
//		//获取部门下拉树
//		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//		String ZDEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//		ZDEPARTMENT_ID = "".equals(ZDEPARTMENT_ID)?"0":ZDEPARTMENT_ID;
//		PageData dept = new PageData();
//		dept.put("DEPARTMENT_ID",ZDEPARTMENT_ID);
//		dept=this.departmentService.findById(dept);
        List<PageData> zdepartmentPdList = new ArrayList<PageData>();
        PageData dept = new PageData();
        dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        dept = this.departmentService.findByCorpId(dept);
        String ZDEPARTMENT_ID = dept.getString("DEPARTMENT_ID");

        PageData node = new PageData();
        node.put("id", dept.get("DEPARTMENT_ID"));
        node.put("parentId", dept.get("PARENT_ID"));
        node.put("name", dept.get("NAME"));
        node.put("icon", "../../../assets/images/user.gif");
        zdepartmentPdList.add(node);
        JSONArray arr = JSONArray.fromObject(departmentService.listAllDepartmentToSelect(ZDEPARTMENT_ID, zdepartmentPdList));
        map.put("zTreeNodes", (null == arr ? "" : "{\"treeNodes\":" + arr.toString() + "}"));
        String depname = null == dept ? "请选择" : dept.getString("NAME");
        map.put("depname", null == depname ? "请选择" : depname);
        pd = usersService.findById(pd);                                //根据ID读取
        pd.put("ISSTUDENT", Boolean.valueOf(pd.getString("ISSTUDENT")));
        PageData shiftDutyPeriod = new PageData();
        shiftDutyPeriod.put("DURATION", pd.get("DURATION"));
        shiftDutyPeriod.put("WORKSTATUS", pd.get("WORKSTATUS"));
        shiftDutyPeriod.put("WORKPERIOD", pd.get("WORKPERIOD"));

        String ROLE_IDS = pd.getString("ROLE_IDS");                    //副职角色ID
        if (Tools.notEmpty(ROLE_IDS)) {
            String arryROLE_ID[] = ROLE_IDS.split(",");
            for (int i = 0; i < roleList.size(); i++) {
                Role role = roleList.get(i);
                String roleId = role.getROLE_ID();
                for (int n = 0; n < arryROLE_ID.length; n++) {
                    if (arryROLE_ID[n].equals(roleId)) {
                        role.setRIGHTS("1");    //此时的目的是为了修改用户信息上，能看到副职角色都有哪些
                        break;
                    }
                }
            }
        }

        PageData userInfo = userInfoService.findById(pd); // 添加 用户详情 CERTIFICATE_INFORMATION 证书信息
        List<PageData> userCerList = new ArrayList<PageData>();
        if (null != userInfo) {
            PageData userCerPd = new PageData();
            userCerPd.put("TYPE", "18");
            userCerPd.put("FOREIGN_KEY", pd.get("USER_ID"));
            userCerList = imgfilesService.listAll(userCerPd);
            pd.putAll(userInfo);
        }
        //获取岗位下拉
        PageData post = new PageData();
        post.put("DEPARTMENT_ID", ZDEPARTMENT_ID);
        post.put("STATUS", 0);
        List<PageData> postList = this.postService.listAll(post);
        map.put("postList", postList);
        map.put("pd", pd);
        map.put("userList", userlist);
        map.put("period", shiftDutyPeriod);
        map.put("periodStr", shiftDutyPeriod.getString("DURATION") + ',' + shiftDutyPeriod.getString("WORKSTATUS") + ',' + shiftDutyPeriod.getString("WORKPERIOD"));
        map.put("userCerList", userCerList);
        map.put("roleList", roleList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 去修改用户页面(个人资料修改)
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goEditMyInfo")
    @ResponseBody
    public Object goEditMyInfo() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("ROLE_ID", Jurisdiction.getVIPLEVEL());
        List<Role> roleList = roleService.listAllRolesByPId(pd);    //列出所有系统用户角色
        pd.put("USERNAME", Jurisdiction.getUsername());
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        pd = usersService.findByUsername(pd);                        //根据用户名读取
        //获取部门下拉树
//		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//		String ZDEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//		ZDEPARTMENT_ID = "".equals(ZDEPARTMENT_ID)?"0":ZDEPARTMENT_ID;
//		PageData dept = new PageData();
//		dept.put("DEPARTMENT_ID",ZDEPARTMENT_ID);
//		dept=this.departmentService.findById(dept);
        //获取部门下拉树
        List<PageData> zdepartmentPdList = new ArrayList<PageData>();
        PageData dept = new PageData();
        dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        dept = this.departmentService.findByCorpId(dept);
        String ZDEPARTMENT_ID = dept.getString("DEPARTMENT_ID");

        PageData deptname = departmentService.findById(pd);
        PageData node = new PageData();
        node.put("id", dept.get("DEPARTMENT_ID"));
        node.put("parentId", dept.get("PARENT_ID"));
        node.put("name", dept.get("NAME"));
        node.put("icon", "../../../assets/images/user.gif");
        zdepartmentPdList.add(node);
        JSONArray arr = JSONArray.fromObject(departmentService.listAllDepartmentToSelect(ZDEPARTMENT_ID, zdepartmentPdList));
        map.put("zTreeNodes", (null == arr ? "" : "{\"treeNodes\":" + arr.toString() + "}"));

        String depname = null == dept ? "请选择" : dept.getString("NAME");
        map.put("depname", null == depname ? "请选择" : depname);

        //获取岗位下拉
        PageData post = new PageData();
        post.put("DEPARTMENT_ID", ZDEPARTMENT_ID);
        post.put("STATUS", 0);
        List<PageData> postList = this.postService.listAll(post);
        map.put("postList", postList);
        map.put("pd", pd);
        map.put("deptname", deptname.getString("NAME"));//获取当前登录的人部门名称
        map.put("roleList", roleList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 获取隐患确认人
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/getHiddenConfirm")
    @ResponseBody
    public Object getHiddenConfirm() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        pd.put("IS_HAZARDCONFIRMER", "1");
        List<PageData> userList = usersService.listAllUser(pd);
        map.put("userList", userList);
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * 修改用户(系统用户列表修改)
     */
    @RequestMapping(value = "/editUser")
    // @RequiresPermissions("user:edit")
    @ResponseBody
    @LogAnno(menuType = "双重预防", menuServer = "企业管理", instructionsOperate = "用户管理", instructionsType = "修改用户(系统用户列表修改)")
    public Object editUser() throws Exception {
        Map<String, Object> map = new HashMap<>();
        String errInfo = "success";
        PageData pd = this.getPageData();

        // 检查是否需要更新学习者类别
        if ("input".equals(pd.getString("LEARNERCATEGORYSTATUS"))) {
            pd.put("DICTTYPE", "APPLICABLE_PERSONNEL");
            PageData lc = dictionariesCorpService.saveSelf(pd);
            pd.put("LEARNERCATEGORY", lc.getString("DICTIONARIES_ID"));
        }

        FHLOG.save(Jurisdiction.getUsername(), "从系统用户中修改" + pd.getString("USERNAME") + "的资料");  // 记录日志

        // 检查修改的用户名是否为本人
        if (!Jurisdiction.getUsername().equals(pd.getString("USERNAME"))) {
            if ("admin".equals(pd.getString("USERNAME")) && !"admin".equals(Jurisdiction.getUsername())) {
                return null;  // 非admin用户不能修改admin信息
            }
        } else {
            // 如果是本人修改，恢复原角色ID
            PageData upd = usersService.findByUsername(pd);
            pd.put("ROLE_ID", upd.getString("ROLE_ID"));  // 恢复原角色ID
            pd.put("ROLE_IDS", Tools.notEmpty(upd.getString("ROLE_IDS")) ? upd.get("ROLE_IDS") : "");  // 恢复副职角色ID
        }

        // 如果有修改密码
        if (pd.getString("PASSWORD") != null && !"".equals(pd.getString("PASSWORD"))) {
            pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
        }

        String msg = usersService.changeOrUpdUserCardNo(pd);
        if (msg.equals(Const.CAN_CHENG_USER)) {
            pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
            PageData data = corpInfoService.findById(pd);
            if ("0".equals(data.getString("PERSONNEL_POSITION"))) {
                try {
                    // 执行远程调用
                    if (!PLSUtil.editUser(pd)) {
                        return ReturnMap.ok().put("webSiteStatus", "1");
                    }
                } catch (Exception e) {
                    return ReturnMap.ok().put("webSiteStatus", "1");
                }
            }

            // 远程调用成功后执行本地修改
            if (Tools.isEmpty(pd.getString("CARDNO"))) {
                pd.put("CARDNO", null);
            }
            usersService.editUser(pd);  // 执行本地用户修改

            // 学生信息保存逻辑
            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.delete(pd);
                userInfoService.save(pd);
            }

            // 如果修改了部门/岗位，将该用户所有清单都删除
            if (pd.get("OPERATIONTYPE") != null && Tools.notEmpty(pd.get("OPERATIONTYPE").toString())) {
                List<PageData> listIds = listManagerService.listListByUser(pd);
                if (listIds != null && listIds.size() > 0) {
                    for (PageData listPd : listIds) {
                        PageData pd1 = new PageData();
                        pd1.put("OPERATOR", Jurisdiction.getUsername());    //修改人
                        pd1.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
                        pd1.put("LISTMANAGER_ID", listPd.get("LISTMANAGER_ID"));
                        listManagerService.remove(pd1);
                        pd1 = listManagerService.findById(pd1);
                        if (pd1.get("TYPE") != null && Tools.notEmpty(pd1.get("TYPE").toString())) {
                            if ("listType0005".equals(pd1.get("TYPE").toString())) {
                                pd1.put("LISTSTATISTICS_ID", this.get32UUID());    //主键
                                pd1.put("STARTTIME", pd1.get("START_DATE").toString() + " 00:00:00");
                                pd1.put("ENDTIME", pd1.get("END_DATE").toString() + " 23:59:59");
                                pd1.put("PERIOD", null);
                                PageData statistics = listStatisticsService.findByCondition(pd1);
                                if (statistics != null && statistics.get("LISTSTATISTICS_ID") != null) {
                                    statistics.put("NOTEXAMINEDNUM", Integer.parseInt(statistics.get("NOTEXAMINEDNUM").toString()) - 2);
                                    listStatisticsService.edit(statistics);
                                }
                                pd1.put("ISSTATISTICS", '0');
                                // 本期已检查的不计入统计
                                checkrecordService.editStatistics(pd1);
                            } else {
                                if (pd1.get("PERIOD") != null && Tools.notEmpty(pd1.get("PERIOD").toString())) {
                                    String period = pd1.get("PERIOD").toString();
                                    switch (period) {
                                        case "checkPeriod0001"://每日
                                            pd1.put("STARTTIME", DateUtil.getDay() + " 00:00:00");
                                            pd1.put("ENDTIME", DateUtil.getDay() + " 23:59:59");
                                            break;
                                        case "checkPeriod0002"://每周
                                            pd1.put("STARTTIME", DateUtil.getWeekStart());
                                            pd1.put("ENDTIME", DateUtil.getWeekEnd());
                                            break;
                                        case "checkPeriod0003"://每旬
                                            String year = DateUtil.getYear().toString();
                                            String month = DateUtil.getMonth().toString();
                                            Integer day = Integer.parseInt(DateUtil.getOnlyDay().toString());
                                            String startTime = year + "-" + month + "-";
                                            String endTime = year + "-" + month + "-";
                                            if (day <= 10) {
                                                startTime = startTime + "01 00:00:00";
                                                endTime = endTime + "10 23:59:59";
                                            } else if (day > 10 && day <= 20) {
                                                startTime = startTime + "11 00:00:00";
                                                endTime = endTime + "20 23:59:59";
                                            } else {
                                                startTime = startTime + "21 00:00:00";
                                                endTime = DateUtil.getMonthEndDay() + " 23:59:59";
                                            }
                                            pd1.put("STARTTIME", startTime);
                                            pd1.put("ENDTIME", endTime);
                                            break;
                                        case "checkPeriod0004"://每月
                                            pd1.put("STARTTIME", DateUtil.getMonthFirstDay() + " 00:00:00");
                                            pd1.put("ENDTIME", DateUtil.getMonthEndDay() + " 23:59:59");
                                            break;
                                        case "checkPeriod0005"://每季
                                            pd1.put("STARTTIME", DateUtil.quarterStart() + " 00:00:00");
                                            pd1.put("ENDTIME", DateUtil.quarterEnd() + " 23:59:59");
                                            break;
                                        case "checkPeriod0006"://每年
                                            pd1.put("STARTTIME", DateUtil.getCurrYearFirst() + " 00:00:00");
                                            pd1.put("ENDTIME", DateUtil.getCurrYearLast() + " 23:59:59");
                                            break;
                                        case "checkPeriod0007"://半年
                                            String byear = DateUtil.getYear().toString();
                                            Integer bmonth = Integer.parseInt(DateUtil.getMonth().toString());
                                            if (bmonth <= 6) {
                                                pd1.put("STARTTIME", byear + "-01-01 00:00:00");
                                                pd1.put("ENDTIME", byear + "-06-30 23:59:59");
                                            } else if (bmonth > 6) {
                                                pd1.put("STARTTIME", byear + "-07-01 00:00:00");
                                                pd1.put("ENDTIME", byear + "-12-31 23:59:59");
                                            }
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                PageData statistics = listStatisticsService.findByCondition(pd1);
                                if (statistics != null && statistics.get("LISTSTATISTICS_ID") != null) {
                                    statistics.put("NOTEXAMINEDNUM", Integer.parseInt(statistics.get("NOTEXAMINEDNUM").toString()) - 1);
                                    listStatisticsService.edit(statistics);
                                }
                                pd1.put("ISSTATISTICS", '0');
                                // 本期已检查的不计入统计
                                checkrecordService.editStatistics(pd1);
                            }
                        }
                    }
                }
            }
            map.put("result", errInfo);
        } else {
            map.put("result", "errInfo");
            map.put("msg", msg);
        }

        return map;
    }


    /**
     * 修改用户(系统用户列表修改)
     */
    @RequestMapping(value = "/editUserFuns")
    // @RequiresPermissions("user:edit")
    @ResponseBody
    public Object editUserFuns() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        FHLOG.save(Jurisdiction.getUsername(), "从系统用户中修改" + pd.getString("USERNAME") + "的小程序菜单权限");                //记录日志
        usersService.editUserFuns(pd);    //执行修改
        map.put("result", errInfo);
        return map;
    }

    /**
     * 修改用户(个人资料修改)
     */
    @RequestMapping(value = "/editUserOwn")
    @ResponseBody
    public Object editUserOwn() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        if (!Jurisdiction.getUsername().equals(pd.getString("USERNAME"))) { //如果当前登录用户修改用户资料提交的用户名非本人
            FHLOG.save(Jurisdiction.getUsername(), "恶意修改用户资料：" + pd.getString("USERNAME"));
            return null;//不能修改非本人的资料
        } else {            //如果当前登录用户修改用户资料提交的用户名是本人，则不能修改本人的角色ID
            PageData upd = new PageData();
            upd = usersService.findByUsername(pd);
            pd.put("USER_ID", upd.getString("USER_ID")); //对ID还原本人ID，防止串改
            pd.put("ROLE_ID", upd.getString("ROLE_ID")); //对角色ID还原本人角色ID
            pd.put("ROLE_IDS", Tools.notEmpty(upd.getString("ROLE_IDS")) ? upd.get("ROLE_IDS") : ""); //对角色ID还原本人副职角色ID
        }
        if (pd.getString("PASSWORD") != null && !"".equals(pd.getString("PASSWORD"))) {
            pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
        }
        usersService.editUser(pd);    //执行修改
        FHLOG.save(Jurisdiction.getUsername(), "从个人资料中修改" + pd.getString("USERNAME") + "的资料");                //记录日志
        map.put("result", errInfo);
        return map;
    }

    /**
     * 判断用户名是否存在
     *
     * @return
     */
    @RequestMapping(value = "/hasUser")
    @ResponseBody
    @LogAnno(menuType = "双重预防", menuServer = "企业管理", instructionsOperate = "用户管理", instructionsType = "判断用户名是否存在")
    public Object hasUser() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd = usersService.findByUsername(pd);
        if (pd != null) {
            map.put("pd", pd);
        }
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * 判断邮箱是否存在
     *
     * @return
     */
    @RequestMapping(value = "/hasEmail")
    @ResponseBody
    public Object hasEmail() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        if (usersService.findByEmail(pd) != null) {
            errInfo = "fail";
            map.put("msg", "邮箱重复");
        }
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * 判断编码是否存在
     *
     * @return
     */
    @RequestMapping(value = "/hasNumber")
    @ResponseBody
    public Object hasNumber() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        if (usersService.findByNumbe(pd) != null) {
            errInfo = "error";
        }
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * 检验身份证号是否有效
     *
     * @return
     */
    @RequestMapping(value = "/validateIdentity")
    @ResponseBody
    public Object validateIdentity() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("ISVALIDATE", IdcardUtils.validateCard(pd.getString("IDENTITY_NUMBER")));
        map.put("pd", pd);
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * 保存用户
     *
     * @return
     * @throws Exception
     */
//	@RequestMapping(value="/saveUser")
//	// @RequiresPermissions("user:add")
//	@ResponseBody
//	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "用户管理",instructionsType = "保存用户")
//	public Object saveUser() throws Exception{
//		Map<String,Object> map = new HashMap<String,Object>();
//		String errInfo = "success";
//		PageData pd = new PageData();
//		pd = this.getPageData();
//		// 默认周期初始值为1
//		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
////		pd.put("DURATION", "1");							//工作状态持续时间
//		pd.put("WORKSTATUS", "1");							//工作状态
//		pd.put("WORKPERIOD", "1");							//当前工作周期数
//		pd.put("RIGHTS", "788664966448");
//
//		if(pd.get("USERAVATARURL")!=null && !pd.getString("USERAVATARURL").equals("")){
////			System.out.println("USERAVATARURL原长度："+pd.getString("USERAVATARURL").length());
//			String USERAVATARURL64 = ImageAnd64Binary.zipBase64(pd.getString("USERAVATARURL"));
////			System.out.println("USERAVATARURL压缩长度："+USERAVATARURL64.length());
//			try{
//				FaceUtil.compareFace(pd.getString("USERAVATARURL"),pd.getString("USERAVATARURL"));
//			}catch (Exception e){
//				map.put("result", "fail");
//				map.put("msg", "人脸图像不符合要求 请重新上传!");
//				return map;
//			}
//		}
//		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", this.get32UUID());			//ID 主键
//		pd.put("LAST_LOGIN", "");						//最后登录时间
//		pd.put("IP", "");								//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"), pd.getString("PASSWORD")).toString());			//密码加密
//
//
//		if(null == usersService.findByUsername(pd)){	//判断用户名是否存在
//				usersService.saveUser(pd); 					//执行保存
//			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);
//			}
//		}else{
//			map.put("result","failed");
//		}
//		FHLOG.save(Jurisdiction.getUsername(), "新增用户："+pd.getString("USERNAME"));//记录日志
//
//
//		map.put("result", errInfo);				//返回结果
//		map.put("USER_ID", pd.getString("USER_ID"));				//返回结果
//		return map;
//	}
    @RequestMapping(value = "/saveUser")
    // @RequiresPermissions("user:add")
    @ResponseBody
    @Transactional
    @LogAnno(menuType = "双重预防", menuServer = "企业管理", instructionsOperate = "用户管理", instructionsType = "保存用户")
    public Object saveUser() throws Exception {
        Map<String, Object> map = new HashMap<>();
        PageData pd = this.getPageData();
        try {
            return usersService.saveUserNew(pd);
            // 调用 Service 层保存用户
        } catch (Exception e) {
            map.put("msg", e.getMessage());
            throw e;
        }
    }

    /**
     * 删除用户
     *
     * @return
     */
    @RequestMapping(value = "/deleteUser")
    // @RequiresPermissions("user:del")
    @ResponseBody
    @LogAnno(menuType = "双重预防", menuServer = "企业管理", instructionsOperate = "用户管理", instructionsType = "删除用户")
    public Object deleteUser() throws Exception {
        Map<String, String> map = new HashMap<>();
        PageData pd = new PageData();
        String errInfo = "success";
        pd = this.getPageData();

        // 记录日志
        FHLOG.save(Jurisdiction.getUsername(), "删除用户ID：" + pd.getString("USER_ID"));

        // 设置企业信息
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        PageData data = corpInfoService.findById(pd);

        if ("0".equals(data.getString("PERSONNEL_POSITION"))) {
            try {
                if (!PLSUtil.removeUser(pd)) {
                    return ReturnMap.ok().put("webSiteStatus", "1");
                }
            } catch (Exception e) {
                return ReturnMap.ok().put("webSiteStatus", "1");
            }
        }
        usersService.deleteUser(pd);  // 删除用户
        ueditorService.delete(pd);    // 删除副文本关联数据

        // 构建 USER_ID 和 NAME
        StringBuilder sb = new StringBuilder();
        sb.append(",").append(pd.getString("USER_ID")).append(",");
        String userid = sb.toString();
        System.out.println(userid);

        StringBuilder sn = new StringBuilder();
        sn.append(",").append(pd.getString("NAME")).append(",");
        String name = sn.toString();
        System.out.println(name);

        pd.put("USER_ID", userid);
        pd.put("NAME", name);
        noticemanagementService.delete(pd);  // 删除通知管理相关数据

        // 删除列表管理相关数据
        List<PageData> listIds = listManagerService.listListByUser(pd);
        if (listIds != null && !listIds.isEmpty()) {
            for (PageData listPd : listIds) {
                PageData pd1 = new PageData();
                pd1.put("OPERATOR", Jurisdiction.getUsername());  // 修改人
                pd1.put("OPERATTIME", DateUtil.date2Str(new Date()));  // 修改时间
                pd1.put("LISTMANAGER_ID", listPd.get("LISTMANAGER_ID"));
                listManagerService.remove(pd1);
                pd1 = listManagerService.findById(pd1);

                if (pd1.get("TYPE") != null && Tools.notEmpty(pd1.get("TYPE").toString())) {
                    if ("listType0005".equals(pd1.get("TYPE").toString())) {
                        pd1.put("LISTSTATISTICS_ID", this.get32UUID());  // 主键
                        pd1.put("STARTTIME", pd1.get("START_DATE").toString() + " 00:00:00");
                        pd1.put("ENDTIME", pd1.get("END_DATE").toString() + " 23:59:59");
                        pd1.put("PERIOD", null);
                        PageData statistics = listStatisticsService.findByCondition(pd1);
                        if (statistics != null && statistics.get("LISTSTATISTICS_ID") != null) {
                            statistics.put("NOTEXAMINEDNUM", Integer.parseInt(statistics.get("NOTEXAMINEDNUM").toString()) - 2);
                            listStatisticsService.edit(statistics);
                        }
                        pd1.put("ISSTATISTICS", '0');
                        checkrecordService.editStatistics(pd1);
                    } else {
                        if (pd1.get("PERIOD") != null && Tools.notEmpty(pd1.get("PERIOD").toString())) {
                            String period = pd1.get("PERIOD").toString();
                            switch (period) {
                                case "checkPeriod0001": // 每日
                                    pd1.put("STARTTIME", DateUtil.getDay() + " 00:00:00");
                                    pd1.put("ENDTIME", DateUtil.getDay() + " 23:59:59");
                                    break;
                                case "checkPeriod0002": // 每周
                                    pd1.put("STARTTIME", DateUtil.getWeekStart());
                                    pd1.put("ENDTIME", DateUtil.getWeekEnd());
                                    break;
                                case "checkPeriod0003": // 每旬
                                    String year = DateUtil.getYear().toString();
                                    String month = DateUtil.getMonth().toString();
                                    Integer day = Integer.parseInt(DateUtil.getOnlyDay().toString());
                                    String startTime = year + "-" + month + "-";
                                    String endTime = year + "-" + month + "-";
                                    if (day <= 10) {
                                        startTime = startTime + "01 00:00:00";
                                        endTime = endTime + "10 23:59:59";
                                    } else if (day > 10 && day <= 20) {
                                        startTime = startTime + "11 00:00:00";
                                        endTime = endTime + "20 23:59:59";
                                    } else {
                                        startTime = startTime + "21 00:00:00";
                                        endTime = DateUtil.getMonthEndDay() + " 23:59:59";
                                    }
                                    pd1.put("STARTTIME", startTime);
                                    pd1.put("ENDTIME", endTime);
                                    break;
                                case "checkPeriod0004": // 每月
                                    pd1.put("STARTTIME", DateUtil.getMonthFirstDay() + " 00:00:00");
                                    pd1.put("ENDTIME", DateUtil.getMonthEndDay() + " 23:59:59");
                                    break;
                                case "checkPeriod0005": // 每季
                                    pd1.put("STARTTIME", DateUtil.quarterStart() + " 00:00:00");
                                    pd1.put("ENDTIME", DateUtil.quarterEnd() + " 23:59:59");
                                    break;
                                case "checkPeriod0006": // 每年
                                    pd1.put("STARTTIME", DateUtil.getCurrYearFirst() + " 00:00:00");
                                    pd1.put("ENDTIME", DateUtil.getCurrYearLast() + " 23:59:59");
                                    break;
                                case "checkPeriod0007": // 半年
                                    String byear = DateUtil.getYear().toString();
                                    Integer bmonth = Integer.parseInt(DateUtil.getMonth().toString());
                                    if (bmonth <= 6) {
                                        pd1.put("STARTTIME", byear + "-01-01 00:00:00");
                                        pd1.put("ENDTIME", byear + "-06-30 23:59:59");
                                    } else {
                                        pd1.put("STARTTIME", byear + "-07-01 00:00:00");
                                        pd1.put("ENDTIME", byear + "-12-31 23:59:59");
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }

                        PageData statistics = listStatisticsService.findByCondition(pd1);
                        if (statistics != null && statistics.get("LISTSTATISTICS_ID") != null) {
                            statistics.put("NOTEXAMINEDNUM", Integer.parseInt(statistics.get("NOTEXAMINEDNUM").toString()) - 1);
                            listStatisticsService.edit(statistics);
                        }

                        pd1.put("ISSTATISTICS", '0');
                        // 本期已检查的不计入统计
                        checkrecordService.editStatistics(pd1);
                    }
                }
            }
        }

        map.put("result", errInfo);  // 返回结果
        return map;
    }

    /**
     * 批量删除
     *
     * @throws Exception
     */
    @RequestMapping(value = "/deleteAllUser")
    // @RequiresPermissions("user:del")
    @ResponseBody
    public Object deleteAllUser() throws Exception {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        pd = this.getPageData();
        String USER_IDS = pd.getString("USER_IDS");
        String errInfo = "success";
        if (Tools.notEmpty(USER_IDS)) {
            String ArrayUSER_IDS[] = USER_IDS.split(",");
            FHLOG.save(Jurisdiction.getUsername(), "批量删除用户");                //记录日志
            usersService.deleteAllUser(ArrayUSER_IDS);    //删除用户
            ueditorService.deleteAll(ArrayUSER_IDS);    //删除副文本关联数据
            errInfo = "success";
        } else {
            errInfo = "error";
        }
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * 导出用户信息到EXCEL
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/excel")
    // @RequiresPermissions("toExcel")
    public ModelAndView exportExcel() throws Exception {
        ModelAndView mv = new ModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {

            /*检索条件*/
            String KEYWORDS = pd.getString("KEYWORDS");                        //关键词检索条件
            if (Tools.notEmpty(KEYWORDS)) pd.put("KEYWORDS", KEYWORDS.trim());
            String STARTTIME = pd.getString("STARTTIME");                    //开始时间
            String ENDTIME = pd.getString("ENDTIME");                        //结束时间
            if (Tools.notEmpty(STARTTIME)) pd.put("STARTTIME", STARTTIME + " 00:00:00");
            if (Tools.notEmpty(ENDTIME)) pd.put("ENDTIME", ENDTIME + " 00:00:00");

            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();
            titles.add("用户名");        //1
            titles.add("编号");        //2
            titles.add("姓名");            //3
            titles.add("职位");            //4
            titles.add("手机");            //5
            titles.add("邮箱");            //6
            titles.add("最近登录");        //7
            titles.add("上次登录IP");    //8
            dataMap.put("titles", titles);
            List<PageData> userList = usersService.listAllUser(pd);
            List<PageData> varList = new ArrayList<PageData>();
            for (int i = 0; i < userList.size(); i++) {
                PageData vpd = new PageData();
                vpd.put("var1", userList.get(i).getString("USERNAME"));        //1
                vpd.put("var2", userList.get(i).getString("NUMBER"));        //2
                vpd.put("var3", userList.get(i).getString("NAME"));            //3
                vpd.put("var4", userList.get(i).getString("ROLE_NAME"));    //4
                vpd.put("var5", userList.get(i).getString("PHONE"));        //5
                vpd.put("var6", userList.get(i).getString("EMAIL"));        //6
                vpd.put("var7", userList.get(i).getString("LAST_LOGIN"));    //7
                vpd.put("var8", userList.get(i).getString("IP"));            //8
                varList.add(vpd);
            }
            dataMap.put("varList", varList);
            ObjectExcelView erv = new ObjectExcelView();                    //执行excel操作
            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
        }
        return mv;
    }


    /**
     * 从EXCEL导入到数据库
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/readExcel")
    // @RequiresPermissions("fromExcel")
    @SuppressWarnings("unchecked")
    @ResponseBody
    public Object readExcel(@RequestParam(value = "excel", required = false) MultipartFile file) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        PageData pd = new PageData();
        if (null != file && !file.isEmpty()) {
            File tempFile = new File(file.getOriginalFilename()); //新建file
            FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile); //将MultipartFile复制到File
            List<PageData> listPd = (List) ObjectExcelRead.readExcel(tempFile, 2, 0, 0);            //执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
            pd.put("LAST_LOGIN", "");                //最后登录时间
            pd.put("IP", "");                        //IP
            pd.put("STATUS", "0");                    //状态
            pd.put("SKIN", "pcoded-navbar brand-blue icon-colored brand-default,navbar pcoded-header navbar-expand-lg navbar-light header-blue,");                    //默认皮肤
            pd.put("ROLE_ID", "fhadminzhuche");        //默认角色注册用户
            pd.put("ROLE_IDS", "");                    //副职角色
            /**
             * var0 :编号
             * var1 :姓名
             * var2 :手机
             * var3 :邮箱
             * var4 :备注
             */
            for (int i = 0; i < listPd.size(); i++) {
                pd.put("USER_ID", this.get32UUID());                                        //ID
                pd.put("NAME", listPd.get(i).getString("var1"));                            //姓名
                String USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1"));    //根据姓名汉字生成全拼
                pd.put("USERNAME", USERNAME);
                if (usersService.findByUsername(pd) != null) {                                //判断用户名是否重复
                    USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1")) + Tools.getRandomNum();
                    pd.put("USERNAME", USERNAME);
                }
                pd.put("BZ", listPd.get(i).getString("var4"));                                //备注
                if (Tools.checkEmail(listPd.get(i).getString("var3"))) {                        //邮箱格式不对就跳过
                    pd.put("EMAIL", listPd.get(i).getString("var3"));
                    if (usersService.findByEmail(pd) != null) {                                //邮箱已存在就跳过
                        continue;
                    }
                } else {
                    continue;
                }
                pd.put("NUMBER", listPd.get(i).getString("var0"));                            //编号已存在就跳过
                pd.put("PHONE", listPd.get(i).getString("var2"));                            //手机号

                pd.put("PASSWORD", new SimpleHash("SHA-1", USERNAME, "123").toString());    //默认密码123
                if (usersService.findByNumbe(pd) != null) {
                    continue;
                }
                usersService.saveUser(pd);
            }

            FileUtils.deleteQuietly(tempFile);//删除临时文件
        }
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * 去修改用户页面(在线管理页面打开)
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goEditUfromOnline")
    @ResponseBody
    public Object goEditUfromOnline() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        if ("admin".equals(pd.getString("USERNAME"))) {
            return null;
        }    //不能查看admin用户
        pd.put("ROLE_ID", Jurisdiction.getVIPLEVEL());
        List<Role> roleList = roleService.listAllRolesByPId(pd);    //列出所有系统用户角色
        map.put("fx", "user");
        pd = usersService.findByUsername(pd);                        //根据ID读取
        String ROLE_IDS = pd.getString("ROLE_IDS");                    //副职角色ID
        if (Tools.notEmpty(ROLE_IDS)) {
            String arryROLE_ID[] = ROLE_IDS.split(",");
            for (int i = 0; i < roleList.size(); i++) {
                Role role = roleList.get(i);
                String roleId = role.getROLE_ID();
                for (int n = 0; n < arryROLE_ID.length; n++) {
                    if (arryROLE_ID[n].equals(roleId)) {
                        role.setRIGHTS("1");    //此时的目的是为了修改用户信息上，能看到副职角色都有哪些
                        break;
                    }
                }
            }
        }
        map.put("pd", pd);
        map.put("roleList", roleList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 查看用户
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/view")
    @ResponseBody
    public Object view() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String USERNAME = pd.getString("USERNAME");
        if ("admin".equals(USERNAME)) {
            return null;
        }                    //不能查看admin用户
        pd.put("ROLE_ID", Jurisdiction.getVIPLEVEL());
        List<Role> roleList = roleService.listAllRolesByPId(pd);    //列出所有系统用户角色
        pd = usersService.findByUsername(pd);                        //根据ID读取
        map.put("msg", "1");
        if (null == pd) {
            PageData rpd = new PageData();
            rpd.put("RNUMBER", USERNAME);                            //用户名查不到数据时就把数据当作角色的编码去查询角色表
            rpd = roleService.getRoleByRnumber(rpd);
            map.put("rpd", rpd);
            map.put("msg", "2");
        }
        map.put("pd", pd);
        map.put("roleList", roleList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 显示用户列表(弹窗选择用)
     *
     * @param page
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/listUsersForWindow")
    @ResponseBody
    public Object listUsersForWindow(Page page) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String KEYWORDS = pd.getString("KEYWORDS");                        //关键词检索条件
        if (Tools.notEmpty(KEYWORDS)) pd.put("KEYWORDS", KEYWORDS.trim());
        String STARTTIME = pd.getString("STARTTIME");                    //开始时间
        String ENDTIME = pd.getString("ENDTIME");                        //结束时间
        if (Tools.notEmpty(STARTTIME)) pd.put("STARTTIME", STARTTIME + " 00:00:00");
        if (Tools.notEmpty(ENDTIME)) pd.put("ENDTIME", ENDTIME + " 00:00:00");
        page.setPd(pd);
        List<PageData> userList = usersService.listUsersBystaff(page);    //列出用户列表(弹窗选择用)
        pd.put("ROLE_ID", Jurisdiction.getVIPLEVEL());
        List<Role> roleList = roleService.listAllRolesByPId(pd);        //列出所有系统用户角色
        map.put("userList", userList);
        map.put("roleList", roleList);
        map.put("page", page);
        map.put("pd", pd);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 列表
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/listAll")
    @ResponseBody
    @LogAnno(menuType = "双重预防", menuServer = "隐患排查", instructionsOperate = "清单管理", instructionsType = "列表")
    public Object listAll() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        List<PageData> userList = usersService.listAllUser(pd);    //列出Post列表
        map.put("userList", userList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 列表
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/listUserByDept")
    @ResponseBody
    public Object listUserByDept() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        pd.put("ISMAIN", Jurisdiction.getIS_MAIN());
        pd.put("ISSUPERVISE", Jurisdiction.getISSUPERVISE());
        pd.put("DEPARTMENT_ID", Jurisdiction.getDEPARTMENT_ID());
        String DEPTIDS = pd.getString("DEPTIDS");
        if (Tools.notEmpty(DEPTIDS)) {
            String DEPT_IDS[] = DEPTIDS.split(",");
            pd.put("DEPT_IDS", DEPT_IDS);
        }
        List<PageData> userList = usersService.listUserByDept(pd);    //列出Post列表
        map.put("userList", userList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 从EXCEL导入到数据库
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/readExcel2")
//	// @RequiresPermissions("fromExcel")
    @SuppressWarnings("unchecked")
    @ResponseBody
    @Transactional
    @LogAnno(menuType = "双重预防", menuServer = "企业管理", instructionsOperate = "用户管理", instructionsType = "从EXCEL导入到数据库")
    public Object readExcel2(@RequestParam(value = "FFILE", required = false) MultipartFile file) throws Exception {
        Map<String, String> map = new HashMap<>();
        String errInfo = "success";
        StringBuffer errorStr = new StringBuffer();

        if (file != null && !file.isEmpty()) {
            File tempFile = new File(file.getOriginalFilename()); // 创建临时文件
            FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile); // 将MultipartFile复制到File
            List<PageData> listPd = (List) ObjectExcelRead.readExcel(tempFile, 1, 0, 0);   // 读取Excel数据
            List<String> header = new ArrayList<>(Arrays.asList("部门", "岗位", "用户名", "姓名", "邮箱", "人员定位卡号", "备注", "工种"));
            try {
                if (!listPd.isEmpty()) {
                    Set<String> cardNoMap = new HashSet<>();
                    /** 获取企业下的所有部门信息 */
                    PageData departPd = new PageData();
                    departPd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                    PageData corpData = corpInfoService.findById(departPd);

                    PageData off = new PageData();
                    off.put("currentPage", 1);
                    off.put("showCount", 9999);

                    HashMap<String, String> workMap = new HashMap<>();
                    List<PageData> dataList = officeService.listAll(departPd);
                    dataList.forEach(item -> {
                        workMap.put(item.getString("officeName"), item.getString("WORK_ID"));
                    });
                    // 判断 PERSONNEL_POSITION 是否为 "0"，如果为 "0" 则执行远程调用
//                    if ("0".equals(corpData.getString("PERSONNEL_POSITION"))) {
//                        try {
//                            JSONObject body = PLSUtil.GeneralList("/deploy/office/list", off);
//                            if (body == null || !"200".equals(body.getString("code"))) {
//                                return ReturnMap.ok().put("webSiteStatus", "1"); // 远程调用失败，停止逻辑，返回
//                            }
//                            List<JSONObject> list = body.getJSONArray("rows").toJavaList(JSONObject.class);
//                            list.forEach(jsonObject -> {
//                                workMap.put(jsonObject.getString("officeName"), jsonObject.getString("id"));
//                            });
//                        } catch (Exception e) {
//                            return ReturnMap.ok().put("webSiteStatus", "1"); // 捕获异常，返回 webSiteStatus = 1
//                        }
//                    }

                    // 获取所有用户、部门、岗位信息
                    List<PageData> userInfoMap = usersService.getUserCardNoAll(departPd);
                    HashMap<String, String> userInfos = new HashMap<>();
                    for (PageData pageData : userInfoMap) {
                        userInfos.put(pageData.getString("CARDNO"), pageData.getString("USERNAME"));
                    }

                    List<PageData> departList = departmentService.listAll(departPd);
                    Map<String, Object> departMap = new HashMap<>();
                    for (PageData pageData : departList) {
                        departMap.put(Tools.excelHandle(pageData.getString("NAME")), pageData);
                        departMap.put(Tools.excelHandle(pageData.getString("DEPARTMENT_ID")), pageData.getString("deptId"));
                    }

                    PageData postPd = new PageData();
                    postPd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                    List<PageData> postList = postService.listAll(postPd);
                    Map<String, Map<String, Object>> postMap = new HashMap<>();
                    for (PageData pageData : postList) {
                        Map<String, Object> postValMap = postMap.getOrDefault(pageData.getString("DEPARTMENT_ID"), new HashMap<>());
                        postValMap.put(Tools.excelHandle(pageData.getString("NAME")), pageData);
                        postMap.put(pageData.getString("DEPARTMENT_ID"), postValMap);
                    }

                    PageData userPd = new PageData();
                    userPd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                    List<PageData> userList = usersService.findUserNameAll(userPd);
                    List<PageData> userEList = usersService.findAllUser(userPd);
                    Map<String, String> userMap = new HashMap<>();
                    Map<String, Object> emailMap = new HashMap<>();
                    for (PageData pageData : userList) {
                        userMap.put(pageData.getString("USERNAME"), JSON.toJSONString(pageData));
                    }
                    for (PageData pageData : userEList) {
                        emailMap.put(pageData.getString("USERNAME"), "");
                    }

                    PageData rolePd = new PageData();
                    rolePd.put("ISMAIN", "0");
                    rolePd.put("PARENT_ID", Jurisdiction.getVIPLEVEL());
                    rolePd.put("ROLE_NAME", "个人账号");
                    PageData role = roleService.findByPidAndMain(rolePd);
                    if (Tools.isEmpty(role)) {
                        errorStr.append("未找到默认角色信息！请联系管理员");
                        map.put("result", errInfo); // 返回结果
                        map.put("msg", ""); // 返回结果
                        return map;
                    }

                    Map<String, Object> hasUserNameChongfu = new HashMap<>(); // 判断用户名重复
                    Map<String, Object> emailChongfu = new HashMap<>(); // 判断邮箱重复
                    int number = 0; // 行数，用于提示用户
                    List<PageData> addUserList = new ArrayList<>();
                    List<PageData> editUserList = new ArrayList<>();

                    for (PageData lpd : listPd) {
                        number++;
                        for (int i = 0; i < 8; i++) {
                            if (i == 1 || i == 4 || i == 6 || i == 5) {
                                continue;
                            }
                            if (Tools.isEmpty(lpd.get("var" + i))) {
                                errorStr.append("第").append(number).append("行的\"").append(header.get(i)).append("\"无数据;\n");
                            }
                        }

                        String dept = Tools.excelHandle(lpd.getString("var0"));
                        String postName = lpd.getString("var1");
                        String userName = lpd.getString("var2");
                        String name = lpd.getString("var3");
                        String eMail = lpd.getString("var4");
                        String CardNo = lpd.getString("var5");
                        String bz = lpd.getString("var6");
                        String gz = lpd.getString("var7");

                        Pattern patternPhone = Pattern.compile(RegexPatterns.PHONE_REGEX);
                        Pattern patternCardNo = Pattern.compile(RegexPatterns.VERIFY_CARDNO_REGEX);
                        Matcher matcherPhone = patternPhone.matcher(userName);
                        Matcher matcherCardNo = patternCardNo.matcher(CardNo);

                        if (!workMap.containsKey(gz)) {
                            errorStr.append("第").append(number).append("行,工种").append(gz).append("不存在,请重新确认数据;\n");
                            continue;
                        }

                        if (Tools.notEmpty(CardNo)) {
                            if (!cardNoMap.add(CardNo)) {
                                errorStr.append("第").append(number).append("行,定位卡号").append(CardNo).append("excel中重复,请重新确认数据;\n");
                                continue;
                            }
                            if (!matcherCardNo.matches()) {
                                errorStr.append("第").append(number).append("行,定位卡号格式不正确（非负正整数）,请重新确认数据;\n");
                                continue;
                            }
                        }

                        if (!matcherPhone.matches()) {
                            errorStr.append("第").append(number).append("行,手机号格式不正确,请重新确认数据;\n");
                            continue;
                        }

                        // 部门信息处理
                        String departId = "";
                        if (departMap.containsKey(dept)) {
                            PageData depart = (PageData) departMap.get(dept);
                            departId = depart.getString("DEPARTMENT_ID");
                        } else {
                            errorStr.append("第").append(number).append("行,部门信息错误，系统未找到该部门,请重新确认数据;\n");
                            continue;
                        }

                        // 岗位信息处理
                        Map<String, Object> postValMap = postMap.get(departId);
                        String postId = "";
                        if (postValMap != null) {
                            PageData o = (PageData) postValMap.get(postName);
                            if (o != null) {
                                postId = o.getString("POST_ID");
                            }
                        }

                        if (hasUserNameChongfu.containsKey(userName)) {
                            errorStr.append("第").append(number).append("行,用户名重复,请重新确认数据;\n");
                            continue;
                        }

                        if (emailMap.containsKey(eMail)) {
                            errorStr.append("第").append(number).append("行,邮箱“").append(eMail).append("”已经存在，请勿重复导入;\n");
                            continue;
                        }

                        if (emailChongfu.containsKey(eMail)) {
                            errorStr.append("第").append(number).append("行,邮箱重复,请重新确认数据;\n");
                            continue;
                        }

                        hasUserNameChongfu.put(userName, name);
                        if (Tools.notEmpty(eMail)) {
                            emailChongfu.put(eMail, "");
                        }

                        PageData user = new PageData();
                        user.put("USER_ID", this.get32UUID());
                        user.put("USERNAME", userName);
                        user.put("PASSWORD", new SimpleHash("SHA-1", userName, "666666").toString());
                        user.put("NAME", name);
                        user.put("CARDNO", Tools.isEmpty(CardNo) ? null : CardNo);
                        user.put("ROLE_ID", role.getString("ROLE_ID"));
                        user.put("LAST_LOGIN", "");
                        user.put("deptId", departId);
                        user.put("empId", corpData.getString("enterpriseId"));
                        user.put("IP", "");
                        user.put("STATUS", "0");
                        user.put("BZ", bz);
                        user.put("SKIN", "pcoded-navbar navbar-image-3,navbar pcoded-header navbar-expand-lg navbar-light header-dark,");
                        user.put("EMAIL", eMail);
                        user.put("NUMBER", "");
                        user.put("PHONE", "");
                        user.put("ROLE_IDS", "");
                        user.put("DEPARTMENT_ID", departId);
                        user.put("POST_ID", postId);
                        user.put("ISMAIN", "0");
                        user.put("FUN_IDS", "");
                        user.put("RIGHTS", "788664966448");
                        user.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                        user.put("WORK_ID", workMap.get(gz));
                        user.put("WORK_NAME", gz);
                        user.put("ISSTUDENT", "0"); // 在线学习情况
                        user.put("DURATION", "-1"); // 工作状态

                        if (userMap.containsKey(userName)) {
                            PageData useredit = JSON.parseObject(userMap.get(userName), PageData.class);
                            useredit.put("NAME", name);
                            useredit.put("CARDNO", Tools.isEmpty(CardNo) ? null : CardNo);
                            useredit.put("ROLE_ID", role.getString("ROLE_ID"));
                            useredit.put("LAST_LOGIN", "");
                            useredit.put("IP", "");
                            useredit.put("STATUS", "0");
                            useredit.put("BZ", bz);
                            useredit.put("deptId", departId);
                            useredit.put("empId", corpData.getString("enterpriseId"));
                            useredit.put("SKIN", "pcoded-navbar navbar-image-3,navbar pcoded-header navbar-expand-lg navbar-light header-dark,");
                            useredit.put("EMAIL", eMail);
                            useredit.put("NUMBER", "");
                            useredit.put("PHONE", "");
                            useredit.put("ROLE_IDS", "");
                            useredit.put("DEPARTMENT_ID", departId);
                            useredit.put("POST_ID", postId);
                            useredit.put("ISMAIN", "0");
                            useredit.put("FUN_IDS", "");
                            useredit.put("RIGHTS", "788664966448");
                            useredit.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                            useredit.put("ISSTUDENT", "0");
                            useredit.put("DURATION", "-1");
                            useredit.put("WORK_ID", workMap.get(gz));
                            useredit.put("WORK_NAME", gz);
                            editUserList.add(useredit);
                        } else {
                            addUserList.add(user);
                        }
                    }
                    if ("0".equals(corpData.getString("PERSONNEL_POSITION"))) {
                        // 同步校验定位卡号
                        for (PageData pageData : editUserList) {
                            String msg = usersService.changeOrUpdUserCardNo(pageData);
                            if (!msg.equals(Const.CAN_CHENG_USER)) {
                                errorStr.append("第").append(number).append("行,").append(msg).append("\n");
                            }
                        }
                    }


                    if (Tools.isEmpty(errorStr.toString())) {
                        if ("0".equals(corpData.getString("PERSONNEL_POSITION"))) {

                            // 新增用户
                            for (PageData pageData : addUserList) {
                                PageData response = PLSUtil.saveUser(pageData);
                                if ("200".equals(response.getString("code"))) {
                                    pageData.put("PLS_ID", response.getString("data"));
                                } else {
                                    errorStr.append("第").append(number).append("行,人员定位系统用户添加失败，请联系管理员。\n");
                                }
                            }
                        }
                        // 修改用户
                        for (PageData pageData : editUserList) {
                            if ("0".equals(corpData.getString("PERSONNEL_POSITION"))) {
                                if (PLSUtil.editUser(pageData)) {
                                    usersService.editUser(pageData);
                                } else {
                                    errorStr.append("第").append(number).append("行,人员定位系统用户修改失败，请联系管理员。\n");
                                }
                            } else {
                                usersService.editUser(pageData);
                            }
                        }
                        errorStr.append("成功导入").append(addUserList.size()).append("条数据!\n");
                        errorStr.append("成功修改").append(editUserList.size()).append("条数据!");
                    } else {
                        errInfo = "error";
                    }

                    FileUtils.deleteQuietly(tempFile); // 删除临时文件
                } else {
                    map.put("result", "error");
                    map.put("msg", "Excel数据为空，请检查数据后重新上传！");
                    FileUtils.deleteQuietly(tempFile); // 删除临时文件
                    return map;
                }
            } catch (Exception e) {
                map.put("result", "fail");
                map.put("msg", e.toString());
                e.printStackTrace();
                return map;
            }
        }

        map.put("result", errInfo);
        map.put("msg", errorStr.toString());
        map.put("isExcel", "1");
        map.put("resultStr", errorStr.toString());
        return map;
    }


    /**
     * 从EXCEL导入到数据库
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/readExcel3")
//	// @RequiresPermissions("fromExcel")
    @SuppressWarnings("unchecked")
    @ResponseBody
    @Transactional
    @LogAnno(menuType = "双重预防", menuServer = "企业管理", instructionsOperate = "用户管理", instructionsType = "从EXCEL导入到数据库")
    public Object readExcel3(@RequestParam(value = "FFILE", required = false) MultipartFile file) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        StringBuffer errorStr = new StringBuffer();

        if (null != file && !file.isEmpty()) {
            File tempFile = new File(file.getOriginalFilename()); //新建file
            FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile); //将MultipartFile复制到File
            List<PageData> listPd = (List) ObjectExcelRead.readExcel(tempFile, 1, 0, 0);            //执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
            /**
             * var0 :部门
             * var1 :岗位
             * var2 :用户名
             * var3 :姓名
             * var4 :邮箱
             * var5 :备注
             * var6 :是否在线学习人员
             * var7 :身份证号
             * var8 :民族
             * var9 :性别
             * var10 :政治面貌
             * var11 :出生年月
             * var12 :文化程度
             * var13 :人员类型
             * var14 :职务
             * var15 :职称
             * var16 :工种
             * var17 :入职日期
             * var18 :参加工种日期
             * var19 :在职情况
             */

            List<String> header = new ArrayList<String>();
//			header.add("部门");header.add("岗位");
            header.add("用户名");
            header.add("姓名");
//			header.add("邮箱");header.add("备注");header.add("是否在线学习人员");
            header.add("身份证号");
            header.add("民族");
            header.add("性别");
            header.add("政治面貌");
            header.add("出生年月");
            header.add("文化程度");
            header.add("人员类型");
            header.add("职务");
            header.add("职称");
            header.add("工种");
            header.add("入职日期");
            header.add("参加工种日期");
            header.add("在职情况");
            try {

                if (listPd.size() > 0) {
                    /** 获取企业下的所有部门信息*/
                    PageData departPd = new PageData();
                    departPd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                    List<PageData> departList = departmentService.listAll(departPd);
                    Map<String, Object> departMap = new HashMap<String, Object>();
                    for (PageData pageData : departList) {
                        departMap.put(Tools.excelHandle(pageData.getString("NAME")), pageData);
                    }
/*					Map<String,Object> departNameMap = new HashMap<>();
					for (PageData pageData : departList) {
						String nameKey = getParentName(pageData.getString("DEPARTMENT_ID"),departMap);
						departNameMap.put(nameKey,pageData.getString("DEPARTMENT_ID"));
					}*/

                    /** 获取所有岗位信息 */
                    PageData postPd = new PageData();
                    postPd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                    List<PageData> postList = postService.listAll(postPd);
                    Map<String, Map<String, Object>> postMap = new HashMap<>(); //部门id，岗位map
                    for (PageData pageData : postList) {
                        Map<String, Object> postValMap = new HashMap<>();
                        String postDept = pageData.getString("DEPARTMENT_ID");
                        if (postMap.containsKey(postDept)) {
                            postValMap = postMap.get(postDept);
                        }
                        postValMap.put(Tools.excelHandle(pageData.getString("NAME")), pageData);
                        postMap.put(postDept, postValMap);
                    }
                    /** 获取所有岗位信息结束 */

                    /** 获取所有用户信息 用于判断姓名是否重复 */
                    PageData userPd = new PageData();
                    userPd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
//					List<PageData> userList = usersService.findUserNameAll(userPd);
//					List<PageData> userEList = usersService.findAllUser(userPd);
//					Map<String, Object> userMap = new HashMap<>();
//					Map<String, Object> emailMap = new HashMap<>();
//					for (PageData pageData : userList) {
//						userMap.put(pageData.getString("USERNAME"), "");
//					}
//					for (PageData pageData : userEList) {
//						emailMap.put(pageData.getString("USERNAME"), "");
//					}
                    PageData rolePd = new PageData();
                    rolePd.put("ISMAIN", "0");
                    rolePd.put("PARENT_ID", Jurisdiction.getVIPLEVEL());
                    rolePd.put("ROLE_NAME", "个人账号");
                    PageData role = roleService.findByPidAndMain(rolePd);
                    if (Tools.isEmpty(role)) {
                        errorStr.append("未找到默认角色信息！请联系管理员");
                        map.put("result", errInfo);                //返回结果
                        map.put("msg", "");                //返回结果
                        return map;
                    }
                    /**
                     *  判断是否填写必填
                     *  判断excel是有有重复数据
                     *  判断数据库是否有重复数据
                     *  导入 Page
                     *
                     *  企业分级账号
                     */
//					Map<String, Object> hasUserNameChongfu = new HashMap<>();//判断重复数据

//					Map<String, Object> emailChongfu = new HashMap<>();//判断重复数据
                    Integer number = 0;//行数，用于提示用户
                    List<PageData> addUserList = new ArrayList<>();
                    for (PageData lpd : listPd) {
                        number++;
                        for (int i = 0; i < 14; i++) {
                            if (i >= 2) {
                                continue;
                            }
                            if (!lpd.containsKey("var" + i)) {
                                errorStr.append("第" + number + "行的\"" + header.get(i) + "\"无数据;\n");
                                continue;
                            }
                            if (Tools.isEmpty(lpd.get("var" + i))) {
                                errorStr.append("第" + number + "行的\"" + header.get(i) + "\"无数据;\n");
                                continue;
                            }
//							if(Tools.checkEmail(listPd.get(i).getString("var3"))){						//邮箱格式不对就跳过
//								lpd.put("EMAIL", listPd.get(i).getString("var3"));
//							}else{
//								continue;
//							}
                        }

//						String dept = Tools.isEmpty(lpd.get("var0")) ? "" : Tools.excelHandle(lpd.get("var0"));//部门
//						String postName = Tools.isEmpty(lpd.get("var1")) ? "" : lpd.get("var1").toString();//岗位
                        String userName = Tools.isEmpty(lpd.get("var0")) ? "" : lpd.get("var0").toString();//用户名
                        String name = Tools.isEmpty(lpd.get("var1")) ? "" : lpd.get("var1").toString();//姓名
//						String eMail = Tools.isEmpty(lpd.get("var4")) ? "" : lpd.get("var4").toString();//邮箱
//						String bz = Tools.isEmpty(lpd.get("var5")) ? "" : lpd.get("var5").toString();//备注
//						String USER_ID_CARD = Tools.isEmpty(lpd.get("var6"))?"":lpd.get("var6").toString();//身份证号
//						String NATION = Tools.isEmpty(lpd.get("var7"))?"":lpd.get("var7").toString();//民族
//						String SEX = Tools.isEmpty(lpd.get("var8"))?"":lpd.get("var8").toString();//性别
//
//						String POLITICAL_OUTLOOK = Tools.isEmpty(lpd.get("var9"))?"":lpd.get("var9").toString();//政治面貌
//						String DATE_OF_BIRTH = Tools.isEmpty(lpd.get("var10"))?"":lpd.get("var10").toString();//出生年学
//						String DEGREE_OF_EDUCATION = Tools.isEmpty(lpd.get("var11"))?"":lpd.get("var11").toString();//文化程度
//
//						String PERSONNEL_TYPE = Tools.isEmpty(lpd.get("var12"))?"":lpd.get("var12").toString();//人员类型
//						String DUTIES = Tools.isEmpty(lpd.get("var13"))?"":lpd.get("var13").toString();//职务
//						String TITLE = Tools.isEmpty(lpd.get("var14"))?"":lpd.get("var14").toString();//职称
//
//						String TYPE_OF_WORK = Tools.isEmpty(lpd.get("var15"))?"":lpd.get("var15").toString();//工种
//						String ENTRY_DATE = Tools.isEmpty(lpd.get("var16"))?"":lpd.get("var16").toString();//入职日期
//						String WORKING_DATE = Tools.isEmpty(lpd.get("var17"))?"":lpd.get("var17").toString();//参加工作日期
//
//						String INCUMBENCY = Tools.isEmpty(lpd.get("var18"))?"":lpd.get("var18").toString();//在职情况
			/*
						if(Tools.isEmpty(dept) || Tools.isEmpty(postName) || Tools.isEmpty(userName) ||Tools.isEmpty(name)  ) {
							errInfo = "error";
							errorStr.append("第"+number+"行,公司级部门,岗位,用户名,姓名为信息必填项,请重新确认数据");
							break;
						}
						*/
			/*			if(!departMap.containsKey(dept)) {
							errorStr.append("第"+number+"行的"+header.get(0)+"未找到名称为\""+dept+"\"的部门"+";\n");
							continue;
						}*/
                        Pattern patternPhone = Pattern.compile(RegexPatterns.PHONE_REGEX);
                        Matcher matcher = patternPhone.matcher(lpd.getString("var0"));
                        if (!matcher.matches()) {
                            errorStr.append("第" + number + "行,");
                            errorStr.append("手机号格式不正确,请重新确认数据;\n");
                            continue;
                        }
                        Pattern patternCard = Pattern.compile(RegexPatterns.USERID_CARD);
                        Matcher matchercard = patternCard.matcher(lpd.getString("var2"));
                        if (!matchercard.matches()) {
                            errorStr.append("第" + number + "行,");
                            errorStr.append("身份证号格式不正确,请重新确认数据;\n");
                            continue;
                        }
//						/** 部门信息 **/
//						String departId = "";
//						if (departMap.containsKey(dept)) {
//							PageData depart = (PageData) departMap.get(dept);
//							departId = depart.get("DEPARTMENT_ID").toString();
//						} else {
//							errorStr.append("第" + number + "行,部门信息错误，系统未找到该部门,请重新确认数据;\n");
//							continue;
//						}
//						/** 部门信息  结束**/
//						/** 岗位 **/

/*						if(Tools.isEmpty(postName)) {
							errInfo = "error";
							errorStr.append("第"+number+"行,岗位信息为空,请重新确认数据");
							break;
						}*/
//						if (!postMap.containsKey(departId)) {
//							errorStr.append("第" + number + "行,未找到该部门的岗位信息,请重新确认数据;\n");
//							continue;
//						}
//						Map<String, Object> postValMap = postMap.get(departId);//这个部门下的所有岗位信息
//						if (!postValMap.containsKey(postName)) {
//							errorStr.append("第" + number + "行,在" + dept + "部门下，未找到" + postName + "岗位信息,请重新确认数据;\n");
//							continue;
//						}
//						PageData post = (PageData) postValMap.get(postName);
//						String postId = post.getString("POST_ID");
						/*for (PageData pageData : postValList) {
							if(postName.equals(pageData.getString("NAME"))) {
								postId = pageData.getString("POST_ID");
							}
						}*/
/*						if(Tools.isEmpty(postId)) {
							errInfo = "error";
							errorStr.append("第"+number+"行,");
							errorStr.append("在"+keyDept+"部门下，未找到"+postName+"岗位信息,请重新确认数据");
							break;
						}*/

//						/** 岗位  结束**/
//						if(userMap.containsKey(userName)) {
//							System.out.println(userMap.containsKey(userName));
//							errorStr.append("第"+number+"行,");
//							errorStr.append("用户名“"+userName+"”已经存在，请勿重复导入;\n");
//							continue;
//						}
//						if(hasUserNameChongfu.containsKey(userName)) {
//							errorStr.append("第"+number+"行,");
//							errorStr.append("用户名重复,请重新确认数据;\n");
//							continue;
//						}
//
//
//						if(emailMap.containsKey(eMail)) {
//							errorStr.append("第"+number+"行,");
//							errorStr.append("邮箱“"+eMail+"”已经存在，请勿重复导入;\n");
//							continue;
//						}
//						if(emailChongfu.containsKey(eMail)) {
//							errorStr.append("第"+number+"行,");
//							errorStr.append("邮箱重复,请重新确认数据;\n");
//							continue;
//						}
//						if(hasUserNameChongfu.containsValue(name)) {
//							errInfo = "error";
//							errorStr.append("第"+number+"行,");
//							errorStr.append("姓名重复,请重新确认数据");
//							break;
//						}
//						hasUserNameChongfu.put(userName, name);
//						if(Tools.notEmpty(eMail)) {
//							emailChongfu.put(eMail, "");
//						}
                        PageData user = new PageData();

//						user.put("USER_ID", this.get32UUID());
                        user.put("USERNAME", userName);
                        user.put("NAME", name);
                        user.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
//						user.put("DEPARTMENT_ID", departId);
                        user = usersService.findByUsername(user);
                        if (user != null && user.size() > 0) {
                            user.get("USER_ID");
                        } else {
                            errorStr.append("第" + number + "行,");
                            errorStr.append("未找到该学员信息或人员信息不一致，请重新检查数据\n");
                            continue;
                        }
                        user.put("PASSWORD", new SimpleHash("SHA-1", userName, "666666").toString());
                        user.put("ROLE_ID", role.getString("ROLE_ID"));
                        user.put("LAST_LOGIN", "");
                        user.put("IP", "");
                        user.put("STATUS", "0");
//							user.put("BZ", bz);
                        user.put("SKIN", "pcoded-navbar navbar-image-3,navbar pcoded-header navbar-expand-lg navbar-light header-dark,");
//							user.put("EMAIL", eMail);
                        user.put("NUMBER", "");
                        user.put("PHONE", "");
                        user.put("ROLE_IDS", "");
//							user.put("POST_ID", postId);
                        user.put("ISMAIN", "0");
                        user.put("FUN_IDS", "");
                        user.put("RIGHTS", "788664966448");
                        user.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
                        user.put("ISSTUDENT", "true");// 在线学习情况
                        user.put("DURATION", "-1");// 工作状态持

//							String zxxxType = Tools.isEmpty(lpd.get("var6")) ? "" : lpd.get("var6").toString();//是否在线学习人员
//							if ("是".equals(zxxxType)) { // 在线学习情况
                        user.put("zxxxType", "1");// 在线学习情况
                        for (int i = 3; i < 14; i++) {
                            if (i == 8) // 人员类型 非必填
                                if (!lpd.containsKey("var" + i)) {
                                    errorStr.append("第" + number + "行的\"" + header.get(i) + "\"无数据;\n");
                                    continue;
                                }
                            if (Tools.isEmpty(lpd.get("var" + i))) {
                                errorStr.append("第" + number + "行的\"" + header.get(i) + "\"无数据;\n");
                                continue;
                            }
                        }
                        String USER_ID_CARD = Tools.isEmpty(lpd.get("var2")) ? "" : lpd.get("var2").toString();//身份证号
                        String NATION = Tools.isEmpty(lpd.get("var3")) ? "" : lpd.get("var3").toString();//民族
                        String SEX = Tools.isEmpty(lpd.get("var4")) ? "" : lpd.get("var4").toString();//性别

                        String POLITICAL_OUTLOOK = Tools.isEmpty(lpd.get("var5")) ? "" : lpd.get("var5").toString();//政治面貌
                        String DATE_OF_BIRTH = Tools.isEmpty(lpd.get("var6")) ? "" : lpd.get("var6").toString();//出生年学
                        String DEGREE_OF_EDUCATION = Tools.isEmpty(lpd.get("var7")) ? "" : lpd.get("var7").toString();//文化程度

                        String PERSONNEL_TYPE = Tools.isEmpty(lpd.get("var8")) ? "" : lpd.get("var8").toString();//人员类型
                        String DUTIES = Tools.isEmpty(lpd.get("var9")) ? "" : lpd.get("var9").toString();//职务
                        String TITLE = Tools.isEmpty(lpd.get("var10")) ? "" : lpd.get("var10").toString();//职称

                        String TYPE_OF_WORK = Tools.isEmpty(lpd.get("var11")) ? "" : lpd.get("var11").toString();//工种
                        String ENTRY_DATE = Tools.isEmpty(lpd.get("var12")) ? "" : lpd.get("var12").toString();//入职日期
                        String WORKING_DATE = Tools.isEmpty(lpd.get("var13")) ? "" : lpd.get("var13").toString();//参加工作日期

                        String INCUMBENCY = Tools.isEmpty(lpd.get("var14")) ? "" : lpd.get("var14").toString();//在职情况


                        PageData minzu = dictionariesService.findByName(NATION, "0a0e406f27f74ee698fe9979d25f62dd");//民族
                        if (null == minzu) {
                            errorStr.append("第" + number + "行,");
                            errorStr.append("未找到该民族信息,请重新确认数据;\n");
                            continue;
                        }
                        PageData xibei = dictionariesService.findByName(SEX, "21501808bbc344d593fbf9ccfe6c4531");//性别
                        if (null == xibei) {
                            errorStr.append("第" + number + "行,");
                            errorStr.append("未找到该性别信息,请重新确认数据;\n");
                            continue;
                        }
                        PageData zhengzhimianmao = dictionariesService.findByName(POLITICAL_OUTLOOK, "6351efdd12dc4730952e5d195718e252");//政治面貌
                        if (null == zhengzhimianmao) {
                            errorStr.append("第" + number + "行,");
                            errorStr.append("未找到政治面貌信息,请重新确认数据;\n");
                            continue;
                        }
                        Pattern pattern = Pattern.compile("[0-9]*");
                        Date beginDate = DateUtil.fomatDate("1900-01-01"); // 1900, 0, 1
                        Matcher isNum = pattern.matcher(DATE_OF_BIRTH); //判断是否为数字
                        Date DATE_OF_BIRTH_VAL = new Date();
                        if (isNum.matches()) {
                            DATE_OF_BIRTH_VAL = DateUtil.getDateAfter(beginDate, Integer.parseInt(DATE_OF_BIRTH));
                        } else {
                            DATE_OF_BIRTH_VAL = DateUtil.fomatDateByNian(DATE_OF_BIRTH);//出生年月
                        }
                        PageData wenhuyachengdu = dictionariesService.findByName(DEGREE_OF_EDUCATION, "d7d80f08d73a4accbccf4fd3d8d1d867");//文化程度
                        if (null == wenhuyachengdu) {
                            errorStr.append("第" + number + "行,");
                            errorStr.append("未找到文化程度信息,请重新确认数据;\n");
                            continue;
                        }
                        PageData renyuanleixing = new PageData();
                        if (!Tools.isEmpty(PERSONNEL_TYPE)) {//人员类型
                            renyuanleixing = dictionariesService.findByName(PERSONNEL_TYPE, "0b62f92b0b624aab8e89a77304a64d5e");//人员类型
                            if (null == renyuanleixing) {
                                errorStr.append("第" + number + "行,");
                                errorStr.append("未找到人员类型信息,请重新确认数据;\n");
                                continue;
                            }

                        }
                        PageData zhiwu = dictionariesCorpService.findByName(DUTIES, Jurisdiction.getCORPINFO_ID(), "09e36ac01e9540f8bc84eab1c1a78754");//职务
                        if (null == zhiwu) { //如果数据库没有这个职务，新增职务
                            zhiwu = new PageData();
                            zhiwu.put("PARENT_ID", "09e36ac01e9540f8bc84eab1c1a78754");
                            zhiwu.put("BIANMA", "zhiwu");
                            zhiwu.put("NAME", DUTIES);
                            zhiwu = dictionariesCorpService.saveByZidongxinzeng(zhiwu);
                        }
                        PageData zhicheng = dictionariesCorpService.findByName(TITLE, Jurisdiction.getCORPINFO_ID(), "945a6b10e59946078b500f0fbafa8679");//职称
                        if (null == zhicheng) { //如果数据库没有这个职称，新增职称
                            zhicheng = new PageData();
                            zhicheng.put("PARENT_ID", "945a6b10e59946078b500f0fbafa8679");
                            zhicheng.put("BIANMA", "zhicheng");
                            zhicheng.put("NAME", TITLE);
                            zhicheng = dictionariesCorpService.saveByZidongxinzeng(zhicheng);
                        }
                        PageData gongzhong = dictionariesCorpService.findByName(TYPE_OF_WORK, Jurisdiction.getCORPINFO_ID(), "55484e491a5e442d839c4595380713ec");//工种
                        if (null == gongzhong) { //如果数据库没有这个工种，新增工种
                            gongzhong = new PageData();
                            gongzhong.put("PARENT_ID", "55484e491a5e442d839c4595380713ec");
                            gongzhong.put("BIANMA", "gongzhong");
                            gongzhong.put("NAME", TYPE_OF_WORK);
                            gongzhong = dictionariesCorpService.saveByZidongxinzeng(gongzhong);
                        }

                        Date ENTRY_DATE_VAL = new Date();//入职日期
                        Matcher isNum2 = pattern.matcher(ENTRY_DATE);
                        if (isNum2.matches()) {
                            ENTRY_DATE_VAL = DateUtil.getDateAfter(beginDate, Integer.parseInt(ENTRY_DATE));
                        } else {
                            ENTRY_DATE_VAL = DateUtil.fomatDateByNian(ENTRY_DATE);
                        }

                        Date WORKING_DATE_VAL = new Date();//参加工作日期
                        Matcher isNum3 = pattern.matcher(WORKING_DATE);
                        if (isNum3.matches()) {
                            WORKING_DATE_VAL = DateUtil.getDateAfter(beginDate, Integer.parseInt(WORKING_DATE));
                        } else {
                            WORKING_DATE_VAL = DateUtil.fomatDateByNian(WORKING_DATE);
                        }

                        PageData zaizhiqingkuang = dictionariesService.findByName(INCUMBENCY, "548764b5d4bf4bd7a18ef88274ef49e4");//在职情况
                        if (null == zaizhiqingkuang) {
                            errorStr.append("第" + number + "行,");
                            errorStr.append("未找到在职情况信息,请重新确认数据;\n");
                            continue;
                        }

                        user.put("USER_ID_CARD", USER_ID_CARD);
                        user.put("NATION", minzu.get("DICTIONARIES_ID"));
                        user.put("SEX", xibei.get("DICTIONARIES_ID"));
                        user.put("POLITICAL_OUTLOOK", zhengzhimianmao.get("DICTIONARIES_ID"));
                        user.put("DATE_OF_BIRTH", DATE_OF_BIRTH_VAL);
                        user.put("DEGREE_OF_EDUCATION", wenhuyachengdu.get("DICTIONARIES_ID"));
                        user.put("PERSONNEL_TYPE", renyuanleixing.get("DICTIONARIES_ID"));
                        user.put("DUTIES", zhiwu.get("DICTIONARIES_ID"));
                        user.put("TITLE", zhicheng.get("DICTIONARIES_ID"));
                        user.put("TYPE_OF_WORK", gongzhong.get("DICTIONARIES_ID"));
                        user.put("ENTRY_DATE", ENTRY_DATE_VAL);
                        user.put("WORKING_DATE", WORKING_DATE_VAL);
                        user.put("INCUMBENCY", zaizhiqingkuang.get("DICTIONARIES_ID"));
                        user.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
//							}
                        addUserList.add(user);
                    }
                    if (Tools.isEmpty(errorStr.toString())) {
                        for (PageData pageData : addUserList) {
                            usersService.editUserState(pageData);
                            userInfoService.delete(pageData);
                            userInfoService.save(pageData);
                        }

                        errorStr.append("成功导入" + addUserList.size() + "条数据!");
                    } else {
                        errInfo = "error";
                    }
                    FileUtils.deleteQuietly(tempFile);//删除临时文件
                } else {
                    map.put("result", "error");                //返回结果
                    map.put("msg", "Excel数据为空，请检查数据后，重新上传！");
                    FileUtils.deleteQuietly(tempFile);//删除临时文件
                    return map;
                }
            } catch (Exception e) {
                map.put("result", "fail");                //返回结果
                map.put("msg", e.toString());
                e.printStackTrace();
                return map;
            }

        }
        map.put("result", errInfo);                //返回结果
        map.put("msg", errorStr.toString());                //返回结果
        map.put("isExcel", "1");                //返回类型
        map.put("resultStr", errorStr.toString());
        return map;
    }

    /**
     * 递归循环  找到父节点名称
     *
     * @param parentId  部门父节点id
     * @param departMap 全部部门信息
     * @param valName   部门名称
     * @return 从子节点开始往上循序
     */
    public String getParentName(String parentId, Map<String, Object> departMap) {
        StringBuffer keyName = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            PageData dept = (PageData) departMap.get(parentId);
            if ("0".equals(dept.getString("PARENT_ID"))) {
                keyName.append(dept.getString("NAME") + "-");
                break;
            } else {
                keyName.append(dept.getString("NAME") + "-");
                parentId = dept.getString("PARENT_ID");
            }
        }
        return keyName.toString();
    }

    /**
     * 获取当前登录用户ID
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goUserId")
    @ResponseBody
    public Object goUserId() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        map.put("result", errInfo);
        map.put("USER_ID", Jurisdiction.getUSER_ID());
        return map;
    }


    /**
     * 查询公司所有用户
     *
     * @param page
     * @throws Exception
     */
    @RequestMapping(value = "/listUserByCorp")
    @ResponseBody
    @LogAnno(menuType = "高危作业管理", menuServer = "有限空间作业管理", instructionsOperate = "有限空间台账", instructionsType = "查询公司所有用户")
    public Object listUserByCorp() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        List<PageData> userList = usersService.listUserDepPos(pd);    //列出Post列表
        map.put("userList", userList);
        map.put("result", errInfo);
        return map;
    }


    /**
     * 显示列表listCascader
     *
     * @return
     */
    @RequestMapping(value = "/listCascader")
    // @RequiresPermissions("department:list")
    @ResponseBody
    public Object listCascader() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        List<PageData> pdList = new ArrayList<PageData>();
        List<Dictionaries> dictList = dictionariesService.listSubDictByParentId("532282f9c48346b8b646531909c739df"); //获取在线考试适用人员的子列表数据
        PageData pd = new PageData();
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        List<PageData> userList = this.usersService.listCascader(pd);    //获取单位下的所有人员

        PageData other = new PageData();
        other.put("value", "-");
        other.put("label", "其他");
        List<PageData> otherChildrenList = new ArrayList<PageData>();
        for (Dictionaries dict : dictList) {
            PageData pd0 = new PageData();
            pd0.put("value", dict.getBIANMA());
            pd0.put("label", dict.getNAME());
            List<PageData> childrenList = new ArrayList<PageData>();
            for (PageData user : userList) {
                if (user.get("LEARNERCATEGORY") != null && dict.getBIANMA().equals(user.getString("LEARNERCATEGORY"))) {
                    PageData pd1 = new PageData();
                    pd1.put("value", user.getString("USER_ID"));
                    pd1.put("label", user.getString("USERNAME") + " [" + user.getString("DEPARTMENTNAME") + " ]");
                    childrenList.add(pd1);
                }
            }
            if (childrenList.size() > 0) {
                pd0.put("children", childrenList);
                pdList.add(pd0);
            }
        }
        //未设置人员在线学习分类的放到其他里
        for (PageData user : userList) {
            if (user.get("LEARNERCATEGORY") == null) {
                PageData pd1 = new PageData();
                pd1.put("value", user.getString("USER_ID"));
                pd1.put("label", user.getString("USERNAME") + " [" + user.getString("DEPARTMENTNAME") + " ]");
                otherChildrenList.add(pd1);
            }
        }
        if (otherChildrenList.size() > 0) {
            other.put("children", otherChildrenList);
            pdList.add(other);
        }

        JSONArray arr = JSONArray.fromObject(pdList);
        String json = arr.toString();
        map.put("USER_ID", Jurisdiction.getUSER_ID());
        map.put("CascaderNodes", json);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 显示列表listCascader
     *
     * @return
     */
    @RequestMapping(value = "/listCascaderByDeptLevel")
//	// @RequiresPermissions("department:list")
    @ResponseBody
    @LogAnno(menuType = "监测预警", menuServer = "安全承诺", instructionsOperate = "公司级承诺公告", instructionsType = "显示列表listCascader")
    public Object listCascaderByDeptLevel() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        List<PageData> pdList = new ArrayList<PageData>();
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("PARENT_ID", "4a661fa8aedc4d158c9cddaa9d2ec47e"); //获取部门级别数据
        List<Dictionaries> dictList = dictionariesService.listSubDictByParent(pd);
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        List<PageData> userList = this.usersService.listCascader(pd);    //获取单位下的所有人员

        for (Dictionaries dict : dictList) {
            PageData pd0 = new PageData();
            pd0.put("value", dict.getBIANMA());
            pd0.put("label", dict.getNAME());
            List<PageData> childrenList = new ArrayList<PageData>();
            for (PageData user : userList) {
                PageData pd1 = new PageData();
                pd1.put("value", user.getString("USER_ID"));
                pd1.put("label", user.getString("USERNAME") + " [" + user.getString("DEPARTMENTNAME") + " ]");
                childrenList.add(pd1);
            }
            if (childrenList.size() > 0) {
                pd0.put("children", childrenList);
                pdList.add(pd0);
            }
        }
        //未设置人员在线学习分类的放到其他里
//		PageData other = new PageData();
//		other.put("value", "-");
//		other.put("label", "其他");
//		List<PageData> otherChildrenList = new ArrayList<PageData>();
//		for (PageData user : userList ) {
//			if (user.get("LEARNERCATEGORY") == null) {
//				PageData pd1 = new PageData();
//				pd1.put("value", user.getString("USER_ID"));
//				pd1.put("label", user.getString("USERNAME")+" [" + user.getString("DEPARTMENTNAME") + " ]");
//				otherChildrenList.add(pd1);
//			}
//		}
//		if (otherChildrenList.size() > 0) {
//			other.put("children", otherChildrenList);
//			pdList.add(other);
//		}

        JSONArray arr = JSONArray.fromObject(pdList);
        String json = arr.toString();
        map.put("USER_ID", Jurisdiction.getUSER_ID());
        map.put("CascaderNodes", json);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 修改用户签字信息状态
     * 安全生产机构负责人 和 记录人员
     *
     * @throws Exception
     */
    @RequestMapping(value = "/updataSignType")
    @ResponseBody
    @LogAnno(menuType = "教育培训", menuServer = "签字信息管理", instructionsOperate = "签字信息管理", instructionsType = "修改用户签字信息状态")
    public Object updataSignType() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        String msg = "";
        PageData pd = new PageData();
        pd = this.getPageData();

        PageData userInfo = userInfoService.findById(pd);// 获取用户的详情信息.没有的就是没有签字的
        if (null == userInfo || Tools.isEmpty(userInfo.get("USER_SIGN_FILE_PATH"))) {
            errInfo = "error";
            msg = "未找到用户签字信息！请该用户先在APP中设置签字信息";
            map.put("result", errInfo);
            map.put("msg", msg);
            return map;
        }
        PageData updatePd = new PageData();
        updatePd.put("USER_ID", userInfo.getString("USER_ID"));
        if (!Tools.isEmpty(pd.get("type"))) {// IS_RECORDER  IS_RECORDER
            if ("IS_RECORDER".equals(pd.get("type").toString())) {
                updatePd.put("IS_RECORDER", pd.getString("state"));
            }
            if ("IS_CHARGE".equals(pd.get("type").toString())) {
                updatePd.put("IS_CHARGE", pd.getString("state"));
            }
            userInfoService.editUserSignType(updatePd);
        }
        map.put("result", errInfo);
        map.put("msg", msg);
        return map;
    }

    /**
     * 列表
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/listAllByCorp")
    @ResponseBody
    @LogAnno(menuType = "监测预警", menuServer = "在线监测", instructionsOperate = "智能预警", instructionsType = "列表")
    public Object listAllByCorp() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        List<PageData> userList = usersService.listAllUser(pd);    //列出Post列表
        map.put("userList", userList);
        map.put("result", errInfo);
        return map;
    }
}
