package com.malk.hake.controller;

import com.alibaba.fastjson.JSON;
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.utils.UtilDateTime;
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.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 错误抛出与拦截详见 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));
        hkClient.callbackProcess(data);
        return McR.success();
    }

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

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

    @PostMapping("monitor/sync")
    McR pay(String code) {

        log.info("手动触发, 拉取Monitor同步");
        hkClient.syncMonitor(code);
        return McR.success();
    }


    @Autowired
    private YDClient ydClient;

    @Autowired
    private YDService ydService;

    @GetMapping("test")
    McR test() {

//        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();
    }
}
