package com.yunzhupaas.base.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.ImmutableList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.entity.DataInterfaceEntity;
import com.yunzhupaas.base.entity.DataSetEntity;
import com.yunzhupaas.base.model.datainterface.DataInterfaceModel;
import com.yunzhupaas.base.model.dataset.*;
import com.yunzhupaas.base.service.DataInterfaceService;
import com.yunzhupaas.base.service.DataSetService;
import com.yunzhupaas.base.util.dataSet.DataSetConstant;
import com.yunzhupaas.base.util.dataSet.DataSetSwapUtil;
import com.yunzhupaas.constant.DataInterfaceVarConst;
import com.yunzhupaas.constant.DbSensitiveConstant;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.model.visualJson.FieLdsModel;
import com.yunzhupaas.model.visualJson.config.ConfigModel;
import com.yunzhupaas.util.JsonUtil;
import com.yunzhupaas.util.ParameterUtil;
import com.yunzhupaas.util.RandomUtil;
import com.yunzhupaas.util.StringUtil;
import com.yunzhupaas.util.treeutil.SumTree;
import com.yunzhupaas.util.visiual.YunzhupaasKeyConsts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 数据集控制器
 *
 * @author 云筑产品开发平台组
 * @version v5.0.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2024/5/7 10:09:18
 */
@Tag(name = "数据集", description = "DataSet")
@RestController
@RequestMapping("/api/system/DataSet")
public class DataSetController {

    @Autowired
    private DataSetService dataSetService;
    @Autowired
    private DataSetSwapUtil dataSetSwapUtil;
    @Autowired
    private DataInterfaceService dataInterfaceService;

    @Operation(summary = "列表")
    @SaCheckPermission(value = { "onlineDev.printDev", "onlineDev.report" }, mode = SaMode.OR)
    @GetMapping
    public ActionResult<List<SumTree<TableTreeModel>>> list(DataSetPagination pagination) throws Exception {
        List<DataSetEntity> list = dataSetService.getList(pagination);
        List<SumTree<TableTreeModel>> res = new ArrayList<>();
        for (DataSetEntity item : list) {
            if (StringUtil.isNotEmpty(ParameterUtil.checkContainsSensitive(item.getDataConfigJson(),
                    DbSensitiveConstant.PRINT_SENSITIVE))) {
                return ActionResult.fail(MsgCode.SYS047.get());
            }
            // if (!item.getDataConfigJson().contains("@formId")) {
            // return ActionResult.fail(MsgCode.SYS048.get());
            // }
            SumTree<TableTreeModel> printTableFields = dataSetService.getTabFieldStruct(item);
            res.add(printTableFields);
        }
        return ActionResult.success(res);
    }

    @Operation(summary = "获取字段")
    @SaCheckPermission(value = { "onlineDev.printDev", "onlineDev.report" }, mode = SaMode.OR)
    @PostMapping("/fields")
    public ActionResult<List<SumTree<TableTreeModel>>> getOneFields(@RequestBody DataSetForm form) throws Exception {
        DataSetEntity item = JsonUtil.getJsonToBean(form, DataSetEntity.class);
        SumTree<TableTreeModel> printTableFields = dataSetService.getTabFieldStruct(item);
        return ActionResult.success(printTableFields.getChildren());
    }

