package com.zkqy.web.controller.dragForm;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.zkqy.common.core.controller.BaseController;
import com.zkqy.common.core.domain.AjaxResult;
import com.zkqy.common.utils.form.FromUtils;
import com.zkqy.system.entity.CommonEntity;
import com.zkqy.system.entity.DragForm;
import com.zkqy.system.entity.DragTable;
import com.zkqy.system.entity.DragTableBtn;
import com.zkqy.system.entity.vo.DragTableBtnDefaultVo;
import com.zkqy.system.mapper.DragTableMapper;
import com.zkqy.system.service.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;

/**
 * @author hanzihang
 * @date 2023/11/16 5:49 PM
 */
@RestController
@RequestMapping("/dragform/commonbtn")
public class CommonBtnController extends BaseController {
    @Resource // 共通crud
    private ICommonService commonService;

    @Resource // 动态表单
    private IDragFormService dragFormService;

    @Resource // 表格按钮
    private IDragTableBtnService iDragTableBtnService;

    @Resource
    private FromUtils fromUtils;

    @Resource
    private DragTableMapper dragTableMapper;

    @Resource
    private IDragTableGroupService dragTableGroupService;

    @Resource
    private IDragTableService dragTableService;

    @GetMapping("/hauxian/btn")
    public Object asd12312312312() throws Exception {

        String btnJson = "{\n" + "  \"remark\": \"默认初始化\",\n" + "  \"btnParentId\": 0,\n"
            + "  \"ancestorsId\": \"0\",\n" + "  \"btnKey\": \"66f9462f-3200-4339-9a8e-3325fd83130a\",\n"
            + "  \"btnGroupName\": \"组名称\",\n" + "  \"btnGroupType\": \"top\",\n" + "  \"btnName\": \"操作\",\n"
            + "  \"btnType\": \"DIRECTORY\",\n" + "  \"btnIcon\": \"bpmn-icon-data-store\",\n"
            + "  \"btnFormKey\": null,\n" + "  \"btnFormType\": \"noNeed\",\n" + "  \"btnProcessKey\": \"\",\n"
            + "  \"btnTableKey\": \"\",\n" + "  \"btnScriptKey\": \"\",\n" + "  \"btnTableFormGroupKey\": null,\n"
            + "  \"btnShowCondition\": \"\",\n"
            + "  \"btnParams\": \"{\\\"commonFieldData\\\":[],\\\"conditionData\\\":[]}\",\n"
            + "  \"btnHasPermi\": \"\",\n" + "  \"btnSort\": 0,\n" + "  \"children\": [\n" + "    {\n"
            + "      \"remark\": \"默认初始化\",\n" + "      \"btnParentId\": 0,\n" + "      \"ancestorsId\": \"0,0\",\n"
            + "      \"btnKey\": \"ece9101a-599a-4d0e-a987-b5241e463f1e\",\n" + "      \"btnGroupName\": \"\",\n"
            + "      \"btnGroupType\": \"top\",\n" + "      \"btnName\": \"新增\",\n" + "      \"btnType\": \"INSERT\",\n"
            + "      \"btnIcon\": \"el-icon-plus@primary\",\n" + "      \"btnFormKey\": null,\n"
            + "      \"btnFormType\": \"noNeed\",\n" + "      \"btnProcessKey\": \"\",\n"
            + "      \"btnTableKey\": \"\",\n" + "      \"btnScriptKey\": \"\",\n"
            + "      \"btnTableFormGroupKey\": null,\n" + "      \"btnShowCondition\": \"\",\n"
            + "      \"btnParams\": \"{\\\"commonFieldData\\\":[],\\\"conditionData\\\":[]}\",\n"
            + "      \"btnHasPermi\": \"guandao:shenqing:xinzeng\",\n" + "      \"btnSort\": 0\n" + "    },\n"
            + "    {\n" + "      \"remark\": \"默认初始化\",\n" + "      \"btnParentId\": 0,\n"
            + "      \"ancestorsId\": \"0,0\",\n" + "      \"btnKey\": \"5685de0b-96c6-4d24-89b7-5cbd9afed73e\",\n"
            + "      \"btnGroupName\": \"\",\n" + "      \"btnGroupType\": \"top\",\n" + "      \"btnName\": \"修改\",\n"
            + "      \"btnType\": \"UPDATE\",\n" + "      \"btnIcon\": \"el-icon-edit@success\",\n"
            + "      \"btnFormKey\": null,\n" + "      \"btnFormType\": \"noNeed\",\n"
            + "      \"btnProcessKey\": \"\",\n" + "      \"btnTableKey\": \"\",\n" + "      \"btnScriptKey\": \"\",\n"
            + "      \"btnTableFormGroupKey\": null,\n" + "      \"btnShowCondition\": \"\",\n"
            + "      \"btnParams\": \"{\\\"commonFieldData\\\":[],\\\"conditionData\\\":[]}\",\n"
            + "      \"btnHasPermi\": \"\",\n" + "      \"btnSort\": 1\n" + "    },\n" + "    {\n"
            + "      \"remark\": \"默认初始化\",\n" + "      \"btnParentId\": 0,\n" + "      \"ancestorsId\": \"0,0\",\n"
            + "      \"btnKey\": \"f530b421-c593-4914-bd45-b92ce533f9b9\",\n" + "      \"btnGroupName\": \"\",\n"
            + "      \"btnGroupType\": \"top\",\n" + "      \"btnName\": \"删除\",\n" + "      \"btnType\": \"DELETE\",\n"
            + "      \"btnIcon\": \"el-icon-delete@danger\",\n" + "      \"btnFormKey\": null,\n"
            + "      \"btnFormType\": \"noNeed\",\n" + "      \"btnProcessKey\": \"\",\n"
            + "      \"btnTableKey\": \"\",\n" + "      \"btnScriptKey\": \"\",\n"
            + "      \"btnTableFormGroupKey\": null,\n" + "      \"btnShowCondition\": \"\",\n"
            + "      \"btnParams\": \"{\\\"commonFieldData\\\":[],\\\"conditionData\\\":[]}\",\n"
            + "      \"btnHasPermi\": \"\",\n" + "      \"btnSort\": 2\n" + "    },\n" + "    {\n"
            + "      \"remark\": \"默认初始化\",\n" + "      \"btnParentId\": 0,\n" + "      \"ancestorsId\": \"0,0\",\n"
            + "      \"btnKey\": \"446baf01-39ae-4866-b9b7-a72616c6586f\",\n" + "      \"btnGroupName\": \"\",\n"
            + "      \"btnGroupType\": \"top\",\n" + "      \"btnName\": \"导入\",\n" + "      \"btnType\": \"IMPORT\",\n"
            + "      \"btnIcon\": \"el-icon-upload@info\",\n" + "      \"btnFormKey\": null,\n"
            + "      \"btnFormType\": \"noNeed\",\n" + "      \"btnProcessKey\": \"\",\n"
            + "      \"btnTableKey\": \"\",\n" + "      \"btnScriptKey\": \"\",\n"
            + "      \"btnTableFormGroupKey\": null,\n" + "      \"btnShowCondition\": \"\",\n"
            + "      \"btnParams\": \"{\\\"commonFieldData\\\":[],\\\"conditionData\\\":[]}\",\n"
            + "      \"btnHasPermi\": \"\",\n" + "      \"btnSort\": 3\n" + "    },\n" + "    {\n"
            + "      \"remark\": \"默认初始化\",\n" + "      \"btnParentId\": 0,\n" + "      \"ancestorsId\": \"0,0\",\n"
            + "      \"btnKey\": \"822cda1a-e40e-4ba6-9fe1-11690e33da97\",\n" + "      \"btnGroupName\": \"\",\n"
            + "      \"btnGroupType\": \"top\",\n" + "      \"btnName\": \"导出\",\n" + "      \"btnType\": \"EXPORT\",\n"
            + "      \"btnIcon\": \"el-icon-download@warning\",\n" + "      \"btnFormKey\": null,\n"
            + "      \"btnFormType\": \"noNeed\",\n" + "      \"btnProcessKey\": \"\",\n"
            + "      \"btnTableKey\": \"\",\n" + "      \"btnScriptKey\": \"\",\n"
            + "      \"btnTableFormGroupKey\": null,\n" + "      \"btnShowCondition\": \"\",\n"
            + "      \"btnParams\": \"{\\\"commonFieldData\\\":[],\\\"conditionData\\\":[]}\",\n"
            + "      \"btnHasPermi\": \"\",\n" + "      \"btnSort\": 4\n" + "    }\n" + "  ]\n" + "}";

        String jsonFilePath = "/Users/zrwj/Desktop/ZKQY_LJJ/Intelligent_manufacturing/drag_form/C:/log/qwe3.json";

        BufferedReader bufferedReader = new BufferedReader(new FileReader(jsonFilePath));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        String jsonString = sb.toString();

        // 解析JSON字符串为List<Map<String, Object>>类型
        List<Map<String, Object>> menuDataList =
            JSON.parseObject(jsonString, new TypeReference<List<Map<String, Object>>>() {});

        DragTable dragTable = new DragTable();
        dragTable.setDtType("0");

        // 得到tableList
        List<DragTable> tableList = dragTableService.selectDragTableList(dragTable);
        Map<String, Map<String, String>> tableBTNMap = new HashMap();
        tableList.forEach(item -> {
            Map<String, Object> objectMap = (Map<String, Object>)JSON.parse(item.getEchoData());
            String menuName = ((Map)objectMap.get("formData")).get("menuName").toString();
            Map<String, String> val = new HashMap<>();
            val.put("menuName", menuName);
            val.put("menuID", item.getMenuId().toString());
            tableBTNMap.put(item.getTableKey(), val);
        });
        tableBTNMap.remove("a0ede390-f1a3-429a-a4f3-3882a51a67d6"); // 当前表格已存在顶部按钮
        List<DragTableBtnDefaultVo> dragTableBtnDefaultVos = new ArrayList<>();
        // 封装按钮数据
        tableBTNMap.keySet().forEach(key -> {
            DragTableBtnDefaultVo dragTableBtnDefaultVo = new DragTableBtnDefaultVo();
            String mId = tableBTNMap.get(key).get("menuID");
            dragTableBtnDefaultVo.setTableKey(key);
            dragTableBtnDefaultVo.setMenuID(mId);
            StringBuffer fujicaidanname = new StringBuffer(); // 父级菜单Id
            menuDataList.forEach(item -> {
                if (item.get("menuId").toString().equals(mId)) {
                    menuDataList.forEach(mtem -> {
                        if (mtem.get("menuId").toString().equals(item.get("parentId").toString())) {
                            fujicaidanname.append(mtem.get("menuName"));
                        }
                    });
                }
            });
            dragTableBtnDefaultVo.setHasPermiName("huaxian:" + fujicaidanname + tableBTNMap.get(key).get("menuName"));
            DragTableBtn dragTableBtnTop = JSON.parseObject(btnJson, DragTableBtn.class);
            dragTableBtnDefaultVo.setDragTableBtnTop(dragTableBtnTop);
            dragTableBtnDefaultVos.add(dragTableBtnDefaultVo);
        });
        List<Map<String, Object>> menuList = new ArrayList<>();
        dragTableBtnDefaultVos.forEach(item -> {
            menuList.addAll(iDragTableBtnService.insertByDefaultBtn(item));
        });
        return menuList;

    }


