package com.malk.aiwei.controller;

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

import com.alibaba.fastjson.JSON;
import com.malk.aiwei.service.AWClint;
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.DDConf;
import com.malk.server.teambition.TBConf;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.service.teambition.TBClient;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilServlet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Slf4j
@RestController
@RequestMapping
public class TBxYDController {

    @Autowired
    private AWClint awClint;

    /**
     * 交付物审批回调
     */
    @PostMapping("approved")
    McR approve(HttpServletRequest request) {

        Map<String, ?> data = UtilServlet.getParamMap(request);
        log.info("交付物审批回调, {}", data);
        McException.assertParamException_Null(data, "projectId, taskId, creatorId, approve");

        awClint.approved(data);
        return McR.success();
    }

    /**
     * 检查项check回调
     */
    @PostMapping("checked")
    McR check(HttpServletRequest request) {

        Map<String, ?> data = UtilServlet.getParamMap(request);
        log.info("检查项check回调, {}", data);
        McException.assertParamException_Null(data, "taskId, creatorId, formInstId");

        awClint.checked(data);
        return McR.success();
    }

    /**
     * 选项卡渲染获取详情
     */
    @PostMapping("load-check")
    public Map details(String taskId) {

        log.info("选项卡渲染, {}", taskId);

        String result = UtilMap.getString(awClint.doCheck(taskId, true), "result");
        String strJson = "{\"version\":\"1.0.0\",\"template\":{\"status\":\"#variables.status#\",\"toolbar\":[{\"label\":\"成功\",\"type\":\"text\",\"visible\":\"#variables.isDetailVisible#\",\"payload\":\"#variables.detailURL#\"}]},\"data\":[{\"itemId\":\"61b80257e1fe2200410c8ecd\",\"avatarUrl\":\"\",\"title\":\"xxxxx\",\"description\":\"\"}],\"variables\":{\"userId\":\"5bdc085d60bcef000146634f\",\"taskId\":\"\",\"status\":\"\",\"primaryLabel\":\"详情\",\"itemURL\":\"\",\"detailURL\":\"\",\"createURL\":\"\",\"createPlanTimeLabel\":\"\",\"createPlanTimeURL\":\"\",\"editURL\":\"\",\"removeURL\":\"\",\"isItemVisible\":true,\"isDetailVisible\":true,\"isCreatePlanTimeVisible\":true,\"isPrimaryVisible\":true,\"isEditVisible\":true,\"isRemoveVisible\":true}}";
        strJson = strJson.replace("xxxxx", result);
        return (Map) JSON.parse(strJson);
    }

    /**
     * 检查项发起
     */
    @PostMapping("do-check")
    McR doCheck(String taskId) {

        log.info("检查项发起, {}", taskId);
        return McR.success(awClint.doCheck(taskId, false));
    }

    /**
     * 通过模板创建项目
     */
    @PostMapping("project/create")
    McR createProject(HttpServletRequest request) {

        Map<String, ?> data = UtilServlet.getParamMap(request);
        log.info("通过模板创建项目, {}", data);
        McException.assertParamException_Null(data, "projectCode");
        String templateId = UtilMap.getString(data, "templateId");
        if (data.containsKey("manual")) {
            awClint.createProject(UtilMap.getString(data, "projectCode"), templateId);
        } else {
            // ppExt: 宜搭数据创建后, 以及客户系统同步到主数据有时间差, 做延迟代理 10s
            mcDelegate.setTimeout(() -> {
                awClint.createProject(UtilMap.getString(data, "projectCode"), templateId);
            }, 10000);
        }
        return McR.success();
    }

    /**
     * 分配项目角色
     */
    @PostMapping("project/role")
    McR updateRoleProject(HttpServletRequest request) {

        Map<String, ?> data = UtilServlet.getParamMap(request);
        log.info("分配项目角色, {}", data);
        McException.assertParamException_Null(data, "projectId", "trNode");

        awClint.updateProjectRole(UtilMap.getString(data, "projectId"), (List<String>) JSON.parse(UtilMap.getString(data, "trNode")));
        return McR.success();
    }

