

package com.ruoyi.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.PostCheckedConfig;
import com.ruoyi.common.constant.DeletedEnum;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.SysDeptEnum;
import com.ruoyi.common.utils.AesUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.cnooc.Dept;
import com.ruoyi.system.domain.cnooc.User;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时任务：同步工业互联网的部门信息、人员信息
 *
 * @author ruoyi
 */
@Data
@Slf4j
@Component("postCheckSystemTask")
public class PostCheckSystemTask {

    private static int index = 0;

    @Autowired
    private PostCheckedConfig config;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;

    /**
     * 同步统一认证的部门信息
     * 注意：方法名不要修改，配置到定时任务中了。
     */
    public void runDept() {
        index++;
        log.info("【同步部门】开始");

        //4.1.2获取组织机构 http://10.152.70.4:8040/authority/Org/orgList?gsid=17
        Map<String, Object> param = new HashMap<>();
        param.put("gsid", 17);
        String backResult = null;
        try {
//            backResult = restTemplate.getForObject("http://10.152.70.4:8040/authority/Org/orgList?gsid={gsid}", String.class, param);
            backResult = restTemplate.getForObject(config.getSyncDept(), String.class, param);
        } catch (Exception e) {
            e.printStackTrace();
//            backResult = runDeptDataTest();
        }
        log.info("【同步部门】查询接口返回的数据：{}", backResult);
        if (StringUtils.isBlank(backResult)) {
            log.info("【同步部门】本次查询无数据返回");
            log.info("【同步部门】结束");
            return;
        }

        List<Dept> deptList = JSON.parseArray(backResult, Dept.class);
//        System.out.println("list = " + deptList);
//        System.out.println("list = " + JSON.toJSONString(deptList));

        if (CollectionUtils.isEmpty(deptList)) {
            log.info("【同步部门】本次查询无数据返回");
            log.info("【同步部门】结束");
            return;
        }
        for (Dept dept : deptList) {
            List<Dept.ChildrenDept> children = dept.getChildren();
            if (CollectionUtils.isEmpty(deptList)) {
                continue;
            }

            for (Dept.ChildrenDept child : children) {
                Long parentId = child.getParentId();
                //统一认证部门ID存储在sourceId字段上，然后截取前4位后放到部门表deptId主键上，因为雪花ID太长，作为主键的话，VUE会精度丢失
                Long deptId = child.getDeptId();
                String deptName = child.getDeptName();
                String deptCode = child.getDeptCode();
                Integer orderNum = child.getOrderNum();

                SysDept sysDept = new SysDept();
                if (parentId.toString().length() > 16) {
                    sysDept.setParentId(Long.parseLong(parentId.toString().substring(4)));
                } else {
                    sysDept.setParentId(parentId);
                }
                //仅大于16位时才截取
                if (deptId.toString().length() > 16) {
                    sysDept.setDeptId(Long.parseLong(deptId.toString().substring(4)));
                } else {
                    sysDept.setDeptId(deptId);
                }

                sysDept.setDeptName(deptName);
                sysDept.setDeptCode(deptCode);
                sysDept.setOrderNum(orderNum);
                //默认参数
//                sysDept.setType(SysDeptEnum.TYPE_OTHER.getValue());
//                sysDept.setCreateBy("System");
//                sysDept.setCreateTime(DateUtils.getNowDate());
                sysDept.setUpdateBy("SYSTEM");
                sysDept.setUpdateTime(DateUtils.getNowDate());
                sysDept.setDelFlag(DeletedEnum.VALID.getValue());

//                SysDept sysDeptDB = deptService.selectDeptById(deptId);
                SysDept sysDeptDB = deptService.selectDeptBySourceId(deptId.toString());
                //新增
                if (sysDeptDB == null) {
                    sysDept.setSourceId(deptId.toString());
                    //默认参数
                    sysDept.setType(SysDeptEnum.TYPE_OTHER.getValue());
                    sysDept.setCreateBy("SYSTEM");
                    sysDept.setCreateTime(DateUtils.getNowDate());
//                    sysDept.setUpdateBy("System");
//                    sysDept.setUpdateTime(DateUtils.getNowDate());
//                    sysDept.setDelFlag(DeletedEnum.VALID.getValue());
                    int insertCount = deptService.insertDeptCnooc(sysDept);
                    log.info("【同步部门】插入部门的deptId={}，数量{}", deptId, insertCount);
                }
                //修改
                else {
                    //部门类型自己设置，不更新：1 职能部门 2 生产部门 3 其他
                    sysDept.setType(sysDeptDB.getType());
                    int updateCount = deptService.updateDeptCnooc(sysDept);
                    log.info("【同步部门】更新部门的deptId={}，数量{}", deptId, updateCount);

                }

            }
        }


        log.info("【同步部门】结束");
    }


