package com.malk.zhiwei.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.PublicUtil;
import com.malk.utils.UtilMap;
import com.malk.zhiwei.service.ZwService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @EnableScheduling 开启定时任务 [配置参考McScheduleTask]
 */
@Slf4j
@Configuration
@EnableScheduling
@ConditionalOnProperty(name = {"enable.scheduling"})
@RestController

public class ScheduleTask {

    @Autowired
    private YDClient ydClient;

    @Autowired
    private ZwService zwService;

    /**
     */
//    @Scheduled(cron = "0 0/5 * * * ?")
    public void sync() {
        List<Map> list=(List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-3A89370AC94B429B9180ED98260BAF680JYM").pageSize(1)
                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("selectField_mcefftmv","待处理"))).build(), YDConf.FORM_QUERY.retrieve_list_all).getData();
        log.info("手动同步查询-结果，{}",list.size());
        if(list==null||list.size()<1){
            return;
        }
        Map data=list.get(0);
        log.info("{}",data);
        String formInstanceId=String.valueOf(data.get("formInstanceId"));
        processing(formInstanceId);
        Map formData=UtilMap.getMap(data,"formData");
        try {
            String type=UtilMap.getString(formData,"selectField_mcefftmu");

            if("销售订单".equals(type)){
                JSONObject jsonObject=zwService.saveSaleOrder(formData);
                comp(formInstanceId,"同步完成！",JSONObject.toJSONString(jsonObject.getJSONObject("result")),jsonObject);
            }else if("发货单".equals(type)){
                JSONObject jsonObject=zwService.saveDeliveryOrder(formData);
                comp(formInstanceId,"同步完成！",JSONObject.toJSONString(jsonObject.getJSONObject("result")),jsonObject);
            }else if("产品同步".equals(type)){
                zwService.syncProduct(UtilMap.getString(formData,"textField_mcefftng"),UtilMap.getString(formData,"textField_mdr1v1di"));
                comp(formInstanceId,"同步完成！","",null);
            }else{
                comp(formInstanceId,"同步完成！","",null);
            }
        }catch (Exception e){
            e.printStackTrace();
            comp(formInstanceId,"异常",e.getMessage(),null);
        }
    }

//    @Scheduled(cron = "0 0 1 * * ?")
    public void syncProd() {
        zwService.syncProduct("","PILOT2024");
        zwService.syncProduct("","PILOT2023");
    }

    private void processing(String id){
        ydClient.operateData(YDParam.builder().formInstanceId(id)
                .updateFormDataJson(JSON.toJSONString(UtilMap.map("selectField_mcefftmv", "处理中")))
                .build(), YDConf.FORM_OPERATION.update);
    }

    private void comp(String id,String result,String msg,Map data){
        if(data==null){
            data=new HashMap<>();
        }
        data.putAll(UtilMap.map("selectField_mcefftmv, textField_mcefftnw, textareaField_mcefftn0", "已完成",result,msg));
        ydClient.operateData(YDParam.builder().formInstanceId(id)
                .updateFormDataJson(JSON.toJSONString(data))
                .build(), YDConf.FORM_OPERATION.update);
    }

    //产品信息同步
    @Scheduled(cron = "0 0 1 * * ?")
    @PostMapping("/product")
    public void product() throws JsonProcessingException {
        zwService.product();
    }

    //销售订单同步
    @SneakyThrows
    @Scheduled(cron = "0 15 1 * * ?")
    @PostMapping("/purchaseOrder")
    public void purchaseOrder() throws JsonProcessingException {
        zwService.purchaseOrder();
    }

    //出库单（发货通知单）同步
    @SneakyThrows
    @Scheduled(cron = "0 30 1 * * ?")
    @PostMapping("/deliveryOrder")
    public void deliveryOrder(){
        zwService.deliveryOrder();
    }

    //退货单同步
    @SneakyThrows
    @Scheduled(cron = "0 45 1 * * ?")
    @PostMapping("/returnForm")
    public void returnForm(){
        zwService.returnForm();
    }

    //补货单同步
    @SneakyThrows
    @Scheduled(cron = "0 0 2 * * ?")
    @PostMapping("/replenishmentOrder")
    public void replenishmentOrder(){
        zwService.replenishmentOrder();
    }

    //开票单同步
    @SneakyThrows
    @Scheduled(cron = "0 15 2 * * ?")
    @PostMapping("/invoice")
    public void invoice(){
        zwService.invoice();
    }

    //应收单同步
    @SneakyThrows
    @Scheduled(cron = "0 30 2 * * ?")
    @PostMapping("/receivableNote")
    public void receivableNote(){
        zwService.receivableNote();
    }

    //客户同步
    @SneakyThrows
//    @Scheduled(cron ="0 0 3 * * ?")
    @PostMapping("/customer")
    public void customer(){
        zwService.customer();
    }

}