package com.malk.qiwang.Controller;

import com.malk.qiwang.Service.ICompanyTitleService;
import com.malk.qiwang.entity.CompanyTitle;
import com.malk.qiwang.mapper.CompanyTitleMapper;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * <p>
 * 公司抬头库表 前端控制器
 * </p>
 *
 * @author LQY
 * @since 2026-04-24
 */
@RestController
@RequestMapping("/qw1")
@Slf4j
public class CompanyTitleController {
@Autowired
private ICompanyTitleService companyTitleService;
@Autowired
private YDClient ydClient;
    @Autowired
    private DDClient_Workflow ddClientWorkflow ;
    @Autowired
    private DDClient ddClient;
    @Autowired
    private CompanyTitleMapper companyTitleMapper;
    @PostMapping("/companyTitle")
    public McR insertTransfer2(@RequestBody(required = false) Map<String, Object> map) {
        if (map == null) {
            map = new HashMap<>();
            log.info("请求体为空，使用默认参数");
        }
        log.info("接收到的参数: {}", map);

        // 获取参数
        String processCode = "PROC-187CB1F8-5BF0-403A-9D01-94EEF987DD77";

        // 设置时间范围（默认查询最近30天）
        Long startTime = System.currentTimeMillis() - 30L * 24 * 60 * 60 * 1000;
        Long endTime = System.currentTimeMillis();

        // 获取钉钉accessToken
        String accessToken = ddClient.getAccessToken();

        // 递归获取所有审批实例ID
        List<String> allInstanceIds = ddClientWorkflow.getInstanceIds_all(accessToken, processCode, startTime, endTime, null);

        log.info("共查询到 {} 条审批实例", allInstanceIds.size());

        // 批量处理审批实例
        int successCount = 0;
        int failCount = 0;

        for (String instanceId : allInstanceIds) {
            try {
                // 获取审批实例详情
                Map<String, Object> processInstance = ddClientWorkflow.getProcessInstanceId(accessToken, instanceId);

                if (processInstance != null) {
                    // 提取并保存公司抬头数据
                    boolean result = saveCompanyTitleFromInstance(processInstance);
                    if (result) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } else {
                    failCount++;
                }
            } catch (Exception e) {
                log.error("处理审批实例失败: instanceId={}", instanceId, e);
                failCount++;
            }
        }

        log.info("处理完成: 成功={}, 失败={}", successCount, failCount);

        return McR.success();
    }
    private boolean saveCompanyTitleFromInstance(Map<String, Object> processInstance) {
        List<Map<String, Object>> formComponentValues =
                (List<Map<String, Object>>) processInstance.get("formComponentValues");

        if (formComponentValues == null || formComponentValues.isEmpty()) {
            log.warn("表单数据为空");
            return false;
        }

        String tt = "", sh = "", dz = "", dh = "", yh = "", zh = "", zt = "";

        // 修复：安全获取审批时间，避免类型转换异常
        Long finishTime = null;
        Object finishTimeObj = processInstance.get("finishTime");
        if (finishTimeObj != null) {
            if (finishTimeObj instanceof Long) {
                finishTime = (Long) finishTimeObj;
            } else if (finishTimeObj instanceof String) {
                try {
                    finishTime = Long.parseLong((String) finishTimeObj);
                } catch (NumberFormatException e) {
                    log.warn("finishTime格式转换失败: {}", finishTimeObj);
                }
            } else if (finishTimeObj instanceof Integer) {
                finishTime = ((Integer) finishTimeObj).longValue();
            }
        }

        for (Map<String, Object> formComponentValue : formComponentValues) {
            String id = String.valueOf(formComponentValue.get("id"));
            String value = formComponentValue.get("value") != null ?
                    String.valueOf(formComponentValue.get("value")) : "";

            switch (id) {
                case "TextField-K2AD4O5B":
                    tt = value;
                    break;
                case "TextField_1JEUFYV5F4E80":
                    sh = value;
                    break;
                case "TextField_EJZY527VJXC0":
                    dz = value;
                    break;
                case "TextField_12YU12T3PZC0":
                    dh = value;
                    break;
                case "TextField_1Z4P9MQFOW3K0":
                    yh = value;
                    break;
                case "TextField_NUL1SS1PJQ80":
                    zh = value;
                    break;
                case "DDSelectField_528A36XIP9C0":
                    zt = value;
                    break;
                default:
                    break;
            }
        }

        if (StringUtils.isBlank(sh)) {
            log.warn("税号为空，跳过保存");
            return false;
        }

        // 打印日志查看税号
        log.info("处理税号: {}", sh);

        // 查询数据库中该税号的最新记录
        CompanyTitle existing = companyTitleMapper.selectByTaxId1(sh);

        // 打印查询结果
        log.info("查询数据库结果: existing={}", existing != null ? "存在" : "不存在");

        if (existing != null) {
            log.info("税号 {} 已存在，执行更新操作", sh);

            // 比较审批时间，判断是否为最新数据
            if (finishTime != null && existing.getUpdatedAt() != null) {
                long existingTime = existing.getUpdatedAt().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                if (finishTime <= existingTime) {
                    log.debug("当前审批数据不是最新，跳过更新: taxId={}, 审批时间={}, 数据库更新时间={}",
                            sh, finishTime, existingTime);
                    return false;
                }
            }

            // 更新现有记录
            existing.setCompanyName(tt);
            existing.setAddress(dz);
            existing.setPhone(dh);
            existing.setBankName(yh);
            existing.setBankAccount(zh);
            existing.setStatus("启用".equals(zt) ? (byte) 0 : (byte) 1);
            existing.setUpdatedAt(LocalDateTime.now());

            int updateResult = companyTitleMapper.updateById(existing);
            log.info("更新结果: {}, 税号: {}", updateResult, sh);

            if (updateResult > 0) {
                log.info("公司抬头更新成功: taxId={}, 审批时间={}", sh, finishTime);
            } else {
                log.warn("公司抬头更新失败: taxId={}", sh);
                return false;
            }
        } else {
            // 税号不存在时才新增
            log.info("税号 {} 不存在，执行新增操作", sh);

            CompanyTitle companyTitle = new CompanyTitle();
            companyTitle.setCompanyName(tt);
            companyTitle.setTaxId(sh);
            companyTitle.setAddress(dz);
            companyTitle.setPhone(dh);
            companyTitle.setBankName(yh);
            companyTitle.setBankAccount(zh);
            companyTitle.setStatus("启用".equals(zt) ? (byte) 0 : (byte) 1);
            companyTitle.setCreatedAt(LocalDateTime.now());
            companyTitle.setUpdatedAt(LocalDateTime.now());

            int insertResult = companyTitleMapper.insert(companyTitle);
            log.info("新增结果: {}, 税号: {}", insertResult, sh);

            if (insertResult > 0) {
                log.info("公司抬头新增成功: taxId={}", sh);
            } else {
                log.warn("公司抬头新增失败: taxId={}", sh);
                return false;
            }
        }

        companyTitleMapper.delZT();
        return true;
    }
}
