package org.springblade.zhonnjian.task;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.utils.DigestUtil;
import org.springblade.wecom.entity.BladeDept;
import org.springblade.wecom.entity.BladeUser;
import org.springblade.wecom.entity.BladeUserDept;
import org.springblade.wecom.service.IBladeDeptService;
import org.springblade.wecom.service.IBladeUserService;
import org.springblade.zhonnjian.entity.UserInfoHuamingce;
import org.springblade.zhonnjian.service.IUserInfoHuamingceService;
import org.springblade.zhonnjian.service.ZjBladeUserDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
//@EnableAsync
@Slf4j
public class FileToOssMonthTask {

    @Autowired
    private IBladeDeptService bladeDeptService;

    @Autowired
    private IBladeUserService bladeUserService;

    @Autowired
    private ZjBladeUserDeptService bladeUserDeptService;

    @Autowired
    private IUserInfoHuamingceService userInfoHuamingceService;


    @Value("${weCom.roleId}")
    private String roleId;

    @Value("${weCom.tenantId}")
    private String tenantId;




    //@Scheduled(fixedRate = 10000000)
    @Scheduled(cron = "0 0 1 * * ?")  // 每天凌晨1:00执行
    public void syncDeptAndUserFromMdm() {
        String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        log.info("开始同步MDM组织架构数据，开始时间：{}", startTime);
        try {
            String accessToken = getAccessToken();
            if (StringUtils.isNotBlank(accessToken)) {
                // 同步部门数据，并获取MDM编码到部门ID的映射  同步人员数据，使用部门映射关系
                syncDeptData(accessToken);
                String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                log.info("MDM组织架构数据同步完成，开始时间：{}，结束时间：{}", startTime, endTime);
            }
        } catch (Exception e) {
            String errorTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            log.error("MDM组织架构数据同步失败，开始时间：{}，失败时间：{}", startTime, errorTime, e);
            throw new RuntimeException(e);
        }
    }

    private JSONArray getAllTreeData(String accessToken) {
        JSONArray allData = new JSONArray();
        int page = 1;
        final int pageSize = 500;
        boolean isLastPage = false;

        while (!isLastPage) {
            JSONObject response = getTree(accessToken, page, pageSize);
            if (response != null) {
                // 检查返回结果是否成功
                if (!"S".equals(response.getString("RESULT"))) {
                    log.error("获取部门数据失败: RESULT={}, MESSAGE={}",
                            response.getString("RESULT"),
                            response.getString("MESSAGE"));
                    break;
                }

                // 获取当前页的数据并添加到总列表中
                JSONArray currentPageData = response.getJSONArray("DATA");
                if (currentPageData != null && !currentPageData.isEmpty()) {
                    allData.addAll(currentPageData);
                }

                // 检查是否是最后一页
                isLastPage = response.getBooleanValue("LAST_PAGE");
                log.info("获取部门第{}页数据，本页数据量: {}", page,
                        currentPageData != null ? currentPageData.size() : 0);
                page++;
            } else {
                log.error("获取部门数据失败: 响应为空");
                break;
            }
        }

        log.info("部门数据获取完成，总数据量: {}", allData.size());
        return allData;
    }


    private JSONArray getAllHumanData(String accessToken) {
        JSONArray allData = new JSONArray();
        int page = 1;
        final int pageSize = 500;
        boolean isLastPage = false;

        while (!isLastPage) {
            JSONObject response = getHuman(accessToken, page, pageSize);
            if (response != null) {
                // 检查返回结果是否成功
                if (!"S".equals(response.getString("RESULT"))) {
                    log.error("获取人员数据失败: RESULT={}, MESSAGE={}",
                            response.getString("RESULT"),
                            response.getString("MESSAGE"));
                    break;
                }
                // 获取当前页的数据并添加到总列表中
                JSONArray currentPageData = response.getJSONArray("DATA");
                if (currentPageData != null && !currentPageData.isEmpty()) {
                    allData.addAll(currentPageData);
                }
                // 检查是否是最后一页
                isLastPage = response.getBooleanValue("LAST_PAGE");
                log.info("获取人员数据第{}页，本页数据量: {}", page,
                        currentPageData != null ? currentPageData.size() : 0);
                page++;
            } else {
                log.error("获取人员数据失败: 响应为空");
                break;
            }
        }
        log.info("人员数据获取完成，总数据量: {}", allData.size());
        return allData;
    }


