package com.malk.qiwang.Service.impl;

import com.malk.qiwang.Service.TXYInvoice;
import com.malk.qiwang.entity.CompanyTitle;
import com.malk.qiwang.mapper.CompanyTitleMapper;
import com.malk.qiwang.Service.ICompanyTitleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 公司抬头库表 服务实现类
 * </p>
 *
 * @author LQY
 * @since 2026-04-24
 */
@Service
@Slf4j
public class CompanyTitleServiceImpl extends ServiceImpl<CompanyTitleMapper, CompanyTitle> implements ICompanyTitleService {
    @Autowired
    private DDClient ddClient;
    @Autowired
    private YDClient ydClient;
    @Autowired
    private TXYInvoice txyInvoice;
    @Value("${dingtalk.operator}")
    private String operator;
    @Value("${dingtalk.downloadPath}")
    private String downloadPath;
    @Autowired
    private DDClient_Workflow ddClientWorkflow ;
    @Autowired
    private DDClient_Contacts ddClient_contacts;
    private static final String url = "http://20f2fcef.r39.cpolar.top/qiwang/";
    @Autowired
    private CompanyTitleMapper companyTitleMapper;  // 或者使用 Mapper
    @Override
    public void insertCompanyTitle(Map map) {
        log.info("map:{}", map);
        String processInstanceId = UtilMap.getString(map, "processInstanceId");
        String action = UtilMap.getString(map, "action");
        String nsh = UtilMap.getString(map, "nsh");
        // 删除操作
        if ("del".equals(action)) {
            // 根据税号删除
            if (nsh != null && !nsh.isEmpty()) {
                int result = companyTitleMapper.deleteByTaxId(nsh);
                if (result > 0) {
                    log.info("公司抬头删除成功: 税号={}", nsh);
                } else {
                    log.warn("公司抬头删除失败: 税号={} 不存在", nsh);
                }
            } else {
                log.warn("删除操作失败: 税号为空");
            }
            return; // 删除操作完成后直接返回
        }

        // 新增操作（原有逻辑）
        Map processInstance = ddClientWorkflow.getProcessInstanceId(ddClient.getAccessToken(), processInstanceId);

        if (Objects.nonNull(processInstance)) {
            List<Map> formComponentValues = (List<Map>) processInstance.get("formComponentValues");
            System.out.println("formComponentValues====" + formComponentValues);

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

            for (Map 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;
                }
            }

            // 检查税号是否已存在（避免重复插入）
            CompanyTitle existing = companyTitleMapper.selectByTaxId(sh);
            if (existing != null) {
                log.warn("公司抬头已存在: 税号={}, 执行更新操作", sh);
                // 更新操作
                existing.setCompanyName(tt);
                existing.setAddress(dz);
                existing.setPhone(dh);
                existing.setBankName(yh);
                existing.setBankAccount(zh);
                if ("启用".equals(zt)) {
                    existing.setStatus((byte) 0);
                } else if ("停用".equals(zt)) {
                    existing.setStatus((byte) 1);
                } else {
                    existing.setStatus((byte) 0);
                }
                existing.setUpdatedAt(LocalDateTime.now());
                companyTitleMapper.updateById(existing);
                log.info("公司抬头更新成功: companyName={}, taxId={}", tt, sh);
            } else {
                // 新增操作
                CompanyTitle companyTitle = new CompanyTitle();
                companyTitle.setCompanyName(tt);
                companyTitle.setTaxId(sh);
                companyTitle.setAddress(dz);
                companyTitle.setPhone(dh);
                companyTitle.setBankName(yh);
                companyTitle.setBankAccount(zh);

                // 处理状态
                if ("启用".equals(zt)) {
                    companyTitle.setStatus((byte) 0);
                } else if ("停用".equals(zt)) {
                    companyTitle.setStatus((byte) 1);
                } else {
                    companyTitle.setStatus((byte) 0);
                }

                companyTitle.setCreatedAt(LocalDateTime.now());
                companyTitle.setUpdatedAt(LocalDateTime.now());

                // 保存
                companyTitleMapper.insert(companyTitle);
                log.info("公司抬头新增成功: companyName={}, taxId={}", tt, sh);
            }
        }
    }
}