    /**
     * 处理按钮通用接口（新增、修改、删除...） 判断什么类型走什么接口: visible false代表弹窗未开启时走回显表单模板及数据信息接口；true代表弹窗开启时走保存数据接口 是否提交表单操作 true是
     * false回显表单数据 commonEntity.getBasicMap().get("visible").toString()
     */
    @PostMapping("/commonBtnHandle")
    public AjaxResult commonBtnHandle(@RequestBody CommonEntity commonEntity) {
        // 获取到按钮类型
        String btnType = commonEntity.getBasicMap().get("btnType").toString();
        /**
         * 发起流程类型(需要特定参数)， 启动脚本类型(执行特定脚本无需传递参数)
         */
        switch (btnType) {
            case "INSERT":
                return insertBtn(commonEntity);
            case "UPDATE":
                return updateBtn(commonEntity);
            case "DELETE":
                return deleteBtn(commonEntity);
            case "EXECUTE": // 执行脚本
                return executeBtn(commonEntity);
            case "INITIATED": // 发起流程
                return initiatedBtn(commonEntity);
            default:
                return warn("暂不支持该操作！");
        }
    }

    /**
     * 新增类型按钮
     *
     * @param commonEntity
     * @return
     */

    public AjaxResult insertBtn(CommonEntity commonEntity) {
        if (commonEntity.getBasicMap().get("visible").toString().equals("true")) {
            return AjaxResult.btnMessage(commonService.batchInsert(commonEntity));
        } else if (commonEntity.getBasicMap().get("visible").toString().equals("false")) {
            String sqlKey = commonEntity.getBasicMap().get("sqlKey").toString();
            return success(dragFormService.selectDragFormBySqlKey(sqlKey));
        } else {
            return warn("暂不支持该操作！");
        }
    }