    private void syncDeptData(String accessToken) {
        JSONArray allTreeData = getAllTreeData(accessToken);
        if (!allTreeData.isEmpty()) {
            log.info("开始同步部门数据，总条数: {}", allTreeData.size());
            // 第一次遍历：保存或更新部门基本信息
            Map<String, Long> mdmCodeToDeptId = new HashMap<>();
            for (int i = 0; i < allTreeData.size(); i++) {
                JSONObject deptJson = allTreeData.getJSONObject(i);
                String mdmCode = deptJson.getString("MDM_CODE");
                Long wechatId = deptJson.getLong("WECHAT_ID");

                try {
                    if (wechatId == null) {
                        log.info("部门 wechatId 为空 : {}", deptJson.getString("MDM_NAME"));
                        continue;
                    }
                    // 查询现有部门
                    BladeDept existingDept = bladeDeptService.getOne(new LambdaQueryWrapper<BladeDept>()
                            .eq(BladeDept::getId, wechatId)
                            .eq(BladeDept::getIsDeleted, 0)
                            .eq(BladeDept::getTenantId, tenantId)
                    );

                    BladeDept dept = convertJsonToDept(deptJson);
                    if (existingDept == null) {
                        // 新增部门
                        bladeDeptService.save(dept);
                        log.info("新增部门: {}", dept.getDeptName());
                        mdmCodeToDeptId.put(mdmCode, dept.getId());
                    } else {
                        mdmCodeToDeptId.put(mdmCode, existingDept.getId());
                        if (StringUtils.isBlank(existingDept.getDeptCode())) {
                            log.info("原部门数据补齐关联字段值: {},{}", dept.getDeptName(), dept.getDeptCode());
                            existingDept.setDeptCode(dept.getDeptCode());
                            bladeDeptService.updateById(existingDept);
                        }
                    }
                } catch (Exception e) {
                    log.error("处理部门数据失败, mdmCode: {}", mdmCode, e);
                }
            }

            // 第二次遍历：更新部门的父级关系
            for (int i = 0; i < allTreeData.size(); i++) {
                JSONObject deptJson = allTreeData.getJSONObject(i);
                String mdmCode = deptJson.getString("MDM_CODE");
                String parentMdmCode = deptJson.getString("PARENT_MDM_CODE");

                try {
                    if (StringUtils.isNotBlank(parentMdmCode)) {
                        Long deptId = mdmCodeToDeptId.get(mdmCode);
                        Long parentId = mdmCodeToDeptId.get(parentMdmCode);

                        if (deptId != null && parentId != null) {
                            // 更新部门的父级ID
                            boolean updated = bladeDeptService.lambdaUpdate()
                                    .eq(BladeDept::getId, deptId)
                                    .eq(BladeDept::getIsDeleted, 0)
                                    .set(BladeDept::getParentId, parentId)
                                    .update();
                            if (updated) {
                                log.info("更新部门[{}]的父级关系，父级部门ID,编码: {},{}", mdmCode, parentId, parentMdmCode);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("更新部门父级关系失败, mdmCode: {}", mdmCode, e);
                }
            }
            syncUserData(accessToken, mdmCodeToDeptId);
        }
    }


    private void syncUserData(String accessToken, Map<String, Long> mdmCodeToDeptId) {
        JSONArray allHumanData = getAllHumanData(accessToken);
        if (!allHumanData.isEmpty()) {
            log.info("开始同步人员数据，总条数: {}", allHumanData.size());

            for (int i = 0; i < allHumanData.size(); i++) {
                JSONObject userJson = allHumanData.getJSONObject(i);
                String thirdUserId = userJson.getString("USER_ID");
                String deptCode = userJson.getString("DEPT"); // 部门的MDM编码
                String credentialNo = userJson.getString("CREDENTIAL_NO"); //身份证号
                String phoneNum = userJson.getString("PHONE_NUM"); //手机号

                try {
                    // 查询现有用户
                    BladeUser existingUser = bladeUserService.getOne(new LambdaQueryWrapper<BladeUser>()
                            .eq(BladeUser::getThirdUserId, thirdUserId)
                            .eq(BladeUser::getIsDeleted, 0)
                            .eq(BladeUser::getTenantId, tenantId)
                    );
                    // 获取部门ID
                    Long deptId = mdmCodeToDeptId.get(deptCode);
                    if (deptId == null) {
                        log.error("用户[{}]的部门[{}]不存在", thirdUserId, deptCode);
                        continue;
                    }

                    BladeUser user = convertJsonToUser(userJson);

                    if (existingUser == null) {
                        // 新增用户
                        user.setDeptId(deptId.toString());
                        bladeUserService.save(user);
                        // 设置用户部门关系
                        bladeUserDeptService.updateUserDept(user.getId(), deptId);
                        log.info("新增用户部门关系-用户: {}, 部门: {}", user.getName(), deptId);
                    } else {
                        // 更新用户部门信息
                        if (!deptId.toString().equals(existingUser.getDeptId())) {  // 只有当部门ID发生变化时才更新
                            // 更新用户部门信息
                            boolean updated = bladeUserService.lambdaUpdate()
                                    .eq(BladeUser::getId, existingUser.getId())
                                    .eq(BladeUser::getIsDeleted, 0)
                                    .set(BladeUser::getDeptId, deptId.toString())
                                    .update();
                            if (updated) {
                                log.info("更新用户[{}] [{}] 的部门关系，原部门,新部门: {},{}", existingUser.getName(),existingUser.getId(), existingUser.getDeptId(), deptId);
                            }
                        }

                        // 更新用户身份证信息
                        if (StringUtils.isNotBlank(credentialNo) && StringUtils.isBlank(existingUser.getFaceUserId())) {
                            // 更新用户身份证信息
                            boolean updated = bladeUserService.lambdaUpdate()
                                    .eq(BladeUser::getId, existingUser.getId())
                                    .eq(BladeUser::getIsDeleted, 0)
                                    .set(BladeUser::getFaceUserId, credentialNo)
                                    .update();
                            if (updated) {
                                log.info("更新用户[{}] 的身份证号[{}]", existingUser.getName(),credentialNo);
                            }
                        }

                        // 更新用户账号信息及手机号信息
                        if (!phoneNum.equals(existingUser.getAccount())) {
                            // 更新用户身份证信息
                            boolean updated = bladeUserService.lambdaUpdate()
                                    .eq(BladeUser::getId, existingUser.getId())
                                    .eq(BladeUser::getIsDeleted, 0)
                                    .set(BladeUser::getAccount, phoneNum)
                                    .set(BladeUser::getPhone, phoneNum)
                                    .update();
                            if (updated) {
                                log.info("更新用户[{}] 的账号及手机号：原手机号 = {}，现手机号 = {}", existingUser.getName(),existingUser.getAccount(),phoneNum);
                            }
                        }

                        // 检查并更新部门关系
                        BladeUserDept userDept = bladeUserDeptService.getOne(new LambdaQueryWrapper<BladeUserDept>()
                                .eq(BladeUserDept::getUserId, existingUser.getId().toString())
                        );
                        if (userDept == null || !userDept.getDeptId().equals(deptId)) {
                            // 更新用户部门关系
                            bladeUserDeptService.updateUserDept(existingUser.getId(), deptId);
                            log.info("更新用户部门关系: 用户 {} 部门 {}", user.getName(), deptId);
                        }
                    }

                } catch (Exception e) {
                    log.error("处理用户数据失败, thirdUserId: {}", thirdUserId, e);
                }
            }
        }
    }

    private BladeUser convertJsonToUser(JSONObject json) {
        BladeUser user = new BladeUser();
        user.setTenantId(tenantId);
        user.setAccount(json.getString("PHONE_NUM"));
        user.setName(json.getString("MDM_NAME"));
        user.setRealName(json.getString("MDM_NAME"));
        user.setEmail(json.getString("EMAIL"));
        user.setPhone(json.getString("PHONE_NUM"));
        user.setIsDeleted(0);
        user.setIsLogin(0);
        user.setIsWxLogin(0);
        user.setLoginStatus(0);
        user.setUserAttr(0);
        user.setThirdUserId(json.getString("USER_ID"));
        user.setFaceUserId(json.getString("CREDENTIAL_NO"));
        //user.setDeptId(id.toString());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setPassword(DigestUtil.encrypt("zjbj@2024"));
        user.setRoleId(roleId);
        return user;
    }


    private BladeDept convertJsonToDept(JSONObject json) {
        BladeDept dept = new BladeDept();
        dept.setTenantId(tenantId);
        dept.setId(json.getLong("WECHAT_ID"));
        dept.setDeptName(json.getString("MDM_NAME"));
        dept.setFullName(json.getString("MDM_NAME"));
        dept.setDeptCode(json.getString("MDM_CODE")); // 使用MDM_CODE作为deptCode
        //dept.setParentId(json.getString("PARENT_MDM_CODE"));
        dept.setDeptCategory(1);
        dept.setIsDeleted(0);
        return dept;
    }


    /**
     * 主数据API token
     *
     * @return
     */
    private String getAccessToken() {
        Map<String, Object> formMap = new HashMap<>();
        formMap.put("APP_ID", "7cf6631251e949a8b0193de0062be49e");
        formMap.put("APP_KEY", "0218756eb8d94512a303de71e33b7220");
        String res = HttpUtil.createGet("https://dec.cscec8st.com.cn:50024/demdm-api/open/api/getToken").form(formMap).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(res);
        log.info("jsonObject = {}", jsonObject.toJSONString());
        if (Objects.nonNull(jsonObject.get("code")) && "ok".equals(jsonObject.getString("code"))) {
            return jsonObject.getJSONObject("data").getString("token");
        }
        throw new RuntimeException("主数据获取Token失败|res=" + res);
    }


    /**
     * 获取组织树架构数据
     *
     * @param accessToken
     * @param page
     * @param pageSize
     * @return
     */
    private JSONObject getTree(String accessToken, Integer page, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        map.put("FORM_CODE", "TREE");
        map.put("UUID", "16184989241DD8843F87B0F3BA753RTY");
        map.put("PAGE", page);
        map.put("PAGE_SIZE", pageSize);
        map.put("DATA", dataMap);
        String param = JSON.toJSONString(map);

        HashMap<String, String> headers = new HashMap<>();
        headers.put("demdmtoken", accessToken);
        headers.put("Content-Type", "application/json");

        String result = HttpUtil.createPost("https://dec.cscec8st.com.cn:50024/demdm-api/open/api/v2/selectApi/TREE")
                .headerMap(headers, true)
                .body(param)
                .execute()
                .body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }


    /**
     * 获取人员主数据
     *
     * @param accessToken
     * @param page
     * @param pageSize
     * @return
     */
    private JSONObject getHuman(String accessToken, Integer page, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        map.put("FORM_CODE", "HUMAN");
        map.put("UUID", "16184989241DD8843F87B0F3BA753RTY");
        map.put("PAGE", page);
        map.put("PAGE_SIZE", pageSize);
        map.put("DATA", dataMap);
        String param = JSON.toJSONString(map);

        HashMap<String, String> headers = new HashMap<>();
        headers.put("demdmtoken", accessToken);
        headers.put("Content-Type", "application/json");
        String result = HttpUtil.createPost("https://dec.cscec8st.com.cn:50024/demdm-api/open/api/v2/selectApi/HUMAN1")
                .headerMap(headers, true)
                .body(param)
                .execute()
                .body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }


}


