package com.malk.hengyilong.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malk.hengyilong.service.ClientHylService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.aliwork.YDSearch;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 功能：
 * 作者：hanxue
 * 日期：2026/2/2 10:48
 */

@Service
@Slf4j
public class ClientHylServiceImpl implements ClientHylService {
    @Autowired
    private YDClient ydClient;
    @Override
    public McR getClient(Map param) {
        DDR_New ddrNew;
        int pageNumber = 1;
        int pageSize = 100;
        JSONArray clientList = new JSONArray();
        do {
            ddrNew = ydClient.queryData(YDParam.builder()
                    .formUuid("FORM-GMC66781QZP16UF1NPSLG6C8ZC9G38R5V6IJM1")
                    .searchFieldJson(JSONObject.toJSONString(Arrays.asList(
                            new YDSearch("selectField_mkm0qu7p", "锁定", "selectField_mkm0qu7p", YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ),
                            new YDSearch("employeeField_mkm0ce8w", param.get("userId"), "employeeField_mkm0ce8w",YDSearch.Type.EMPLOYEE_FIELD, YDSearch.Operator.CONTAINS)
                    )))
                    .pageNumber(pageNumber)
                    .pageSize(pageSize)
                    .build(), YDConf.FORM_QUERY.retrieve_list_all);
            if (ddrNew != null && ddrNew.getData() != null) {
                JSONArray currentPageData = (JSONArray) ddrNew.getData();
                clientList.addAll(currentPageData);
                System.out.println("已处理第 " + pageNumber + " 页数据，当前页记录数: " + currentPageData.size());
                if (currentPageData.size() < pageSize) {
                    break;
                }
            }
            pageNumber++;  // 准备查询下一页
        } while (ddrNew != null && ddrNew.getTotalCount() > (pageNumber - 1) * pageSize);
        List clientNameList = new ArrayList();
        for(int i=0;i<clientList.size();i++) {
            Map client = (Map) clientList.get(i);
            Map formData = (Map) client.get("formData");
           String clientName = UtilMap.getString(formData,"textfield_uB2fZYNg");
            clientNameList.add(clientName);
        }
        log.info("clientList:{}",clientNameList);
        return McR.success(clientNameList);
    }

    @Override
    public McR syncClient(Map map) {
         List clientdetails = (List) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-GMC66781QZP16UF1NPSLG6C8ZC9G38R5V6IJM1")
                .searchFieldJson(JSONObject.toJSONString(Arrays.asList(
                        new YDSearch("textfield_uB2fZYNg", UtilMap.getString(map, "clientName"), "textfield_uB2fZYNg", YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ)
                )))
                .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();
        Map clientdetail = (Map) clientdetails.get(0);
        log.info("clientList:{}",clientdetail.get("formInstanceId"));
        String clientLink = "https://gkwk0b.aliwork.com/APP_QX8IOI1D22HK3GC413L5/formDetail/FORM-GMC66781QZP16UF1NPSLG6C8ZC9G38R5V6IJM1?formInstId="+clientdetail.get("formInstanceId");
        return McR.success(clientLink);
    }

    @Override
    public McR getAccountPeriod(Map map) {
        String formInstance = UtilMap.getString(map, "formInstance");
        //            应收帐日期
        String receiveDate = null;
        try {

            Map formData = ydClient.queryData(YDParam.builder()
                    .formInstanceId(formInstance)
                    .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
            String settleMethod = UtilMap.getString(formData, "selectField_ml3e44b1");//结算方式
            Long invoiceDateTimestamp = UtilMap.getLong(formData, "datefield_DMpwNIpo");//发票日期
            int paymentDays = UtilMap.getInt(formData, "selectField_ml3e44b2");//付款天数
            int settleDay = UtilMap.getInt(formData, "numberField_mq8yh6p6");//结算日
            int paymentDate = UtilMap.getInt(formData, "numberField_mjl1xyz3");//付款日

            if (settleMethod == null || settleMethod.trim().isEmpty()) {
                log.warn("结算方式缺失，返回异常标记X");
                receiveDate = "X";
            } else {
                Date invoiceDate = null;
                if (invoiceDateTimestamp != null && invoiceDateTimestamp > 0) {
                    try {
                        invoiceDate = new Date(invoiceDateTimestamp);
                    } catch (Exception e) {
                        log.error("发票日期无效: {}", invoiceDateTimestamp, e);
                        return McR.success(null);
                    }
                } else {
                    log.error("发票日期为空");
                    return McR.success(null);
                }
                if ("货到".equals(settleMethod)) {
                    Date accountDate = DateUtil.offsetDay(invoiceDate, paymentDays);
                    receiveDate = DateUtil.formatDate(accountDate);
                    log.info("货到结算，应到帐时间: {}", receiveDate);
                } else if ("预付".equals(settleMethod)) {
                    receiveDate = DateUtil.formatDate(invoiceDate);
                    log.info("预付结算，应到帐时间: {}", receiveDate);
                } else if ("月结".equals(settleMethod)) {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(invoiceDate);
                    int lastDayOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

                    int adjustDays;
                    if (settleDay == 0 || settleDay == 30) {
                        adjustDays = 0;
                    } else {
                        adjustDays = lastDayOfMonth - settleDay;
                    }
                    Date baseDate = DateUtil.offsetDay(invoiceDate, adjustDays);
                    int months = paymentDays / 30;
                    Date dateWithPeriod = DateUtil.offsetMonth(baseDate, months);
                    Calendar cal2 = Calendar.getInstance();
                    cal2.setTime(dateWithPeriod);
                    int lastDayOfResultMonth = cal2.getActualMaximum(Calendar.DAY_OF_MONTH);
                    cal2.set(Calendar.DAY_OF_MONTH, lastDayOfResultMonth);
                    Date monthEndDate = cal2.getTime();

                    Date finalDate;
                    if (paymentDate == 30) {
                        finalDate = monthEndDate;
                    } else {
                        finalDate = DateUtil.offsetDay(monthEndDate, paymentDate);
                    }

                    receiveDate = DateUtil.formatDate(finalDate);
                    log.info("月结结算，应到帐时间: {}", receiveDate);

                } else {
                    log.warn("未识别的结算方式: {}", settleMethod);
                    receiveDate = "X";
                }
            }
        } catch (NumberFormatException e) {
            log.error("数字格式转换异常", e);
            receiveDate = "X";
        } catch (Exception e) {
            log.error("计算应到帐时间异常", e);
            receiveDate = "X";
        } finally {
            try {
                if (!"X".equals(receiveDate) && receiveDate != null) {
                    Date resultDate = DateUtil.parse(receiveDate);
                    ydClient.operateData(YDParam.builder()
                            .formInstanceId(formInstance)
                            .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("dateField_mpdpzvrv", resultDate.getTime())))
                            .build(), YDConf.FORM_OPERATION.update);
                    log.info("已回写应到帐时间到宜搭: {}", receiveDate);
                } else {
                    log.info("结果为X或null，不回写宜搭");
                }
                return McR.success(receiveDate);
            } catch (Exception e) {
                log.error("回写宜搭失败", e);
                return McR.errorParam( e.getMessage());
            }
        }

    }

}
