package com.malk.kabeiyi.controller;

import com.malk.kabeiyi.entity.OperatingRecordEntity;
import com.malk.kabeiyi.service.KabeiyiService;
import com.malk.kabeiyi.service.OperatingRecordService;
import com.malk.server.common.McR;
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.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;

    @Autowired
    private OperatingRecordService  operatingRecordServiceImpl;

    //审批实例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("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("getSaleoutInfo")
    public McR getSaleoutInfo(){
        return kabeiyiService.getSaleoutInfo();
    }*/


    //============================================== 一期接口停用 =====================================================

    //审批实例推送到宜搭（卡倍亿）
    /*@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("addVoucher")
    public McR addVoucher(@RequestBody Map map){
        kabeiyiService.addVoucher(map);
        return McR.success();
    }

//    付款推送cbs
    @PostMapping("pushCbs")
    public McR puchCBS(@RequestBody Map map){
        kabeiyiService.puchCBS(map);
        return McR.success();
    }

//    定时查询cbs付款情况并推送u8凭证
    @Scheduled(cron = "0 0/40 8-19 * * ?")
    public McR schedulePaymentCBSToU8() {
        try {
            String[] statusList = {"1"};
            List<OperatingRecordEntity> rescords = operatingRecordServiceImpl.findByStatusAndResCode(statusList);
            log.info("开始获取排程单,并推送用友,推送数量为：{}",rescords.size());
            if(rescords.isEmpty() || rescords.size()==0){
                log.info("没有需要推送的订单。");
                return McR.success();
            }
            for(OperatingRecordEntity entity:rescords){
                log.info("开始推送订单：{}",entity.toString());
                kabeiyiService.schedulePaymentCBSToU8(entity);
            }

            return McR.success();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