    @Operation(summary = "获取数据")
    @PostMapping("/Data")
    public ActionResult getData(@RequestBody DataSetQuery query) {
        String moduleId = query.getModuleId();
        StpUtil.checkPermissionOr(moduleId, "onlineDev.report");
        Map<String, Object> dataMapOrList = dataSetService.getDataList(query);
        String id = query.getId();
        String convertConfig = query.getConvertConfig();
        Map<String, List<Map<String, Object>>> resultData = new HashMap<>();
        dataSetSwapUtil.swapData(id, convertConfig, dataMapOrList);
        for (String key : dataMapOrList.keySet()) {
            if (dataMapOrList.get(key) instanceof List) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMapOrList.get(key);
                resultData.put(key, list);
            }
        }
        return ActionResult.success(resultData);
    }

    @Operation(summary = "参数转换")
    @PostMapping("/parameterData")
    public ActionResult getParameterData(@RequestBody DataSetQuery query) {
        String moduleId = query.getModuleId();
        StpUtil.checkPermissionOr(moduleId, "onlineDev.report");
        Map<String, Object> queryMap = query.getMap() != null ? query.getMap() : new HashMap<>();
        List<FieLdsModel> queryList = StringUtil.isNotEmpty(query.getQueryList())
                ? JsonUtil.getJsonToList(query.getQueryList(), FieLdsModel.class)
                : new ArrayList<>();
        Map<String, Map<String, Object>> dataMap = new HashMap<>();
        List<String> systemId = ImmutableList.of(
                DataInterfaceVarConst.USER, DataInterfaceVarConst.USERANDSUB, DataInterfaceVarConst.ORG,
                DataInterfaceVarConst.ORGANDSUB, DataInterfaceVarConst.CHARORG, DataInterfaceVarConst.ID);
        List<DataSetSwapModel> convertList = new ArrayList<>();
        List<DataInterfaceModel> dataInterfaceList = new ArrayList<>();
        for (String id : systemId) {
            DataInterfaceModel model = new DataInterfaceModel();
            model.setField(id);
            model.setSourceType(4);
            model.setRelationField(id);
            model.setDefaultValue(
                    StringUtil.isNotEmpty(query.getSnowFlakeId()) ? query.getSnowFlakeId() : RandomUtil.uuId());
            dataInterfaceList.add(model);
            DataSetSwapModel swapModel = new DataSetSwapModel();
            switch (id) {
                case DataInterfaceVarConst.USER:
                case DataInterfaceVarConst.USERANDSUB:
                    swapModel.setType(DataSetConstant.KEY_USER);
                    break;
                case DataInterfaceVarConst.ORGANDSUB:
                case DataInterfaceVarConst.CHARORG:
                case DataInterfaceVarConst.ORG:
                    swapModel.setType(DataSetConstant.KEY_DEP);
                default:
                    break;
            }
            swapModel.setField(id + "." + id);
            swapModel.setConfig(new DataSetConfig());
            convertList.add(swapModel);
        }
        Map<String, String> paramSystemMap = new HashMap<>();
        dataInterfaceService.paramSourceTypeReplaceValue(dataInterfaceList, paramSystemMap);
        for (String key : paramSystemMap.keySet()) {
            String value = paramSystemMap.get(key);
            Object systemValue = Objects.equals(DataInterfaceVarConst.ID, key) ? value
                    : JsonUtil.getObjectToString(value.split(","));
            Map<String, Object> systemMap = new HashMap<>();
            systemMap.put(key, systemValue);
            dataMap.put(key, systemMap);
        }
        for (String key : queryMap.keySet()) {
            String vModel = key.replace("-", ".");
            String[] name = key.split("-");
            FieLdsModel fieLdsModel = queryList.stream().filter(t -> Objects.equals(t.getVModel(), vModel)).findFirst()
                    .orElse(null);
            if (fieLdsModel != null) {
                // 转换配置
                ConfigModel config = fieLdsModel.getConfig();
                String type = fieLdsModel.getType();
                DataSetConfig dataSetConfig = new DataSetConfig();
                dataSetConfig.setDataType(config.getDataType());
                dataSetConfig.setOptions(JsonUtil.getJsonToList(config.getOptions(), DataSetOptions.class));
                dataSetConfig.setDictionaryType(config.getDictionaryType());
                dataSetConfig.setPropsValue(config.getPropsValue());
                dataSetConfig.setFormat(config.getFormat());
                Object value = queryMap.get(key);
                switch (type) {
                    case YunzhupaasKeyConsts.NUM_INPUT:
                        type = DataSetConstant.KEY_NUMBER;
                        break;
                    case YunzhupaasKeyConsts.COMSELECT:
                        type = DataSetConstant.KEY_ORG;
                        if (value instanceof List) {
                            value = JsonUtil.getObjectToString(value);
                        }
                        break;
                    case YunzhupaasKeyConsts.DEPSELECT:
                        type = DataSetConstant.KEY_DEP;
                        if (value instanceof List) {
                            value = JsonUtil.getObjectToString(value);
                        }
                        break;
                    case YunzhupaasKeyConsts.ROLESELECT:
                        type = DataSetConstant.KEY_ROLE;
                        if (value instanceof List) {
                            value = JsonUtil.getObjectToString(value);
                        }
                        break;
                    case YunzhupaasKeyConsts.POSSELECT:
                        type = DataSetConstant.KEY_POS;
                        if (value instanceof List) {
                            value = JsonUtil.getObjectToString(value);
                        }
                        break;
                    case YunzhupaasKeyConsts.USERSELECT:
                        type = DataSetConstant.KEY_USERS;
                        if (value instanceof List) {
                            value = JsonUtil.getObjectToString(value);
                        }
                        break;
                    case YunzhupaasKeyConsts.GROUPSELECT:
                        type = DataSetConstant.KEY_GROUP;
                        if (value instanceof List) {
                            value = JsonUtil.getObjectToString(value);
                        }
                        break;
                }

                DataSetSwapModel swapModel = new DataSetSwapModel();
                swapModel.setType(type);
                swapModel.setField(fieLdsModel.getVModel());
                swapModel.setConfig(dataSetConfig);
                convertList.add(swapModel);
                // 数据
                String model = name[0];
                Map<String, Object> map = dataMap.get(model) != null ? dataMap.get(model) : new HashMap<>();
                map.put(name[1], value);
                dataMap.put(model, map);
            }
        }
        String convertConfig = JsonUtil.getObjectToString(convertList);
        Map<String, Object> dataMapOrList = new HashMap<>();
        for (String key : dataMap.keySet()) {
            List<Map<String, Object>> dataList = new ArrayList<>();
            dataList.add(dataMap.get(key));
            dataMapOrList.put(key, dataList);
        }
        dataSetSwapUtil.swapData(RandomUtil.uuId(), convertConfig, dataMapOrList);
        return ActionResult.success(dataMap);
    }

    @Operation(summary = "列表")
    @SaCheckPermission(value = { "onlineDev.printDev", "onlineDev.report" }, mode = SaMode.OR)
    @GetMapping("/getList")
    public ActionResult<List<DataSetInfo>> getList(DataSetPagination pagination) {
        List<DataSetEntity> list = dataSetService.getList(pagination);
        List<DataSetInfo> dataSetInfoList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(list)) {
            for (DataSetEntity item : list) {
                DataSetInfo bean = JsonUtil.getJsonToBean(item, DataSetInfo.class);
                try {
                    SumTree<TableTreeModel> printTableFields = dataSetService.getTabFieldStruct(item);
                    bean.setChildren(printTableFields.getChildren());
                    dataSetInfoList.add(bean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (Objects.equals(item.getType(), 3)) {
                    DataInterfaceEntity info = dataInterfaceService.getInfo(item.getInterfaceId());
                    if (info != null) {
                        bean.setTreePropsName(info.getFullName());
                    }
                }
            }
        }
        return ActionResult.success(dataSetInfoList);
    }

    @Operation(summary = "批量保存")
    @Parameters({
            @Parameter(name = "form", description = "数据集表单")
    })
    @SaCheckPermission(value = { "onlineDev.printDev", "onlineDev.report" }, mode = SaMode.OR)
    @PostMapping("/save")
    public ActionResult saveList(@RequestBody DataForm form) {
        List<DataSetInfo> list = form.getList() != null ? form.getList() : new ArrayList<>();
        dataSetService.create(JsonUtil.getJsonToList(list, DataSetForm.class), form.getObjectType(),
                form.getObjectId());
        return ActionResult.success(MsgCode.SU002.get());
    }

    @Operation(summary = "数据预览")
    @SaCheckPermission(value = { "onlineDev.printDev", "onlineDev.report" }, mode = SaMode.OR)
    @PostMapping("/getPreviewData")
    public ActionResult<DataSetViewInfo> getPreviewData(@RequestBody DataSetForm dataSetForm) {
        if (Objects.equals(dataSetForm.getType(), 3)) {
            DataSetViewInfo info = dataSetService.getPreviewDataInterface(dataSetForm);
            return ActionResult.success(info);
        }
        DataSetViewInfo info = dataSetService.getPreviewData(dataSetForm);
        return ActionResult.success(info);
    }
}
