package com.malk.taisen.controller;

/**
 * 错误抛出与拦截详见 CatchException
 */

import com.alibaba.fastjson.JSON;
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.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilServlet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping
public class TSController {

    @Autowired
    private YDClient ydClient;

    @Autowired
    private YDConf ydConf;

    @Autowired
    private YDService ydService;

    /**
     * 保存提交版本
     */
    @PostMapping("backend")
    McR backend(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("保存提交版本, {}", data);
        McException.assertParamException_Null(data, "instanceId, type");
        if ("手动同步".equals(data.get("type"))) {
            return McR.success();
        }
        // type 自动备份: 原报销单提交后同步, 手动同步: 版本备份报价单提交后更新
        String instanceId = String.valueOf(data.get("instanceId"));
        String updateInstanceId = String.valueOf(data.get("updateInstanceId"));
        Map update = UtilMap.map("radioField_lp9wi7lb, textField_lowp416t", data.get("type"), instanceId);
        ydService.mirrorFormData(instanceId, "FORM-L8966281S0WF1JA4AWGDM4QC94TS2E3US8WOLO5", "TPROC--L896628148XFT9KDB3IHI5M14A8W2V7US8WOL1", update, updateInstanceId);

        return McR.success();
    }

    /**
     * 2.26 流程异常重新发起
     */
    @PostMapping("restart")
    McR restart(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("流程异常重新发起, {}", data);

        Map<String, Object> formData = JSON.parseObject(UtilMap.getString(data, "formData"));
        log.info("流程异常重新发起, {}", formData);

        for (String key : formData.keySet()) {
            if (key.startsWith("employeeField_")) {
                formData.put(key, JSON.parse(String.valueOf(formData.get(key))));
            }
        }
        ydService.mirrorFormData(String.valueOf(formData.get("textField_lt2bkgqa")), "FORM-UX866Q61LRK2LACIB8A6M6T1ZOLM2VY5NYB6LZ", "TPROC--UX866Q61LRK2LACIB8A6M6T1ZOLM2YY5NYB6L01", formData, null);
        return McR.success(formData);
    }


    /**
     * 恢复报销明细
     */
    @PostMapping("recover")
    McR recover(@RequestBody Map<String, String> data) {

        String cId = data.get("cId");
        String sId = data.get("sId");
        log.info("恢复报销明细, {}", data);

        Map formData = ydClient.queryData(YDParam.builder()
                        .formInstanceId(cId)
                        .build(),
                YDConf.FORM_QUERY.retrieve_id).getFormData();
        List<Map> details = ((List<Map>) formData.get("tableField_l6lmxo5r")).stream().map(item -> {
            item.put("associationFormField_l6vk2yxg", JSON.parse(String.valueOf(item.get("associationFormField_l6vk2yxg_id"))));
            item.put("associationFormField_l6napwww", JSON.parse(String.valueOf(item.get("associationFormField_l6napwww_id"))));
            return item;
        }).collect(Collectors.toList());

        Map updateForm = UtilMap.map("tableField_l6lmxo5r, associationFormField_l83trmls, textField_l7a7bf8d", details, JSON.parse(String.valueOf(formData.get("associationFormField_l83trmls"))), formData.get("textField_l7a7bf8d"));
        updateForm.putAll(UtilMap.map("numberField_l6lmxo63, numberField_l6lmxo6h, textField_l6bynqte", formData.get("numberField_l6lmxo63"), formData.get("numberField_l6lmxo6h"), formData.get("textField_l6bynqte")));
        ydClient.operateData(YDParam.builder()
                .formInstanceId(sId)
                .updateFormDataJson(JSON.toJSONString(updateForm)).build(), YDConf.FORM_OPERATION.update);

        return McR.success(formData);
    }