    /**
     * 同步统一认证的用户信息：查询部门再遍历
     * 注意：方法名不要修改，配置到定时任务中了。
     */
    public void runUser() {
        index++;
        log.info("【同步用户】开始");

        List<SysDept> deptList = deptService.syncSelectDeptList();
        if (CollectionUtils.isEmpty(deptList)) {
            log.info("【同步用户】本地部门表无数据，直接退出");
            log.info("【同步用户】结束");
            return;
        }

        for (SysDept dept : deptList) {
            try {
                Long deptId = Long.parseLong(dept.getSourceId());//数据源的部门ID，下面的请求数据源接口的参数
                String deptName = dept.getDeptName();
                syncUser(deptId, deptName);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    Thread.sleep(666l);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }


        log.info("【同步用户】结束");
    }

    /**
     * 同步用户信息
     *
     * @param deptId
     * @param deptName
     */
    private void syncUser(Long deptId, String deptName) {
        log.info("【同步用户】{}, deptId={}, deptName={}", index, deptId, deptName);
        if (deptId == null)
            return;
        //4.1.4获取组织机构和用户  http://10.152.70.4:8040/authority/User/selectUserLists?orgId=54
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", deptId);
        String backResult = null;
        try {
//            backResult = restTemplate.getForObject("http://10.152.70.4:8040/authority/User/selectUserLists?orgId={orgId}", String.class, param);
            backResult = restTemplate.getForObject(config.getSyncUser(), String.class, param);
        } catch (Exception e) {
            e.printStackTrace();
//            if (index % 2 == 0)
//                backResult = runUserDataTest01();
//            else
//                backResult = runUserDataTest02();

            /*
            try {
//                String path = "C:/gnhz/syncUserError.txt";
                String path = "/opt/postcheck/jar/syncUserError.txt";
                File file = new File(path);
                if (!file.exists()) {
                    file.mkdirs();
                }
                Files.write(Paths.get(path), ("\r\n" + DateUtils.getTime() + "\t" + deptId + "=" + deptName + "\r\n" + e.getMessage()).getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);
            } catch (Exception ee) {
                ee.printStackTrace();
            }
            */
        }
//        log.info("【同步用户】查询接口返回的数据：{}", backResult);
        /*
        try {
//            String path = "C:/gnhz/syncUserBackResult.txt";
            String path = "/opt/postcheck/jar/syncUserBackResult.txt";
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            Files.write(Paths.get(path), ("\r\n" + DateUtils.getTime() + "\t" + deptId + "=" + deptName + "\r\n" + backResult).getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);
        } catch (Exception e) {
            e.printStackTrace();
        }
        */

        if (StringUtils.isBlank(backResult)) {
            log.info("【同步用户】本次查询无数据返回deptId={}, deptName={}", index, deptId, deptName);
            return;
        }

        List<User> userList = JSON.parseArray(backResult, User.class);
//        System.out.println("list = " + userList);
//        System.out.println("list = " + JSON.toJSONString(userList));
        if (CollectionUtils.isEmpty(userList)) {
            log.info("【同步用户】本次查询无数据返回deptId={}, deptName={}", index, deptId, deptName);
            return;
        }


        log.info("【同步用户】返回用户数量：{}", userList);


        for (User user : userList) {
            List<User.ChildrenUser> children = user.getChildren();
            if (CollectionUtils.isEmpty(children)) {
                return;
            }
            deptId = user.getDeptId() != null ? user.getDeptId() : deptId;
            for (User.ChildrenUser child : children) {
                Long userId = child.getUserId();
                String userName = child.getUserName();
                String nickName = child.getNickName();
                String email = child.getEmail();

                SysUser sysUser = new SysUser();
                if (userId.toString().length() > 16) {
                    sysUser.setUserId(Long.parseLong(userId.toString().substring(4)));
                } else {
                    sysUser.setUserId(userId);
                }
                sysUser.setUserName(userName);
                sysUser.setNickName(nickName);
                sysUser.setEmail(email);
                //一定要和部门同步中设置为一致的长度，否则将无法匹配部门
                if (deptId.toString().length() > 16) {
                    sysUser.setDeptId(Long.parseLong(deptId.toString().substring(4)));
                } else {
                    sysUser.setDeptId(deptId);
                }
                //默认参数
                sysUser.setUpdateBy("SYSTEM");
                sysUser.setUpdateTime(DateUtils.getNowDate());
                sysUser.setDelFlag(DeletedEnum.VALID.getValue());

//                SysUser sysUserDB = userService.selectUserById(userId);
                SysUser sysUserDB = userService.selectUserBySourceId(userId.toString());
                //新增
                if (sysUserDB == null) {
                    sysUser.setSourceId(userId.toString());
                    sysUser.setCreateBy("SYSTEM");
                    sysUser.setCreateTime(DateUtils.getNowDate());
//                    sysUser.setPassword(SecurityUtils.encryptPassword("post@2023"));
                    String userPassword = config.getDefaultUserPassword();
                    sysUser.setPassword(SecurityUtils.encryptPassword(userPassword));
                    sysUser.setCasUserPback(AesUtil.aesEncrypt(userPassword, AesUtil.aesKey));//加密
                    int insertCount = userService.insertUserCnooc(sysUser);
                    log.info("【同步用户】插入用户的userId={}，数量{}", userId, insertCount);
                }
                //修改
                else {
                    int updateCount = userService.updateUserCnooc(sysUser);
                    log.info("【同步用户】更新用户的userId={}，数量{}", userId, updateCount);
                }
            }
        }
    }

    /**
     * 模拟接口部门数据
     *
     * @return
     */
    private String runDeptDataTest() {
        return "[\n" +
                "    {\n" +
                "        \"orgName\": \"惠州石化\",\n" +
                "        \"orgList\": [\n" +
                "            {\n" +
                "                \"orgid\": \"18\",\n" +
                "                \"orgname\": \"统一认证公司领导-" + index + "\",\n" +
                "                \"orgorder\": 1,\n" +
                "                \"gsid\": \"17\",\n" +
                "                \"zhaoshang\": 1,\n" +
                "                \"orgtype\": 0,\n" +
                "                \"orgcode\": \"2000\",\n" +
                "                \"upper_uid\": null,\n" +
                "                \"organtype\": \"0\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"orgid\": \"19\",\n" +
                "                \"orgname\": \"统一认证运行一部-" + index + "\",\n" +
                "                \"orgorder\": 2,\n" +
                "                \"gsid\": \"17\",\n" +
                "                \"zhaoshang\": 1,\n" +
                "                \"orgtype\": 1,\n" +
                "                \"orgcode\": \"1001\",\n" +
                "                \"upper_uid\": null,\n" +
                "                \"organtype\": \"0\"\n" +
                "            }\n" +
                "        ],\n" +
                "        \"orgid\": 17\n" +
                "    }\n" +
                "]";
    }


    private String runUserDataTest01() {
        return "[\n" +
                "    {\n" +
                "        \"userList\": [\n" +
                "            {\n" +
                "                \"cid\": 101,\n" +
                "                \"userid\": \"coonc101\",\n" +
                "                \"username\": \"统一认证公司领导-用户1-" + index + "\",\n" +
                "                \"depart\": \"19\",\n" +
                "                \"useremail\": \"xxx" + index + "@cnooc.com.cn\",\n" +
                "                \"sex\": null,\n" +
                "                \"iphone\": null,\n" +
                "                \"birth\": null\n" +
                "            },\n" +
                "            {\n" +
                "                \"cid\": 102,\n" +
                "                \"userid\": \"coonc102\",\n" +
                "                \"username\": \"统一认证公司领导-用户2-" + index + "\",\n" +
                "                \"useremail\": \"xxx" + index + "@cnooc.com.cn\",\n" +
                "                \"depart\": \"19\",\n" +
                "                \"sex\": null,\n" +
                "                \"iphone\": null,\n" +
                "                \"birth\": null\n" +
                "            }\n" +
                "        \n" +
                "        ],\n" +
                "        \"deptid\": \"18\",\n" +
                "        \"deptname\": \"统一认证公司领导\"\n" +
                "    }\n" +
                "]";
    }


    private String runUserDataTest02() {
        return "[\n" +
                "    {\n" +
                "        \"userList\": [\n" +
                "            {\n" +
                "                \"cid\": 201,\n" +
                "                \"userid\": \"coonc201\",\n" +
                "                \"username\": \"统一认证运行一部-用户1-" + index + "\",\n" +
                "                \"useremail\": \"xxx" + index + "@cnooc.com.cn\",\n" +
                "                \"depart\": \"18\",\n" +
                "                \"sex\": null,\n" +
                "                \"iphone\": null,\n" +
                "                \"birth\": null\n" +
                "            },\n" +
                "            {\n" +
                "                \"cid\": 202,\n" +
                "                \"userid\": \"coonc202\",\n" +
                "                \"username\": \"统一认证运行一部-用户2-" + index + "\",\n" +
                "                \"useremail\": \"xxx" + index + "@cnooc.com.cn\",\n" +
                "                \"depart\": \"18\",\n" +
                "                \"sex\": null,\n" +
                "                \"iphone\": null,\n" +
                "                \"birth\": null\n" +
                "            }\n" +
                "        \n" +
                "        ],\n" +
                "        \"deptid\": \"18\",\n" +
                "        \"deptname\": \"统一认证运行一部\"\n" +
                "    }\n" +
                "]";
    }

    public static void main(String[] args) {
//        Hzsh.eitc@6626.admin = 9888DE88B93ADE3C2F1CF21B3DA5490F1622B52E75C2ED57CD0A3ED8FC621339
//        Hzsh.eitc@6626.user = 57E00682ED216BB1160100FE7EE9B350111E72584087752289390438A67FBDFA

//        String aesEncrypt = AesUtil.aesEncrypt("Hzsh.eitc@6626.admin", AesUtil.aesKey);
        String aesEncrypt = AesUtil.aesEncrypt("Hzsh.eitc@6626.user", AesUtil.aesKey);
        System.out.println("aesEncrypt = " + aesEncrypt);

        String aesDecrypt = AesUtil.aesDecrypt("D87E964E44C6792A6E433F85B13EC1B6", AesUtil.aesKey);
        System.out.println("aesDecrypt = " + aesDecrypt);
        if (true) {
            return;
        }

        PostCheckSystemTask systemTask = new PostCheckSystemTask();
        String backResult = systemTask.runDeptDataTest();
        System.out.println("部门-接口JSON数据 = " + backResult);

        List<Dept> deptList = JSON.parseArray(backResult, Dept.class);

        for (Dept dept : deptList) {
            List<Dept.ChildrenDept> children = dept.getChildren();
            for (Dept.ChildrenDept child : children) {

                System.out.println("child.getDeptName() = " + child.getDeptName());
            }
        }

        System.out.println();
        System.out.println();

        String backResultUser = systemTask.runUserDataTest01();
        System.out.println("用户-接口JSON数据 = " + backResultUser);
        List<User> userList = JSON.parseArray(backResultUser, User.class);
        for (User user : userList) {
            List<User.ChildrenUser> children = user.getChildren();
            for (User.ChildrenUser child : children) {
                String nickName = child.getNickName();
                System.out.println("nickName = " + nickName);
            }
        }


    }
}
