package com.malk.huagao.schedule;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.malk.huagao.entity.KdYdCustomer;
import com.malk.huagao.mapper.KdYdCustomerMapper;
import com.malk.huagao.service.YdHuaGaoService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.aliwork.YDSearch;
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.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@Configuration
@EnableScheduling
@ConditionalOnProperty(name = {"enable.scheduling"})
public class YdScheduleTask {
@Autowired
private YdHuaGaoService ydHuaGaoService;
    @Autowired
    private KdYdCustomerMapper kdYdCustomerMapper;
    @Autowired
    private YDClient ydClient;
//    @Scheduled(cron = "0 0 1 * * ?")
    public void synckdYdMaterialxsy() {
        log.info("定时同步-物料销售员信息");
        try {
            MDC.put("MDC_KEY_PID","1003");
            ydHuaGaoService.synckdYdMaterialxsy();
        } catch (Exception e) {
            log.error("【物料销售员信息同步任务】执行过程中发生严重错误", e);
        }
    }
    //定时客户流入公海池
    @Scheduled(cron = "0 0 4 * * ?")
    public void synckdlrgh() {
        log.info("定时同步-客户流入公海池信息");
        try {
            MDC.put("MDC_KEY_PID","1003");
            ydHuaGaoService.synckdlrgh();
        } catch (Exception e) {
            log.error("【客户流入公海池信息同步任务】执行过程中发生严重错误", e);
        }
    }
//    @Scheduled(cron = "0 0 2 * * ?")
    public void synckdndrq() {
        log.info("定时同步-年度日期信息");
        try {
            MDC.put("MDC_KEY_PID","1003");
            ydHuaGaoService.synckdndrq();
        } catch (Exception e) {
            log.error("【年度日期信息同步任务】执行过程中发生严重错误", e);
        }
    }
    @Scheduled(cron = "0 0 9 1 * ?")
    public void synckdyqsq() {
        log.info("定时同步-自动创建逾期申请");
        try {
            MDC.put("MDC_KEY_PID","1003");
            ydHuaGaoService.synckdyqsq();
        } catch (Exception e) {
            log.error("【自动创建逾期申请同步任务】执行过程中发生严重错误", e);
        }
    }
    /*@Scheduled(cron = "0 0/5 * * * ?")
    public void sync() {
        log.info("定时同步-客户");
        try {

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime fiveMinutesAgo = now.minusMinutes(5);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            List<KdYdCustomer> kdYdCustomers = kdYdCustomerMapper.selectRecentUpdated(fiveMinutesAgo);
            if (kdYdCustomers.isEmpty()) {
                log.info("【客户同步任务】无需要同步的数据，结束");
                return;
            }
            for (KdYdCustomer kdYdCustomer : kdYdCustomers) {
                try {
                    String khbm = kdYdCustomer.getKhbm();
                    String formInstId = kdYdCustomer.getFormInstId();
                    if (ObjectUtil.hasEmpty(formInstId, khbm)) {
                        log.warn("跳过同步: formInstId 或 khbm 为空, customer={}", kdYdCustomer.getId());
                        continue;
                    }
                    ydClient.operateData(
                            YDParam.builder()
                                    .formInstanceId(formInstId)
                                    .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("selectField_mfxrryt3", khbm)))
                                    .useLatestVersion(true).build(), YDConf.FORM_OPERATION.update);

                } catch (Exception e) {
                    log.error("同步单条客户数据异常: formInstId={}", kdYdCustomer.getFormInstId(), e);
                }
            }
            log.info("【客户同步任务】执行完成，共处理 {} 条记录", kdYdCustomers.size());
        } catch (Exception e) {
            log.error("【客户同步任务】执行过程中发生严重错误", e);
        }
    }
    @Scheduled(cron = "0 0/5 * * * ?")
    public void syncKdYdCustomerReferrer() {
        log.info("定时同步-推荐人");
        try {
            ydHuaGaoService.syncKdYDcustomerLiaison();
        } catch (Exception e) {
            log.error("【推荐人同步任务】执行过程中发生严重错误", e);
        }
    }

        @Scheduled(cron = "0 0/5 * * * ?")
    public void syncKdYdOrder() {
        log.info("定时同步-订单");
        try {
            ydHuaGaoService.syncKdYdOrder();
        } catch (Exception e) {
            log.error("【订单同步任务】执行过程中发生严重错误", e);
        }
    }
    @Scheduled(cron = "0 0/5 * * * ?")
    public void syncKdYdDelivery() {
        log.info("定时同步-发货通知单");
        try {
            ydHuaGaoService.syncKdYdDelivery();
        } catch (Exception e) {
            log.error("【发货通知单同步任务】执行过程中发生严重错误", e);
        }
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void syncKdYdDeliveryDetail() {
        log.info("定时同步-发货通知单详情");
        try {
            ydHuaGaoService.syncKdYdDeliveryDetail();
        } catch (Exception e) {
            log.error("【发货通知单详情同步任务】执行过程中发生严重错误", e);
        }
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void synckdYdZp() {
        log.info("定时同步-发票单");
        try {
            ydHuaGaoService.synckdYdZp();
        } catch (Exception e) {
            log.error("【发票单同步任务】执行过程中发生严重错误", e);
        }
    }*/




//    @Scheduled(cron = "0 0/15 * * * ?")
    public void synckdYdOutbound() {
        log.info("定时同步-出库单");
        try {
            MDC.put("MDC_KEY_PID","1003");
            ydHuaGaoService.synckdYdOutbound();
        } catch (Exception e) {
            log.error("【出库单同步任务】执行过程中发生严重错误", e);
        }
    }

//    @Scheduled(cron = "0 0/15 * * * ?")
    public void syncKdYdReceivable() {
        log.info("定时同步-应收单");
        try {
            MDC.put("MDC_KEY_PID","1003");
            ydHuaGaoService.syncKdYdReceivable();
        } catch (Exception e) {
            log.error("【应收单同步任务】执行过程中发生严重错误", e);
        }
    }
//    @Scheduled(fixedRate = 5 * 60 * 1000)
//    @Scheduled(cron = "0 0/15 * * * ?")
//@Scheduled(cron = "0/1 * * * * ?")
    public void synckdYdMaterial() {
        log.info("定时同步-物料信息");
        try {
            MDC.put("MDC_KEY_PID","1003");
            ydHuaGaoService.synckdYdMaterial();
        } catch (Exception e) {
            log.error("【物料信息同步任务】执行过程中发生严重错误", e);
        }
    }

//    @Scheduled(cron = "0 0/15 * * * ?")
    public void synckdYdPayment() {
        log.info("定时同步-synckdYdPayment");
        try {
            MDC.put("MDC_KEY_PID","1003");
            ydHuaGaoService.synckdYdPayment();
        } catch (Exception e) {
            log.error("【synckdYdPayment同步任务】执行过程中发生严重错误", e);
        }
    }

//    @Scheduled(cron = "0 0/15 * * * ?")
    public void synckdYdTRANSFER() {
        log.info("定时同步-synckdYdTRANSFER");
        try {
            MDC.put("MDC_KEY_PID","1003");
            ydHuaGaoService.synckdYdTRANSFER();
        } catch (Exception e) {
            log.error("【synckdYdTRANSFER同步任务】执行过程中发生严重错误", e);
        }
    }

//    @Scheduled(cron = "0/1 * * * * ?")
    public void synckddel() {
        log.info("定时删除物料表");
        try {
            MDC.put("MDC_KEY_PID","1003");
            DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                    .formUuid("FORM-E64114E9F2C9426E91F92886EDFFA2C08Q90")
                    .build(), YDConf.FORM_QUERY.retrieve_search_form_id);

            System.out.println(ddrNew.getTotalCount());

            ydClient.operateData(YDParam.builder()
                    .formUuid("FORM-E64114E9F2C9426E91F92886EDFFA2C08Q90")
                    .asynchronousExecution(true)
                    .formInstanceIdList((List<String>) ddrNew.getData())
                    .build(), YDConf.FORM_OPERATION.delete_batch);
        } catch (Exception e) {
            log.error("【synckdYdTRANSFER同步任务】执行过程中发生严重错误", e);
        }
    }
}