package com.malk.harrison.controller;

import com.alibaba.fastjson.JSONObject;
import com.malk.harrison.config.HarrisonConfig;
import com.malk.server.aliwork.YDConf;
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.harrison.entity.XyTodo;
import com.malk.harrison.server.XYR;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 错误抛出与拦截详见 CatchException
 */
@Slf4j
@RestController
@RequestMapping("/xy")
public class XYController {
    @Autowired
    private DDClient ddClient;

    @Autowired
    private YDClient ydClient;

    @Autowired
    private YDConf ydConf;

    @Autowired
    private HarrisonConfig harrisonConfig;

    private static Map<Integer, String> DD_category = new HashMap<>();

    static {
        DD_category.put(0, "钉钉,宜搭");
        DD_category.put(1, "钉钉,待办");
    }

    private String getXyUrl(String path) {
        return harrisonConfig.getXiangyu().getBaseUrl() + path;
    }

    /**
     * 创建象屿统一待办
     * - prd
     * 1. 待办创建, 更新均需要传递全部参数 (目前仅会校验审批时间不能小于历史数据)
     * 2. 接收人存在多人时, 统一待办会自动拆分为多个 (待办中心以 业务单据号 + 用户域账号)
     */
    private void syncXyTodo(XyTodo todo) {
        try {
            Map body = todo.toMap();
            XYR r = (XYR) UtilHttp.doPost(getXyUrl("/push"),
                    UtilMap.map("deipaaskeyauth", harrisonConfig.getXiangyu().getApiKey()),
                    body, XYR.class);

            log.info("创建统一待办, {}", r);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除象屿统一待办
     */
    private void deleteXyTodo(String busNo) {
        try {
            XYR r = (XYR) UtilHttp.doPost(getXyUrl("/delete"), null, UtilMap.map("busNo",busNo), XYR.class);

            log.info("删除统一待办, {}", r);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 宜搭待办
     */
    @PostMapping("/sync")
    McR sync(@RequestBody Map map) {
        String formInstId = UtilMap.getString(map, "formInstId");//审批实例id

        String busNo = UtilMap.getString(map, "busNo");//唯一流水号

        String boName = UtilMap.getString(map,"boName");//单据名称

        String pcUrl = "https://xiangyu.aliwork.com/"+ydConf.getAppType()+"/processDetail?procInsId="+formInstId;
        String appUrl = "https://xiangyu.aliwork.com/"+ydConf.getAppType()+"/processDetail?procInsId="+formInstId;

        //查询宜搭审批记录, 完成回调, 完成更新
        Map<String,Object> param = new HashMap<>();
        param.put("appType",ydConf.getAppType());
        param.put("systemToken",ydConf.getSystemToken());
        param.put("userId","yida_pub_account");
        param.put("processInstanceId",formInstId);

        Map<String,Object> result = (Map<String,Object>) JSONObject.parse(UtilHttp.doGet("https://api.dingtalk.com/v1.0/yida/processes/operationRecords", ddClient.initTokenHeader(), param));

        List<Map<String,Object>> operationRecords = UtilMap.getList(result,"result");

        XyTodo xyTodo = new XyTodo(
                harrisonConfig.getXiangyu().getSystem(),
                harrisonConfig.getXiangyu().getSecure(),
                DD_category.get(0));

        xyTodo.setBusNo(busNo);//唯一流水号
        xyTodo.setCreateDateTime(UtilDateTime.formatDateTime(new Date()));//创建时间
        xyTodo.setPcUrl(pcUrl);
        xyTodo.setAppUrl(appUrl);
        xyTodo.setOptType(2);//操作类型：1、待办；2、已办；3、待阅
        xyTodo.setCreateDateTime(UtilDateTime.formatDateTime(new Date()));//创建时间
        xyTodo.setReceiveDateTime(UtilDateTime.formatDateTime(new Date()));//接收时间
        xyTodo.setApproveDateTime(UtilDateTime.formatDateTime(new Date()));//审批时间

        boolean isFirst = true;

        //创建人、接收人账号应取象屿平台账号，若找不到账号则固定人员：陈文良
        for (Map<String,Object> operationRecord : operationRecords) {
            //第一条审批记录为发起节点
            if (isFirst) {

                String creatorName = UtilMap.getString(operationRecord, "operatorName");
                String ddUserId = UtilMap.getString(operationRecord, "operatorUserId");
                String creator = getXyUserId(ddUserId);

                //若无域账号
                if (Strings.isBlank(creator)){
                    creator = "wl.chen";//创建人域账号
                    creatorName = "陈文良";//创建人姓名
                }

                xyTodo.setCreator(creator);
                xyTodo.setCreatorName(creatorName);
                xyTodo.setTitle(boName + "-" + creatorName + "-" + busNo);//标题

                isFirst = false;

                continue;
            }

            String type = UtilMap.getString(operationRecord, "type");

            switch (type){
                case "HISTORY":
                    //统一待办仅展示最新 暂不考虑历史记录
                    /*xyTodo.setOptType(2);

                    xyTodo.setReceivers(UtilMap.getString(operationRecord,"operatorUserId"));//接收人域账号
                    xyTodo.setReceiverNames(UtilMap.getString(operationRecord,"operatorName"));//接收人姓名
                    xyTodo.setApproveDateTime(convertDateTime(UtilMap.getString(operationRecord, "operateTimeGMT")));//审批时间

                    //若该代办已存在，则拼接接收人  若该代办不存在，添加该代办
                    if (!isExist(xyTodoList, xyTodo)) {
                        xyTodoList.add(xyTodo);
                    }*/

                    break;
                case "TODO":
                    xyTodo.setOptType(1);
                    xyTodo.setCurrentStatus(UtilMap.getString(operationRecord,"showName"));//当前状况（流程描述）

                    String ddUserId = UtilMap.getString(operationRecord, "operatorUserId");
                    String receiversName = UtilMap.getString(operationRecord, "operatorName");
                    String receivers = getXyUserId(ddUserId);

                    //若无域账号
                    if (Strings.isBlank(receivers)){
                        receivers = "wl.chen";
                        receiversName = "陈文良";
                    }
                    xyTodo.setReceivers(receivers);//接收人域账号
                    xyTodo.setReceiverNames(receiversName);//接收人姓名

                    break;
                case "FORCAST":break;
                default:break;
            }
        }

        //全部已办
        if (Strings.isBlank(xyTodo.getReceivers())){
            //最后一个审批记录审批人设为接收人
            Map<String, Object> operationRecord = operationRecords.get(operationRecords.size() - 1);

            String ddUserId = UtilMap.getString(operationRecord, "operatorUserId");
            String receiversName = UtilMap.getString(operationRecord, "operatorName");
            String receivers = getXyUserId(ddUserId);
            //若无域账号
            if (Strings.isBlank(receivers)){
                receivers = "wl.chen";
                receiversName = "陈文良";
            }

            xyTodo.setReceivers(receivers);//接收人域账号
            xyTodo.setReceiverNames(receiversName);//接收人姓名
            xyTodo.setCurrentStatus(UtilMap.getString(operationRecord,"showName"));//当前状况（流程描述）

        }

        syncXyTodo(xyTodo);

        return McR.success();
    }

    /**
     * 删除宜搭待办
     */
    @PostMapping("/delete")
    McR delete(@RequestBody Map map) {
        String busNo = UtilMap.getString(map, "busNo");//唯一流水号

        deleteXyTodo(busNo);

        return McR.success();
    }

    @GetMapping("/test")
    McR test(){
        return McR.success("111");
    }

    //钉钉userId查询象屿域账号（钉钉工号）
    private String getXyUserId(String userId){
        DDR_New ddrNew = (DDR_New) UtilHttp.doPost("https://oapi.dingtalk.com/topapi/v2/user/get", null, ddClient.initTokenParams(), UtilMap.map("userid", userId), DDR_New.class);

        Map result = (Map) ddrNew.getResult();

        String xyUserId = UtilMap.getString(result, "job_number");

        return xyUserId;//接收人域账号
    }




}
