package com.malk.hake.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.malk.hake.service.HKClient;
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.common.McREnum;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.service.dingtalk.DDClient_Event;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilServlet;
import lombok.SneakyThrows;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 错误抛出与拦截详见 CatchException
 */
@Slf4j
@RestController
@RequestMapping
public class HKController {

    @Autowired
    private HKClient hkClient;

    /**
     * 通用流程发起
     */
    @SneakyThrows
    @PostMapping("process/start")
    McR startProcess(@RequestBody Map data, HttpServletRequest request, @RequestParam String code) {

        Map header = UtilServlet.getHeaders(request);
        log.info("流程发起, {}, {}, {}", code, data, header);
        McException.assertException(!"dinge61fe69900ea236b35c2f4657eb6378f".equals(header.get("authorization")), McREnum.NOT_AUTHORIZED);
        Map result = hkClient.startProcess(code, data);
        return McR.success(result);
    }

    /**
     * 通用审批校验 [区分类型, 宜搭提示不同报错信息]
     */
    @PostMapping("process/validate")
    McR validateProcess(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("审批校验, {}", JSON.toJSONString(data));
        // 拒绝审批意见必填校验 prd 4.17 取消拒绝校验, 统一返回 [审核人xxx拒绝], monitor通过活动跳转
        //McException.assertParamException_Null(data, "Remark");
        return McR.success();
    }

    /**
     * 通用审批回调 [区分类型, 宜搭提示不同报错信息]
     */
    @PostMapping("process/callback")
    McR callbackProcess(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("审批回调, {}", JSON.toJSONString(data));
        if (!"Y".equals(data.get("Status"))) { // 询价\报价
            hkClient.callbackProcess(data);
        }
        return McR.success();
    }


    /**
     * 报价、询价审批, 添加标志位判定
     */
    @PostMapping("process/update")
    McR updateProcess(@RequestBody Map data) {

        McException.assertParamException_Null(data, "ddProcessId", "ddStatus");
        log.info("同步标志, {}", JSON.toJSONString(data));

        ydClient.operateData(YDParam.builder()
                .formInstanceId(UtilMap.getString(data, "ddProcessId"))
                .updateFormDataJson(JSON.toJSONString(UtilMap.map("radioField_lzkqlkgh", data.get("ddStatus"))))
                .build(), YDConf.FORM_OPERATION.update);
        return McR.success();
    }

    /**
     * 通讯录同步
     */
    @Synchronized
    @PostMapping("contact/sync")
    McR syncContact() {

        log.info("手动触发, 通讯录同步");
        hkClient.syncContact(false);
        return McR.success();
    }

    /**
     * 手动同步付款数据
     */
    @PostMapping("monitor/sync")
    McR pay(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("手动触发, 拉取Monitor同步, {}", data);
        hkClient.syncMonitor(UtilMap.getString(data, "code"), data);
        return McR.success();
    }

    /**
     * 手动同步考勤数据
     */
    @PostMapping("attendance/sync")
    McR attendance(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("手动同步考勤数据, {}", data);
        List<String> userIds = (List) JSON.parse(String.valueOf(data.get("userIds")));
        hkClient.syncAttendance(UtilMap.getString(data, "tDate"), userIds);
        return McR.success();
    }

    /**
     * 数据初始化 [临时]
     */
    @PostMapping("attendance/correction")
    McR reissue(HttpServletRequest request) {
//        hkClient._correctionAttendance();
        return McR.success();
    }


    ////////////////////////////////////////////////  TEST  ////////////////////////////////////////////////

    @Autowired
    private YDClient ydClient;

    @Autowired
    private YDService ydService;

    @Autowired
    private DDClient_Event ddClient_event;

    @PostMapping("invoke")
    McR invoke(@RequestBody JSONObject data) {

        ddClient_event.callBackEvent_Attendance(data);
        return McR.success();
    }

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Autowired
    private DDClient ddClient;

    @GetMapping("tmp")
    McR tmp_1() {

        hkClient.test();
//        return McR.success(hkClient.syncContact(true));
        return McR.success();
    }

