package com.malk.mc.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.malk.core.McProject;
import com.malk.mc.service.McYdService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDConf;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.utils.PublicUtil;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class McYdServiceImpl implements McYdService {
    @Autowired
    private YDClient ydClient;
    @Autowired
    private DDClient ddClient;
    @Autowired
    private DDConf ddConf;

    @Override
    @Async
    public void updateFormDataVersion(Map map) {
        String pid = Objects.nonNull(map.get("pid")) ? map.get("pid").toString() : "";
        String formInstId = Objects.nonNull(map.get("formInstId")) ? map.get("formInstId").toString() : "";
        String formUuid = Objects.nonNull(map.get("formUuid")) ? map.get("formUuid").toString() : "";
        if (Strings.isNotBlank(pid)){
            MDC.put("MDC_KEY_PID",pid);
            if (Strings.isNotBlank(formInstId) && Strings.isBlank(formUuid)){
                ydClient.operateData(YDParam.builder()
                        .formInstId(formInstId)
                        .useLatestVersion(true)
                        .updateFormDataJson("{}").build(), YDConf.FORM_OPERATION.update);
            }else if (Strings.isBlank(formInstId) && Strings.isNotBlank(formUuid)){
                int i = 1;
                int pageSize = 50;
                DDR_New ddrNew;
                do {
                    ddrNew = ydClient.queryData(YDParam.builder()
                            .formUuid(formUuid)
                            .pageNumber(i)
                            .pageSize(pageSize)
                            .build(), YDConf.FORM_QUERY.retrieve_search_form_id);

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

                    //noExecuteExpression字段不传或传false  传true会导致实例版本不更新或滞后更新
                    ydClient.operateData(YDParam.builder()
                            .formInstanceIdList(formInstIdList)
                            .formUuid(formUuid)
                            .useLatestFormSchemaVersion(true)
                            .updateFormDataJson("{}")
                            .noExecuteExpression(false)
                            .asynchronousExecution(false)
                            .build(),YDConf.FORM_OPERATION.multi_update);

                    i++;
                }while (ddrNew.getTotalCount() > ddrNew.getPageNumber() * pageSize);
            }

            //发送工作通知给当前登陆人
            if (Objects.nonNull(map.get("userId"))){
                String userId = map.get("userId").toString();
                Map param2 = new HashMap();
                param2.put("access_token",ddClient.getAccessToken());
                Map body3 = new HashMap();
                body3.put("agent_id",ddConf.getAgentId());
                body3.put("userid_list",userId);
                Map msg = new HashMap();
                msg.put("msgtype","text");
                //获取当前时间 精确到秒
                String time = DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss");
                msg.put("text", UtilMap.map("content","表单实例版本已更新  时间：" + time));
                body3.put("msg",msg);
                UtilHttp.doPost("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2",null,param2,body3);
            }
        }
    }

    @Override
    public McR initiateApproval(Map map) {
        String pid = getString(map.get("pid"));
        String formUuid = getString(map.get("formUuid"));
        String processCode = getString(map.get("processCode"));
        String userId = getString(map.get("userId"));
        Map formData = (Map) map.get("formData");
        Map processData = new HashMap();
        if (Objects.nonNull(map.get("processData"))){
            processData = (Map) map.get("processData");
        }

        if (Strings.isNotBlank(pid)){
            //发起审批
            String[] yida = McProject.getYida(pid);
            Map<String,Object> body = new HashMap<>();
            if (!PublicUtil.isNull(pid) && yida != null && yida.length >= 2) {
                body.put("appType",yida[0]);
                body.put("systemToken",yida[1]);
            }
            body.put("userId",userId);
            body.put("formUuid",formUuid);
            body.put("processCode",processCode);
            body.put("formDataJson", JSONObject.toJSONString(formData));
            if (Objects.nonNull(processData) && processData.size() > 0){
                body.put("processData", JSONObject.toJSONString(processData));
            }

            UtilHttp.doPost("https://api.dingtalk.com/v1.0/yida/processes/instances/start", ddClient.initTokenHeader(), null, body, DDR_New.class);
            return McR.success();
        }
        return McR.errorParam("参数缺失！");
    }

    private String getString(Object obj){
        return obj == null ? "" : obj.toString();
    }
}