    /**
     * 删除前后置依赖
     */
    @PostMapping("project/remove/dependencies")
    McR removeDependencies(HttpServletRequest request) {

        Map<String, ?> data = UtilServlet.getParamMap(request);
        log.info("删除前后置依赖, {}", data);
        McException.assertParamException_Null(data, "projectId", "trNode");

        awClint.removeDependencies(UtilMap.getString(data, "projectId"), (List<String>) JSON.parse(UtilMap.getString(data, "trNode")));
        return McR.success();
    }

    /**
     * 手动触发, 同步项目主数据
     */
    @PostMapping("project/sync")
    McR syncProject() {
        awClint.syncProject(null);
        return McR.success();
    }

    /**
     * 手动触发, 同步预检项
     */
    @PostMapping("check/sync")
    McR syncCheck(int type) {
        awClint.syncCheckList(type);
        return McR.success();
    }

    /**
     * 项目主数据增量更新
     */
    @PostMapping("project/update")
    McR updateProject(HttpServletRequest request) {
        Map<String, ?> data = UtilServlet.getParamMap(request);
        log.info("项目主数据增量更新, {}", data);

        // ppExt: 宜搭数据创建后, 以及客户系统同步到主数据有时间差, 做延迟代理 10s
        mcDelegate.setTimeout(() -> {
            // 多项目变更（项目成员变更） ppExt: 自动化通过公式获取子表字段，接口取不到。目前先通过传递实例ID，进行查询
            if (data.containsKey("formInstId")) {
                Map formData = ydClient.queryData(YDParam.builder()
                        .formInstanceId(UtilMap.getString(data, "formInstId"))
                        .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
                for (Map row : (List<Map>) UtilMap.getList(formData, "tableField_lqovv8at")) {
                    awClint.updateProject(UtilMap.getString(row, "textField_lqovv8ax"));
                }
            }
            // 单项目变更（项目号变更）
            if (data.containsKey("projectCode")) {
                awClint.updateProject(UtilMap.getString(data, "projectCode"));
            }
        }, 10000);
        return McR.success();
    }

    /**
     * 手动触发, 同步CRM基线数据
     */
    @PostMapping("crm/sync")
    McR syncCRM(HttpServletRequest request) {
        Map<String, ?> data = UtilServlet.getParamMap(request);
        log.info("同步CRM基线数据, {}", data);

        if (data.containsKey("projectId")) {
            awClint.syncBaseLineForCRM(UtilMap.getString(data, "projectId"));
        } else {
            awClint.syncBaseLineForCRM();
        }
        return McR.success();
    }

    /**
     * 手动触发, 批量修改项目角色
     */
    @PostMapping("batch/update")
    McR batchUpdate(HttpServletRequest request) {
        Map<String, ?> data = UtilServlet.getParamMap(request);
        log.info("批量修改项目角色, {}", data);
        McException.assertParamException_Null(data, "fieldName, preName, modifyName");

        String fieldName = UtilMap.getString(data, "fieldName");
        String preName = UtilMap.getString(data, "preName");
        String modifyName = UtilMap.getString(data, "modifyName");
        awClint.batchUpdate(fieldName, preName, modifyName, UtilMap.getString(data, "projectId"));
        return McR.success();
    }


    /**
     * 提供verifier数据读取服务
     */
    @GetMapping("verifier/sync")
    McR syncVerifier(String projectCode) {

        List<Map> dataList = awClint.syncVerifier(projectCode);
        log.info("syncVerifier, {}, {}", projectCode, dataList.size());
        return McR.success(dataList);
    }

    //////// test ////////

    @Autowired
    private TBClient tbClient;

    @Autowired
    private TBConf tbConf;

    @Autowired
    private DDConf ddConf;


    @GetMapping("t/task")
    McR task(String taskId) {

        log.info("taskId, {}", taskId);
        List<Map> tList = tbClient.queryTaskDetail(taskId, "", "");
        return McR.success(tList);
    }

    @GetMapping("t/template")
    McR template(String name) {

        List<Map> tList = tbClient.templateSearch(null, name);
        return McR.success(tList);
    }

    @Autowired
    private YDClient ydClient;

    @Autowired
    private YDService ydService;

    @Autowired
    private McDelegate mcDelegate;

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

        Map<String, ?> data = UtilServlet.getParamMap(request);
        log.info("test, {}", data);

        awClint.test();
        return McR.success();
    }

    @GetMapping("tmp")
    McR tmp(String programIds) {

        return McR.success(tbClient.queryProgramList(programIds));
    }
}