    @GetMapping("test")
    McR test(@RequestParam String id, @RequestBody Map data) {

        log.info("xxxx, {}, {}", id, data);
//        ddClient_contacts.getDepartmentInfo(ddClient.getAccessToken(), 369113480L);
        return McR.success();

//        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
//                .formUuid("FORM-96C8BF4B18044DF783ADFE1CF7931FE9P4BW")
//                .build());
//        for (Map item : dataList) {
//            ydClient.operateData(YDParam.builder()
//                    .formInstanceId(UtilMap.getString(item, "instanceId"))
//                    .updateFormDataJson(JSON.toJSONString(UtilMap.map("employeeField_lo47byyj", Arrays.asList(UtilMap.getString(item, "textField_m4sjp8pf")))))
//                    .build(), YDConf.FORM_OPERATION.update);
//        }

//        ydClient.operateData(YDParam.builder()
//                .formInstanceId("125e59bb-5f1f-4307-b809-79d0add5e28e")
//                .updateFormDataJson(JSON.toJSONString(UtilMap.map("textareaField_lntocd8u", "管理员拒绝")))
//                .build(), YDConf.FORM_OPERATION.update);


        /// 衣念
//        List<Map> dataList = (List<Map>) ydService.queryFormData_all(YDParam.builder()
//                .appType("APP_ZTKQXN2ISL7TWFDR6PSK")
//                .systemToken("GM866LB1OJTBPZB471GENBEO35YB270I085JLN1")
//                .formUuid("FORM-PR8667D1F4NBYLKI9ZKT9AEDZ6SP2CU4OA5JLQ")
//                .searchFieldJson(JSON.toJSONString(UtilMap.map("selectField_lk82ds02, dateField_lili3nyt", "是", Arrays.asList(UtilDateTime.parseDate("2024-04-01").getTime(), new Date().getTime()))))
//                .useLatestVersion(true)
//                .build());
//        log.info("dataList, {}", dataList.size());
//
//        dataList.forEach(item -> {
//            List<Map> details = (List<Map>) item.get("tableField_lili3nz6");
//            Map formData = UtilMap.map("tableField_lili3nz6", details.stream().map(row -> {
//                row.put("textField_lvf16s5q", String.valueOf(row.get("selectField_lk2byq2q")).replace("-1", "").replace("-2", "").replace("-3", "").replace("-4", "").replace("-5", ""));
//                return row;
//            }).collect(Collectors.toList()));
//            log.info("------, {}", item.get("formInstanceId"));
//            ydClient.operateData(YDParam.builder()
//                    .appType("APP_ZTKQXN2ISL7TWFDR6PSK")
//                    .systemToken("GM866LB1OJTBPZB471GENBEO35YB270I085JLN1")
//                    .formInstanceId(UtilMap.getString(item, "formInstanceId"))
//                    .updateFormDataJson(JSON.toJSONString(formData))
//                    .build(), YDConf.FORM_OPERATION.update);
//        });
//        return McR.success();
    }

    @GetMapping("test2")
    McR test2() {
//
//        ydClient.operateData(YDParam.builder()
//                .appType("APP_ERBDTFS82HOVBPL3NFH0")
//                .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
//                .formInstanceId("ce82e168-ade5-494c-b781-5e5ce3fc451e")
//                .updateFormDataJson(JSON.toJSONString(UtilMap.map("textField_lr383i3u", "test")))
//                .useLatestVersion(true)
//                .build(), YDConf.FORM_OPERATION.update);
        return McR.success();
    }


    //////////// ----------------------------------------------------------------

    @GetMapping("version")
    McR version() {

        /// 哈克
//        String instanceId = "31e7bd1a-7f06-444e-af56-90f8ffa1c8d3";
//        String appType = "APP_ERBDTFS82HOVBPL3NFH0";
//        String systemToken = "RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP";

//        String instanceId = "31e7bd1a-7f06-444e-af56-90f8ffa1c8d3";
//        String appType = "APP_ERBDTFS82HOVBPL3NFH0";
//        String systemToken = "RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP";
//
//        ydClient.operateData(YDParam.builder()
//                .appType(appType)
//                .systemToken(systemToken)
//                .formInstanceId(instanceId)
//                .updateFormDataJson(JSON.toJSONString(UtilMap.map("textareaField_lr383i3y", "")))
//                .useLatestVersion(true)
//                .build(), YDConf.FORM_OPERATION.update);
        return McR.success();
    }

    @GetMapping("/delete")
    McR tmp() {

//        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
//                .formUuid("FORM-4E69EBA1416047078D14601AF17A05643350")
////                .formUuid("FORM-FCD09241E15D4E53A901D54CA3FBB084PQ6P")
//                .build());
//        dataList.forEach(item -> {
//            ydClient.operateData(YDParam.builder()
//                    .formInstanceId(UtilMap.getString(item, "formInstanceId"))
//                    .build(), YDConf.FORM_OPERATION.delete);
//        });

        return McR.success();
    }

    @PostMapping("/approve")
    McR approve() {

        return McR.success(Arrays.asList("095358016629044412", "3044156512719746", "2534342040877632"));
    }
}