    /**
     * 修改类型按钮
     *
     * @param commonEntity
     * @return
     */
    public AjaxResult updateBtn(CommonEntity commonEntity) {
        // 是否开启弹窗
        if (commonEntity.getBasicMap().get("visible").toString().equals("true")) {
            if (commonEntity.getBasicMap().containsKey("btnKey")) { // 按钮提交时会触发别的操作
                // 根据按钮别名查询按钮详细信息
                DragTableBtn dragTableBtn = iDragTableBtnService
                    .selectDragTableBtnByBtnKey(commonEntity.getBasicMap().get("btnKey").toString());
                // 根据流程的key判断当前按钮是否执行触发流程
                if (!dragTableBtn.getBtnProcessKey().isEmpty()) {
                    // 调用发起流程接口
                    fromUtils.runBpmProductionScheduling(commonEntity);
                    // if (dragTableBtn.getBtnFormKey().isEmpty()) { // 校验当前按钮是否是直接触发流程 或者脚本 （新增按钮类型）
                    // fromUtils.runBpmProductionScheduling(commonEntity);
                    // }
                } else if (!dragTableBtn.getBtnScriptKey().isEmpty()) {
                    // 调用执行脚本接口
                    fromUtils.triggerScript(commonEntity);
                }
            }
            return toAjax(commonService.edit(commonEntity));
        } else if (commonEntity.getBasicMap().get("visible").toString().equals("false")) {
            Map<String, Object> map = new HashMap<>();
            // 单纯是表格还是弹窗里有表格
            String sqlKey = commonEntity.getBasicMap().get("sqlKey").toString();
            DragForm dragForm = dragFormService.selectDragFormBySqlKey(sqlKey);
            map.put("template", dragForm);
            // 返回结果
            map.put("result", commonService.getInfoById(commonEntity));
            return success(map);
        } else {
            return warn("暂不支持该操作！");
        }
    }