    /**
     * 子表同步主表
     */
    @PostMapping("unify")
    McR unify(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("子表同步主表, {}", data);

        String instanceId = String.valueOf(data.get("instanceId"));
        Map formData = ydClient.queryData(YDParam.builder()
                        .formInstanceId(instanceId)
                        .build(),
                YDConf.FORM_QUERY.retrieve_id).getFormData();
        List<Map> details = (List<Map>) formData.get("tableField_l6lmxo5r");
        List<Map> associations = new ArrayList<>();
        for (Map detail : details) {
            List<Map> arr = ydConf.associationForm(String.valueOf(detail.get("associationFormField_l6vk2yxg_id")));
            if (arr.size() > 0) {
                associations.addAll(arr);
            }
        }
        Map updateForm = UtilMap.map("associationFormField_l83trmls", associations);
        ydClient.operateData(YDParam.builder()
                .formInstanceId(instanceId)
                .updateFormDataJson(JSON.toJSONString(updateForm)).build(), YDConf.FORM_OPERATION.update);

        return McR.success(updateForm);
    }

//
//    ///// 数据修复
//
//    @PostMapping("test11")
//    McR test11() {
//
//
//        // 丢行处理
//
//        // 孙静
////        String tId = "f54bb1ab-e989-4b61-ad9b-7cd9e2dab69b";
////        String sId = "62f796fd-b35d-4db8-85ad-c14dbc2050ad";
//
//        // 陈黛珠
////        String tId = "96af9edc-83cb-4027-9687-8ec0e1cbd4eb";
////        String sId = "5005d16d-a392-43a6-bdcb-c1ae93d30deb";
//
//        // 陈豹
////        String tId = "640cff6e-89fb-4d50-9c45-aa2fcf8b06d5";
////        String sId = "13dfaba7-7f27-4f51-bcb6-5c8d71b758c1";
//
//        //
//        String tId = "7cd24af9-2ab2-4c70-b723-4db5b75089e4";
//        String sId = "06aec1b9-7023-49aa-b607-cacafae6f9f6";
//
//        Map formData = ydClient.queryData(YDParam.builder()
//                        .formInstanceId(tId)
//                        .build(),
//                YDConf.FORM_QUERY.retrieve_id).getFormData();
//        List<Map> details = ((List<Map>) formData.get("tableField_l6lmxo5r")).stream().map(item -> {
//            item.put("associationFormField_l6vk2yxg", JSON.parse(item.get("associationFormField_l6vk2yxg_id").toString()));
//            item.put("associationFormField_l6napwww", JSON.parse(String.valueOf(item.get("associationFormField_l6napwww_id"))));
//            // 关联申请
////            List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
////                            .formUuid("FORM-78766VC1KTX2HZQ6E6IR3CYXWUFU3RO8RGN6L6")
////                            .searchFieldJson(JSON.toJSONString(UtilMap.map("employeeField_l82gi80j, numberField_l6ngrh2h", formData.get("employeeField_l843wfsm_id"), Arrays.asList(item.get("numberField_l6lmxo60"), item.get("numberField_l6lmxo60")))))
////                            .build(),
////                    YDConf.FORM_QUERY.retrieve_search_form).getData();
////            item.put("associationFormField_l6napwww", ydConf.associationForm("FORM-78766VC1KTX2HZQ6E6IR3CYXWUFU3RO8RGN6L6", dataList.get(0).get("formInstanceId").toString(), "深圳", null, false));
//            return item;
//        }).collect(Collectors.toList());
//
//        Map updateForm = UtilMap.map("tableField_l6lmxo5r", details);
//        ydClient.operateData(YDParam.builder()
//                .formInstanceId(sId)
//                .updateFormDataJson(JSON.toJSONString(updateForm)).build(), YDConf.FORM_OPERATION.update);
//
//        return McR.success(formData);
//    }
//
//    // 当前表税率为0处理
//    @PostMapping("test13")
//    McR test13() {
//
//        String fid = "6f565a2f-a605-4f01-93c2-db177e2118c5";
//
//        Map formData = ydClient.queryData(YDParam.builder()
//                .formInstanceId(fid)
//                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
//        List<Map> details = (List<Map>) formData.get("tableField_l6lmxo5r");
//
//        details.forEach(item -> {
//
//            if (UtilString.isBlankCompatNull(String.valueOf(item.get("numberField_l6lmxo61")))) {
//                item.put("numberField_l6lmxo61", 0);
//            }
//            item.put("associationFormField_l6vk2yxg", JSON.parse(String.valueOf(item.get("associationFormField_l6vk2yxg_id"))));
//            item.put("associationFormField_l6napwww", JSON.parse(String.valueOf(item.get("associationFormField_l6napwww_id"))));
//
//            log.info("xxxx, {}", item.get("numberField_l6lmxo61"));
//        });
//
//        Map updateForm = UtilMap.map("tableField_l6lmxo5r", details);
//
//        ydClient.operateData(YDParam.builder()
//                .formInstanceId(fid)
//                .updateFormDataJson(JSON.toJSONString(updateForm)).build(), YDConf.FORM_OPERATION.update);
//
//        return McR.success(updateForm);
//    }
//
//    // 修改报销金额
//    @PostMapping("test15")
//    McR test15() {
//
//        String fid = "6f565a2f-a605-4f01-93c2-db177e2118c5";
//
//        Map formData = ydClient.queryData(YDParam.builder()
//                .formInstanceId(fid)
//                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
//        List<Map> details = (List<Map>) formData.get("tableField_l6lmxo5r");
//
//
//        details.forEach(item -> {
//
//            if (UtilMap.getFloat(item, "numberField_l6napwwi") == 146.66f || UtilMap.getFloat(item, "numberField_l6napwwi") == 235f || UtilMap.getFloat(item, "numberField_l6napwwi") == 162.66f) {
//                item.put("numberField_l6napwwi", 0);
//            }
//            item.put("associationFormField_l6vk2yxg", JSON.parse(String.valueOf(item.get("associationFormField_l6vk2yxg_id"))));
//            item.put("associationFormField_l6napwww", JSON.parse(String.valueOf(item.get("associationFormField_l6napwww_id"))));
//
//            log.info("xxxx, {}", item.get("numberField_l6napwwi"));
//        });
//        details = details.stream().filter(item -> UtilMap.getFloat(item, "numberField_l6napwwi") > 0f).collect(Collectors.toList());
//        Map updateForm = UtilMap.map("tableField_l6lmxo5r, numberField_l6lmxo6h, textField_l6bynqte", details, 1788, "壹仟柒佰捌拾捌元整");
//
//        ydClient.operateData(YDParam.builder()
//                .formInstanceId(fid)
//                .updateFormDataJson(JSON.toJSONString(updateForm)).build(), YDConf.FORM_OPERATION.update);
//
//        return McR.success(updateForm);
//    }
//
//    // 变更记录
//    @PostMapping("changed")
//    McR changed() {
//
//        for (int i = 1; i <= 55; i++) {
//
//            List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
//                    .formUuid("FORM-UX866Q61LRK2LACIB8A6M6T1ZOLM2VY5NYB6LZ")
//                    .pageNumber(i)
//                    .currentPage(i)
//                    .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();
//
//            Map<String, List<Map>> record = ydClient.queryData(YDParam.builder()
//                    .formUuid("FROM-UX866Q61LRK2LACIB8A6M6T1ZOLM2VY5NYB6LZ")
//                    .formInstanceIdList(dataList.stream().map(item -> String.valueOf(item.get("formInstanceId"))).collect(Collectors.toList()))
//                    .build(), YDConf.FORM_QUERY.retrieve_changed).getOperationLogMap();
//            for (String id : record.keySet()) {
//
//                Map form = dataList.stream().filter(item -> item.get("formInstanceId").equals(id)).findAny().get();
//                Map data = (Map) form.get("formData");
//                Map formData = UtilMap.map("associationFormField_lnukdrl8", ydConf.associationForm("FORM-UX866Q61LRK2LACIB8A6M6T1ZOLM2VY5NYB6LZ", id, String.valueOf(form.get("title")), null, true));
//                formData.put("textField_lnulmox7", data.get("textField_l7a7bf8d"));
//                formData.put("employeeField_lnulmox8", data.get("employeeField_l843wfsm_id"));
//
//                List<Map> details = record.get(id).stream().map(item -> UtilMap.map("textField_lnukfzeh, textField_lnukfzei, textField_lnukfzej, textField_lnukfzel, textField_lnukfzek, textField_lnukfzem",
//                        item.get("currentText"), item.get("preText"), item.get("gmtModified"), item.get("componentName"), item.get("operationType"), UtilMap.getMap(item, "operator").get("displayName")))
//                        .collect(Collectors.toList());
//                formData.put("tableField_lnukfzeg", details);
//                ydClient.operateData(YDParam.builder()
//                        .formUuid("FORM-4W8667D1440FEE4PFEX586YVOCEN3EXFDKUNLB1")
//                        .formDataJson(JSON.toJSONString(formData))
//                        .build(), YDConf.FORM_OPERATION.create);
//            }
//
//        }
//
//        return McR.success();
//    }
//
//
//    /// 广舜临时修改
//    @PostMapping("gc")
//    McR gc() {
//
//
////        ydClient.operateData(YDParam.builder()
////                .formInstanceId("39e50d18-fcd4-4b19-b825-23d421a255ff")
////                .updateFormDataJson(JSON.toJSONString(UtilMap.map("textField_llalwnd7", "HA0051C")))
////                .build(), YDConf.FORM_OPERATION.update);
//
//        List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
//                .formUuid("FORM-08866RA1SPVC8CISDK79NBIXH4ZT3CBF61MKL0")
//                .dynamicOrder(JSON.toJSONString(UtilMap.map("gmt_create", "+")))
//                .build(), YDConf.FORM_QUERY.retrieve_search_process).getData();
//
//        Collections.reverse(dataList);
//
//        int i = 1;
//        for (Map formData : dataList) {
//
//            String newS = String.valueOf(UtilMap.getMap(formData, "data").get("textField_llalwnd7"));
//            if (UtilMap.getMap(formData, "data").containsKey("textField_lmu9nuzp")) {
//                newS += "-" + String.valueOf(UtilMap.getMap(formData, "data").get("textField_lmu9nuzp"));
//            } else {
//                newS += "-" + "M";
//            }
//            if (i > 9) {
//                newS += "00" + i;
//            } else {
//                newS += "000" + i;
//            }
//            newS += UtilDateTime.format(new Date(Long.valueOf(String.valueOf(UtilMap.getMap(formData, "data").get("dateField_llabt1ft")))), "yyMMdd");
//
//            log.info("xxxx, {}, ", newS);
//            ydClient.operateData(YDParam.builder()
//                    .formInstanceId(String.valueOf(formData.get("processInstanceId")))
//                    .updateFormDataJson(JSON.toJSONString(UtilMap.map("textField_lkkmaxdw, serialNumberField_lnlu5r43", newS, newS)))
//                    .build(), YDConf.FORM_OPERATION.update);
//            i++;
////
//        }
//        return McR.success();
//    }
//
//
//    @PostMapping("test")
//    McR test(String id, @RequestBody Map data) {
//
//
//        id = "27791e35-0ade-4f58-91ac-0eb62f8db9b6";
////        String fd = "FORM-56666571H80F5YH6B53L8AMCU02I2HLC4KLNL5"; // 测试
////        String pd = "TPROC--56666571H80F5YH6B53L8AMCU02I29QC4KLNL6";
//
//        String fd = "FORM-UX866Q61LRK2LACIB8A6M6T1ZOLM2VY5NYB6LZ"; // 正式
//        String pd = "TPROC--UX866Q61LRK2LACIB8A6M6T1ZOLM2YY5NYB6L01";
//
//        // 重新审批: selectField_lo6wzjxo, 流程结束:selectField_lo6wzjxp
////        Object rsp = ydService.mirrorFormData(id, fd, pd, UtilMap.map("selectField_lo6wzjxo, employeeField_lo6wzjxm, employeeField_lo6wzjxn", "是", Arrays.asList("112743683235841523"), Arrays.asList("112743683235841523")));
//        Object rsp = ydService.mirrorFormData(id, fd, pd, UtilMap.map("selectField_lo6wzjxo, radioField_l8k1azrt", "是", "是"), null);
//        return McR.success(rsp);
//    }
//
//
//    @PostMapping("exist")
//    DDR_New exist(@RequestBody Map data) {
//
//        DDR_New ddr_new = ydClient.queryData(YDParam.builder()
//                .formUuid(String.valueOf(data.get("formUuid")))
//                .searchFieldJson(JSON.toJSONString(data.get("conditions")))
//                .build(), YDConf.FORM_QUERY.retrieve_search_form);
//        return ddr_new;
//    }
}
