package com.malk.luyi.controller;

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

import com.alibaba.fastjson.JSON;
import com.malk.delegate.McDelegate;
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.utils.UtilMap;
import com.malk.utils.UtilServlet;
import lombok.SneakyThrows;
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.Optional;

@Slf4j
@RestController
@RequestMapping()
public class LYController {

    @Autowired
    private YDClient ydClient;

    /**
     * 报告查询
     */
    @PostMapping("report/query")
    McR query(@RequestBody Map data) {

        log.info("报告查询, {}", data);
        McException.assertParamException_Null(data, "cardNo, page, size");

        // prd 3.5 无手机号查询
        if (data.containsKey("phoneNo")) {
            // 更新客户档案
            DDR_New ddr_new = ydClient.queryData(YDParam.builder()
                    .formUuid("FORM-MFA66S91KKJDA2708OHTW6RBOJRK3SVWO7KLL1")
                    .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_llvq2dqf", data.get("cardNo"))))
                    .build(), YDConf.FORM_QUERY.retrieve_search_form);
            McException.assertAccessException(ddr_new.getTotalCount() == 0, "信息未登记! ");
            Map formData = (Map) ((List<Map>) ddr_new.getData()).get(0).get("formData");
            List<Map> details = (List<Map>) formData.get("tableField_llk8hw38");
            Optional optional = details.stream().filter(item -> data.get("phoneNo").equals(item.get("textField_llvq2dqr"))).findAny();
            if (!optional.isPresent()) {
                details.add(UtilMap.map("textField_llvq2dqr, textField_llk8hw39, radioField_lndtpa2c", data.get("phoneNo"), "报告回写", "报告回写"));
                ydClient.operateData(YDParam.builder()
                        .formInstId(String.valueOf(((List<Map>) ddr_new.getData()).get(0).get("formInstanceId")))
                        .updateFormDataJson(JSON.toJSONString(UtilMap.map("tableField_llk8hw38", details))) // 仅修改子表, 避免全量覆盖数据格式不兼容
                        .build(), YDConf.FORM_OPERATION.update);
                // 写入联系人记录表
                ydClient.operateData(YDParam.builder()
                        .formUuid("FORM-XHA6688148UDAB8RCH4TO7T0CBGF3NWHGI4ML8")
                        .formDataJson(JSON.toJSONString(UtilMap.map("selectField_lm4kbce2, textField_lm4igzq0, textField_lm4igzq2, textField_lm4igzq4, radioField_lndtpa2c",
                                formData.get("textField_llk8hw32"), formData.get("serialNumberField_llkb8w7t"), "报告回写", data.get("phoneNo"), "报告回写")))
                        .build(), YDConf.FORM_OPERATION.create);
            }
        }
        // 查询报告结果
        DDR_New ddr_new2 = ydClient.queryData(YDParam.builder()
                .formUuid("FORM-XHA66881E3ODR7EKBGK9XBXECRML267EIQVLL5")
                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_lm0653jv", data.get("cardNo"))))
                .pageNumber(UtilMap.getInt(data, "page"))
                .pageSize(UtilMap.getInt(data, "size"))
                .dynamicOrder(JSON.toJSONString(UtilMap.map("dateField_lpjim03p", "-")))
                .build(), YDConf.FORM_QUERY.retrieve_search_form);
        return McR.success(ddr_new2);
    }


    /**
     * 细胞查询
     */
    @PostMapping("cell/query")
    McR cell(@RequestBody Map data) {

        log.info("细胞查询, {}", data);
        McException.assertParamException_Null(data, "cardNo, name, page, size");

        // 查询细胞结果
        DDR_New ddr_new2 = ydClient.queryData(YDParam.builder()
                .formUuid("FORM-FDA66N818YLEFETQ694XF5GV8CN73D6NFMFNLE")
                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_lnspbi7w, textField_lnfmfzth", data.get("cardNo"), data.get("name"))))
                .pageNumber(UtilMap.getInt(data, "page"))
                .pageSize(UtilMap.getInt(data, "size"))
                .dynamicOrder(JSON.toJSONString(UtilMap.map("dateField_lnsva9el", "-")))
                .build(), YDConf.FORM_QUERY.retrieve_search_form);
        return McR.success(ddr_new2);
    }

    /**
     * 免登地址
     */
    @PostMapping("report/temporary")
    McR temporary(@RequestBody Map data) {
        McException.assertParamException_Null(data, "urls");
        List<String> images = new ArrayList<>();
        for (String url : (List<String>) UtilMap.getList(data, "urls")) {
            images.add(ydClient.convertTemporaryUrl(url));
        }
        log.info("免登地址, {}", images);
        return McR.success(images);
    }

    @Autowired
    private McDelegate mcDelegate;

    /**
     * 客户关联渠道
     */
    @PostMapping("relation")
    @SneakyThrows
    McR relation(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("客户关联渠道, {}", data);

        if ("是".equals(data.get("type"))) {
            mcDelegate.setTimeout(() -> {

                List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-6YA66WB1BATD2ZPWA2Z2S813SFFC3EGRBHYLLH")
                        .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_lozlyqpb", data.get("code"))))
                        .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();
                if (dataList.size() == 1) {
                    Map formData = (Map) dataList.get(0).get("formData");
                    String title = String.valueOf(formData.get("textField_llyhc8ca"));
                    List<Map> associations = YDConf.associationForm("APP_I45JU7MQMRRVZ472GS1U", "FORM-6YA66WB1BATD2ZPWA2Z2S813SFFC3EGRBHYLLH", String.valueOf(dataList.get(0).get("formInstanceId")), title, title, false);
                    ydClient.operateData(YDParam.builder()
                            .formInstanceId(String.valueOf(data.get("instanceId")))
                            .updateFormDataJson(JSON.toJSONString(UtilMap.map("textField_llkbx3ob, associationFormField_lm4hoevr, textField_lm4hoevs", formData.get("serialNumberField_llyhc8ck"), associations, title)))
                            .build(), YDConf.FORM_OPERATION.update);
                }
            }, 5000);
        }
        return McR.success();
    }

    @PostMapping("test")
    McR test() {

//        ydClient.queryData(YDParam.builder()
//                .formUuid("FORM-MFA66S91KKJDA2708OHTW6RBOJRK3SVWO7KLL1")
//                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_llk8hw32", "张少文")))
//                .build(), YDConf.FORM_QUERY.retrieve_search_form);

//        ydClient.queryData(YDParam.builder()
//                .formUuid("FORM-6YA66WB1BATD2ZPWA2Z2S813SFFC3EGRBHYLLH")
//                .searchFieldJson(JSON.toJSONString(UtilMap.map("serialNumberField_llyhc8ck", "QD-20240130-0009")))
//                .build(), YDConf.FORM_QUERY.retrieve_search_form);


        ydClient.operateData(YDParam.builder()
                .formInstanceId("FINST-I1A66071U47JBCQBAS6P087BV43127WAFE9ULH0A9")
                .build(), YDConf.FORM_OPERATION.delete);
        return McR.success();
    }
}