    /**
     * 删除类型按钮
     *
     * @param commonEntity
     * @return
     */
    public AjaxResult deleteBtn(CommonEntity commonEntity) {
        return toAjax(commonService.batchDelete(commonEntity));
    }

    /**
     * 按钮执行脚本
     *
     * @param commonEntity
     * @return
     */
    public AjaxResult executeBtn(CommonEntity commonEntity) {
        if (commonEntity.getBasicMap().get("visible").toString().equals("true")) {
            if (commonEntity.getBasicMap().containsKey("btnKey")) { // 按钮提交时会触发别的操作
                // 根据按钮别名查询按钮详细信息
                DragTableBtn dragTableBtn = iDragTableBtnService
                    .selectDragTableBtnByBtnKey(commonEntity.getBasicMap().get("btnKey").toString());
                if (!dragTableBtn.getBtnScriptKey().isEmpty()) {
                    // 调用执行脚本接口
                    fromUtils.triggerScript(commonEntity);
                }
            }
            commonService.edit(commonEntity);
            return AjaxResult.success("执行脚本成功！");
        } else if (commonEntity.getBasicMap().get("visible").toString().equals("false")) {
            Map<String, Object> map = new HashMap<>();
            String sqlKey = commonEntity.getBasicMap().get("sqlKey").toString();
            DragForm dragForm = dragFormService.selectDragFormBySqlKey(sqlKey);
            map.put("template", dragForm);
            map.put("result", commonService.getInfoById(commonEntity));
            return success(map);
        } else {
            return AjaxResult.error("执行脚本失败！");
        }
    }

    /**
     * 发起流程按钮
     *
     * @param commonEntity
     * @return
     */
    public AjaxResult initiatedBtn(CommonEntity commonEntity) {
        // 是否开启弹窗
        if (commonEntity.getBasicMap().get("visible").toString().equals("true")) {
            if (commonEntity.getBasicMap().containsKey("btnKey")) { // 按钮提交时会触发别的操作
                // 根据按钮别名查询按钮详细信息
                DragTableBtn dragTableBtn = iDragTableBtnService
                    .selectDragTableBtnByBtnKey(commonEntity.getBasicMap().get("btnKey").toString());
                // 根据流程的key判断当前按钮是否执行触发流程
                if (!dragTableBtn.getBtnProcessKey().isEmpty()) {
                    // 表示对当前操作是及时选择的流程模板
                    if (dragTableBtn.getBtnProcessKey().equals("unknown")) {
                        // 调用发起流程接口
                        fromUtils.runBpmProductionScheduling(commonEntity);
                    } else {
                        // 执行当前按钮绑定的流程-》暂无直接执行流程
                    }
                }
            }
            toAjax(commonService.edit(commonEntity));
            return AjaxResult.success("启动流程成功！");
        } else if (commonEntity.getBasicMap().get("visible").toString().equals("false")) {
            Map<String, Object> map = new HashMap<>();
            // 单纯是表格还是弹窗里有表格
            String sqlKey = commonEntity.getBasicMap().get("sqlKey").toString();
            DragForm dragForm = dragFormService.selectDragFormBySqlKey(sqlKey);
            map.put("template", dragForm);
            // 返回结果
            map.put("result", commonService.getInfoById(commonEntity));
            return success(map);
        } else {
            // return warn("暂不支持该操作！");
            return AjaxResult.error("发起流程失败！");
        }
    }

    /**
     * 动态表格绑定的弹窗表格结构信息
     */
    @GetMapping(value = "/getProcessPopupTableInfo")
    public AjaxResult getProcessPopupTableInfo(CommonEntity commonEntity) {
        return AjaxResult.success(dragTableGroupService.getProcessPopupTableInfo(commonEntity));
    }

    /**
     * 动态表格弹窗表格信息
     */
    @GetMapping(value = "/getProcessPopupTableList")
    public AjaxResult getProcessPopupTableList(CommonEntity commonEntity) {
        return AjaxResult.success(dragTableGroupService.getProcessPopupTableList(commonEntity));
    }

}
