package com.malk.ruisi.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.service.aliwork.YDClient;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilServlet;
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.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("yd")
public class YDController {

    @Autowired
    private YDClient ydClient;

    @Autowired
    private McDelegate delegate;

    /// 接口校验通用逻辑
    @Synchronized
    @PostMapping("/invokeThird")
    McR invokeThird(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("接口校验通用逻辑, {}", JSON.toJSONString(data));

        McException.assertParamException_Null(data, "instanceId");

        // 多人审批场景下, 避免重复推送
        if ("成功".equals(UtilMap.getString(data, "radioField_m1hmte37"))) {
            return McR.success();
        }

        boolean isSuccess = true;
        String message = "记录推送成功";
        try {
            /// 调用服务, 若也存在异常, 抛出

        } catch (McException exception) {
            isSuccess = true;
            message = exception.getMessage();
            log.error(exception.getMessage(), exception);
        }

        // ppExt: 避免同意的数据更新, 与接口更新重复, 导致更新失败
        boolean finalIsSuccess = isSuccess;
        String finalMessage = message;
        delegate.setTimeout(() -> {
            ydClient.operateData(YDParam.builder()
                    .formInstId(UtilMap.getString(data, "instanceId"))
                    .updateFormDataJson(JSON.toJSONString(UtilMap.map("radioField_m1hmte37, textareaField_lntocd8u", finalIsSuccess ? "成功" : "失败", finalMessage)))
                    .build(), YDConf.FORM_OPERATION.update);
        }, isSuccess ? 0 : 2000);

        McException.assertAccessException(!isSuccess, message); // 抛出异常

        return McR.success();
    }

    /// 获取审批节点 1. 未到达审批前权限问题, 2. 抄送人\审批人不能评论权限问题, 3. 或签非审批操作人无打印权限问题
    @PostMapping("approval/record")
    McR approvalRecord(@RequestParam String processInstanceId, @RequestBody Map data) {

        log.info("获取审批节点, {}, {}", processInstanceId, data);

        List<Map> records = (List<Map>) ydClient.queryData(YDParam.builder()
                .processInstanceId(processInstanceId)
                .build(), YDConf.FORM_QUERY.retrieve_approval_record).getResult();

        List<String> userIds = new ArrayList<>();   // 后端格式
        List<Map> users = new ArrayList<>();        // 前端格式
        for (Map record : records) {

            // 节点多人情况处理
            List<Map> domainList = UtilMap.getList(record, "domainList");
            if (!domainList.isEmpty()) {
                for (Map operator : domainList) {
                    String userId = UtilMap.getString(operator, "operator");
                    if (!userIds.contains(userId)) {
                        userIds.add(userId);
                        // 前端格式显示通过label控制
                        users.add(UtilMap.map("name, label, value", operator.get("operatorName"), operator.get("operatorName"), userId));
                    }
                }
            } else {
                // 单人审批节点处理
                String userId = UtilMap.getString(record, "operatorUserId");
                if (!userIds.contains(userId)) {
                    userIds.add(userId);
                    // 前端格式显示通过label控制
                    users.add(UtilMap.map("name, label, value", record.get("operatorName"), record.get("operatorName"), userId));
                }
            }
        }

        // 执行更新逻辑
        if (UtilMap.getBoolean(data, "isUpdate")) {
            McException.assertParamException_Null(data, "compId");
            ydClient.operateData(YDParam.builder()
                    .formInstId(processInstanceId)
                    .updateFormDataJson(JSON.toJSONString(UtilMap.map(UtilMap.getString(data, "compId"), userIds)))
                    .build(), YDConf.FORM_OPERATION.update);
        }
        return McR.success(UtilMap.map("users, userIds", users, userIds));
    }

    /// 流程分享权限 1. 发起人可操作权限 2. 配置弹出框在可编辑权限
    @PostMapping("share/record")
    McR shareRecord(@RequestParam String processInstanceId, @RequestBody Map data) {

        log.info("流程分享权限, {}, {}", processInstanceId, data);

        // 执行分享逻辑 [ 拼接后的权限组 ]
        McException.assertParamException_Null(data, "compId, userIds, userId, content");
        ydClient.operateData(YDParam.builder()
                .formInstId(processInstanceId)
                .updateFormDataJson(JSON.toJSONString(UtilMap.map(UtilMap.getString(data, "compId"), UtilMap.getList(data, "userIds"))))
                .build(), YDConf.FORM_OPERATION.update);

        YDParam ydParam = YDParam.builder()
                .formInstanceId(processInstanceId)
                .userId(UtilMap.getString(data, "userId"))
                .content(UtilMap.getString(data, "content"))
                .build();
        if (UtilMap.getBoolean(data, "isNotice")) {
            ydParam.setAtUserId(UtilMap.getString(data, "atUserId"));
        }
        ydClient.operateData(ydParam, YDConf.FORM_OPERATION.remarks);


        return McR.success();
    }

    // 重新发起请假流程
    @GetMapping("/test21")
    McR test21() {

        String formInstanceId = "35c8ba1b-2c5b-4581-bf75-a53f9f3b4657";
        String userId = "1007054";
        Map formData = (Map) ydClient.queryData(YDParam.builder().formInstId(formInstanceId)
                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        List employeeField_lts1mg30_id = (List) formData.get("employeeField_lts1mg30_id");
        List departmentSelectField_lts1mg2z_id = (List) formData.get("departmentSelectField_lts1mg2z_id");
        List departmentSelectField_lys0k6qb_id = (List) formData.get("departmentSelectField_lys0k6qb_id");
        System.out.println("==" + employeeField_lts1mg30_id);
        formData.put("employeeField_lts1mg30", employeeField_lts1mg30_id);
        formData.put("departmentSelectField_lts1mg2z", departmentSelectField_lts1mg2z_id);
        formData.put("departmentSelectField_lys0k6qb", departmentSelectField_lys0k6qb_id);

        System.out.println(formData);
        ydClient.operateData(YDParam.builder()
                .formUuid("FORM-A02F7EA3AD6548E59B8E1692AD729C77C5LD")
                .userId(userId)
                .formDataJson(JSON.toJSONString(formData))
                .build(), YDConf.FORM_OPERATION.start).toString();
        return McR.success(formData);
    }
}
