package com.malk.mc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.UtilMap;
import com.malk.utils.UtilServlet;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
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.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/fangan")
public class McCjController {

    @Autowired
    private YDClient ydClient;
    @Autowired
    private YDConf ydConf;
    @Autowired
    private DDConf ddConf;
    @Autowired
    private DDClient dd;
    @SneakyThrows
    @PostMapping("/insetXMC")
    McR insetXMC(@RequestBody JSONObject param) {
        MDC.put("MDC_KEY_PID","1059");
//        Map data = UtilServlet.getParamMap(request);
        String formInstanceId = param.getString("formInstanceId");
//        String type = param.getString("type");
        log.info("formInstanceId:{}", formInstanceId);
//        log.info("type:{}", type);
        //根据实例ID获取表单数据
        Map data = (Map) ydClient.queryData(YDParam.builder().formInstId(formInstanceId)
                .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                .userId(ddConf.getOperator()).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        log.info("data:{}", data);
        String UUID = "";

        String FORMID = "";

        String ZD = "";


        String XMLX = data.get("selectField_lt1iahs9").toString();

        String hangye1 = data.get("selectField_lt1iahsi").toString();//行业1

        String hangye2 = data.get("selectField_lt1iahsj").toString();//行业2

        String zyyw = data.get("textField_ltr1vksn").toString();//主营业务

        if (XMLX.equals("投前项目")) {

            FORMID = "textField_ltjj7pre";

            UUID = "FORM-6195AAEC573C4B8C897F173ABA583710X9UE";

            ZD = "associationFormField_lt1jaec6, textField_lt1jaecd, textField_lt1jaecc, selectField_lt1iahs9, selectField_lt1iahsi, selectField_lt1iahsj, textField_ltr1vksn";


        } else if (XMLX.equals("投后项目")) {

            FORMID = "textField_ltjj7prg";

            UUID = "FORM-0D46B270FD8D4A7187267CC6E39C5B58QXNP";

            ZD = "associationFormField_lt1ouopy, textField_lt1ouopz, textField_lt1ouoq2, selectField_lt1oy6qj";

        }


        log.info("项目池, {}", data);

        if (XMLX.equals("投前项目") || XMLX.equals("投后项目")) {

            List<Map> associations = YDConf.associationForm("APP_PSYQ8H0CVYMKA5PVG8X1", "FORM-496C6B71B5D34E62AA46FB8CAA4FAB69BYTF", formInstanceId, data.get("serialNumberField_lt1i52jt").toString(), null, false);

            log.info("associations: {}", associations);

            log.info("UUID, {}", UUID);

            log.info("ZD, {}", ZD);

            String tquid = ydClient.operateData(YDParam.builder()

                    .appType("APP_PSYQ8H0CVYMKA5PVG8X1")

                    .systemToken("ULD66N81VLRUVLB5E1R6A71CSI0N2NNW5NQ9MP71")

                    .formUuid(UUID)

                    .formDataJson(JSON.toJSONString(UtilMap.map(ZD, associations, data.get("textField_lt1i52ju"), data.get("serialNumberField_lt1i52jt"), XMLX, hangye1, hangye2, zyyw)))//这里

                    .build(), YDConf.FORM_OPERATION.create).toString();////

            if (tquid != "") {

                ydClient.operateData(YDParam.builder()

                        .appType("APP_PSYQ8H0CVYMKA5PVG8X1")

                        .systemToken("ULD66N81VLRUVLB5E1R6A71CSI0N2NNW5NQ9MP71")

                        .formInstanceId(formInstanceId)

                        .updateFormDataJson(JSON.toJSONString(UtilMap.map(FORMID, tquid)))

                        .build(), YDConf.FORM_OPERATION.update);

            }


        }

        return McR.success();

    }

    @SneakyThrows

    @PostMapping("/insetTHXM")
    McR insetTHXM(@RequestBody JSONObject param) {
        MDC.put("MDC_KEY_PID","1059");
        String formInstanceId = param.getString("formInstanceId");
//        String type = param.getString("type");
        log.info("formInstanceId:{}", formInstanceId);
//        log.info("type:{}", type);
        //根据实例ID获取表单数据
        Map data = (Map) ydClient.queryData(YDParam.builder().formInstId(formInstanceId)
                .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                .userId(ddConf.getOperator()).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        log.info("data:{}", data);
//        Map data = UtilServlet.getParamMap(request);


        if (data.get("selectField_ltxs7o0g").toString().equals("否")) {


            List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()

                    .appType("APP_PSYQ8H0CVYMKA5PVG8X1")

                    .systemToken("ULD66N81VLRUVLB5E1R6A71CSI0N2NNW5NQ9MP71")

                    .formUuid("FORM-496C6B71B5D34E62AA46FB8CAA4FAB69BYTF")

                    .searchFieldJson(JSON.toJSONString(UtilMap.map("serialNumberField_lt1i52jt", data.get("textField_lt1jaecc").toString())))

                    .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();

            if (dataList != null && dataList.size() > 0) {

                log.info("dataList:" + dataList);

                String XMCSLID = dataList.get(0).get("formInstanceId").toString();

                String FORMID = "textField_ltjj7prg";

                String UUID = "FORM-0D46B270FD8D4A7187267CC6E39C5B58QXNP";

                String ZD = "associationFormField_lt1ouopy, textField_lt1ouopz, textField_lt1ouoq2, selectField_lt1oy6qj";

                List<Map> associations = YDConf.associationForm("APP_PSYQ8H0CVYMKA5PVG8X1", "FORM-496C6B71B5D34E62AA46FB8CAA4FAB69BYTF", XMCSLID, data.get("textField_lt1jaecc").toString(), null, false);

                String tquid = ydClient.operateData(YDParam.builder()

                        .appType("APP_PSYQ8H0CVYMKA5PVG8X1")

                        .systemToken("ULD66N81VLRUVLB5E1R6A71CSI0N2NNW5NQ9MP71")

                        .formUuid(UUID)

                        .formDataJson(JSON.toJSONString(UtilMap.map(ZD, associations, data.get("textField_lt1jaecd"), data.get("textField_lt1jaecc"), "投后项目")))

                        .build(), YDConf.FORM_OPERATION.create).toString();////

                if (tquid != "") {

                    ydClient.operateData(YDParam.builder()

                            .appType("APP_PSYQ8H0CVYMKA5PVG8X1")

                            .systemToken("ULD66N81VLRUVLB5E1R6A71CSI0N2NNW5NQ9MP71")

                            .formInstanceId(String.valueOf(XMCSLID))

                            .updateFormDataJson(JSON.toJSONString(UtilMap.map(FORMID, tquid)))

                            .build(), YDConf.FORM_OPERATION.update);

                }

            }

            log.info("request, {}", dataList);

        }

        return McR.success();

    }

    @SneakyThrows

    @PostMapping("/report/PJJStemporary")
    McR temporary(@RequestBody Map<String, String> data) {

        MDC.put("MDC_KEY_PID","1059");
        String formid = data.get("fomid");

        log.info("formid,{}", formid);

        Map formdata = ydClient.queryData(YDParam.builder()

                .appType("APP_PSYQ8H0CVYMKA5PVG8X1")

                .systemToken("ULD66N81VLRUVLB5E1R6A71CSI0N2NNW5NQ9MP71")

                .formUuid("FORM-82D513EC7BA24BD592EB7484C58F6604PWOZ")

                .formInstanceId(String.valueOf(formid))

                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();


        List<Map> list = (List<Map>) JSON.parse(String.valueOf(formdata.get("attachmentField_lt468w10")));

    // return McR.success(ydClient.convertTemporaryUrl(list.get(0).get("url").toString(),"APP_G951QZ32AUJNJUE4G127","HOA66I8176RID79L6QF3554SPPYH22VTBH1TLX6",ddapptonken));

        //log.info("url, {}",McR.success(ydClient.convertTemporaryUrl_PJJS(list.get(0).get("url").toString() )));

//        System.out.println("URL："+McR.success(ydClient.convertTemporaryUrl_PJJS(list.get(0).get("url").toString() )));

//        System.out.println("afasdf:" + ydClient.convertTemporaryUrl(list.get(0).get("url").toString()));

        return McR.success(ydClient.convertTemporaryUrl(list.get(0).get("url").toString()));



    }
//    private String convertTemporaryUrl_PJJS(String url ) {
//          String ddapptonken= dd.getAccessToken("dingtcx6xmpmvzihpnnd","PbzbXn065v7qqfGWO-zUdvPoFFO8oB67fyOVX7zao_YXzH7di2ekPZxDcdYKSGUH");
//        Map param = new HashMap();
//        param.put("systemToken", "ULD66N81VLRUVLB5E1R6A71CSI0N2NNW5NQ9MP71");
//        param.put("userId", YDConf.PUB_ACCOUNT);
//        param.put("fileUrl", url);          // URL在param上时, 需要编码 [UtilHttp已经做了编码] - URLEncoder.encode(url, "UTF-8")
//        param.put("timeout", 60000);      // 默认1分钟, 最大24小时 [毫秒]
////        System.out.println("ssss:"+(String) DDR_New.doGet("https://api.dingtalk.com/v1.0/yida/apps/temporaryUrls/APP_PSYQ8H0CVYMKA5PVG8X1" , ddClient.initTokenHeader_PJSS(), param).getResult());
//        return (String) DDR_New.doGet("https://api.dingtalk.com/v1.0/yida/apps/temporaryUrls/APP_PSYQ8H0CVYMKA5PVG8X1" , ddClient.initTokenHeader_PJSS(), param).getResult();
//    }

}
