package com.malk.kabeiyi.controller;

import com.malk.kabeiyi.service.KabeiyiService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McException;
import com.malk.server.common.McR;
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_Workflow;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

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

@Slf4j
@RestController
@RequestMapping("/dd/")
public class KabeiyiController {

    @Autowired
    private DDClient ddClient;
    @Autowired
    private DDClient_Workflow ddClient_workflow;

    @Autowired
    private KabeiyiService kabeiyiService;

    //审批实例url前缀
    private static final String PROC_INST_PREFIX_URL = "https://aflow.dingtalk.com/dingtalk/web/query/pchomepage.htm?from=oflow&op=true&corpid=dingc3a744cb591a7346f2c783f7214b6d69#/plainapproval?procInstId=";
    @GetMapping("test")
    public McR test(){
        return McR.success();
    }

    @GetMapping("getList")
    public McR getList(String pid,String procCode,String nextToken){
        LocalDateTime now=LocalDateTime.now();
        Map data=new HashMap();
        data.put("maxResults",10);
        data.put("nextToken",nextToken);
        data.put("statuses", Arrays.asList("COMPLETED"));
//        data.put("userIds","");
        Map rsp=ddClient_workflow.getInstanceIds(ddClient.getAccessToken(),procCode,
                UtilDateTime.getLocalDateTimeTimeStamp(now.minusDays(120)),UtilDateTime.getLocalDateTimeTimeStamp(now),data);
        List<String> list=(List)rsp.get("list");
        List result=new ArrayList();
        for(String id:list){
            Map detail=ddClient_workflow.getProcessInstanceId(ddClient.getAccessToken(),id);
            if("agree".equals(String.valueOf(detail.get("result")))){
                Map dd=new HashMap();
                dd.put("url",PROC_INST_PREFIX_URL + id);
                dd.put("title",detail.get("title"));
                dd.put("businessId",detail.get("businessId"));
                result.add(dd);
            }
        }
        return McR.success(UtilMap.map("data, nextToken",result,rsp.get("nextToken")));
    }
    //新增一张付款单
    @PostMapping("addPayment")
    public McR addPayment(@RequestBody Map map){
        return kabeiyiService.addPayment(map);

    }

    //审批实例推送到宜搭（卡倍亿）
    @PostMapping("pushProcInstToYD")
    public McR pushProcInstToYD(@RequestBody Map map){
        return kabeiyiService.pushProcInstToYD(map);
    }

    //审批实例推送到宜搭（特充）
    @PostMapping("pushProcInstToYD2")
    public McR pushProcInstToYD2(@RequestBody Map map){
        return kabeiyiService.pushProcInstToYD2(map);
    }

    //发起问题整改审批
    @PostMapping("addQuestionApproval")
    public McR addQuestionApproval(@RequestBody Map map){
        return kabeiyiService.addQuestionApproval(map);
    }

    //审核计划发起审核表
    @PostMapping("addPlanApproval")
    public McR addPlanApproval(@RequestBody Map map){
        return kabeiyiService.addPlanApproval(map);
    }

    //ocr识别
    @GetMapping("/ocr")
    public McR ocr(String downloadUrl,String name,String type){
        return kabeiyiService.ocr(downloadUrl,name,type);
    }

    //每天0点定时同步发货单信息
    @Scheduled(cron = "0 0 0 * * ?")
    @GetMapping("/getDeliveryInfo")
    public McR getDeliveryInfo(){
        return kabeiyiService.getDeliveryInfo();
    }

    /*@Autowired
    private YDClient ydClient;
    @GetMapping("deleteAllData")
    public McR deleteAllData(){
        MDC.put("MDC_KEY_PID","1019");
        DDR_New ddrNew;
        int pageNumber = 1;
        int pageSize = 100;
        String formUuid = "FORM-809458EB6D524CF5AE1A91A3492D8B1BZIMN";
        List<String> errorList = new ArrayList<>();
        do {
            ddrNew = ydClient.queryData(YDParam.builder()
                    .formUuid(formUuid)
                    .pageNumber(pageNumber)
                    .pageSize(pageSize).build(), YDConf.FORM_QUERY.retrieve_search_form_id);

            List<String> list =(List<String>) ddrNew.getData();

            int i=1;
            boolean flag = false;
            while (i<=5 && !flag){
                try {
                    ydClient.operateData(YDParam.builder()
                            .formUuid(formUuid)
                            .asynchronousExecution(false)
                            .formInstanceIdList(list)
                            .build(),YDConf.FORM_OPERATION.delete_batch);
                    flag = true;
                }catch (McException e){
                    if (e.getMessage().contains("The request has failed due to a temporary failure of the server.")){
                        log.info("请求失败，尝试次数:{}",i);
                        i++;
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException ex) {
                            throw new RuntimeException(ex);
                        }
                    }else {
                        log.info("删除失败 失败原因:{}" , e.getMessage());
                        errorList.addAll(list);
                        flag = true;
                    }
                }catch (Exception e){
                    log.info("删除失败 失败原因:{}" , e.getMessage());
                    errorList.addAll(list);
                    flag = true;
                }
            }
            if (i>5){
                log.info("删除失败，重试次数过多");
            }

        }while (ddrNew.getTotalCount() > 0);
        log.info("失败列表:{}",errorList);
        return McR.success();
    }*/
}
