package com.yiqi.web.controller.system;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.system.domain.SysConfig;
import com.yiqi.system.domain.SysConfigRecord;
import com.yiqi.system.domain.SysDataGroupInfo;
import com.yiqi.system.domain.dto.DataGroupRules;
import com.yiqi.system.domain.dto.SysConfigTabDto;
import com.yiqi.system.service.ISysConfigRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
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.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yiqi.common.annotation.Log;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AjaxResult;
import com.yiqi.common.enums.BusinessType;
import com.yiqi.system.domain.SysConfigTab;
import com.yiqi.system.service.ISysConfigTabService;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.common.core.page.TableDataInfo;

/**
 * 配置分类Controller
 *
 * @author douya
 * @date 2024-11-01
 */
@Api(tags = "管理后台 - 配置分类")
@RestController
@RequestMapping(UrlConstants.managerApi + "/system/configTab")
public class SysConfigTabController extends BaseController {
    @Autowired
    private ISysConfigTabService sysConfigTabService;

    @Autowired
    private ISysConfigRecordService sysConfigRecordService;

    /**
     * 查询配置分类列表
     */
    @PreAuthorize("@ss.hasPermi('system:configTab:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询配置分类列表")
    public TableDataInfo list(SysConfigTab sysConfigTab) {
        startPage();
        List<SysConfigTab> list = sysConfigTabService.selectSysConfigTabList(sysConfigTab);
        return getDataTable(list);
    }

    /**
     * 查询配置分类列表
     */
    @PreAuthorize("@ss.hasPermi('system:configTab:list')")
    @GetMapping("/config_class")
    @ApiOperation(value = "查询配置分类列表")
    public TableDataInfo configClass(String title, Integer status) {
        startPage();
        SysConfigTab sysConfigTab = new SysConfigTab();
        sysConfigTab.setTitle(title);
        sysConfigTab.setStatus(status);
        List<SysConfigTab> list = sysConfigTabService.selectSysConfigTabList(sysConfigTab);
        List<SysConfigTabDto> listDto = new ArrayList<>();
        for (SysConfigTab tab : list) {
            SysConfigTabDto dto = new SysConfigTabDto();
            BeanUtil.copyProperties(tab, dto);
            List<SysConfigTab> children = sysConfigTabService.selectSysConfigTabListByPid(tab.getId());
            dto.setChildren(children);
            listDto.add(dto);
        }
        return getDataTable(listDto, new PageInfo(list).getTotal());
    }

    /**
     * 查询组合数据列表
     */
    @PostMapping("/config_class/set_status/{id}/{status}")
    @ApiOperation(value = "数据状态更新")
    public AjaxResult dataDelete(@PathVariable Integer id, @PathVariable Integer status) {
        sysConfigTabService.update(new UpdateWrapper<SysConfigTab>().eq("id", id).set("status", status));
        return success();
    }

    /**
     * 导出配置分类列表
     */
    @PreAuthorize("@ss.hasPermi('system:configTab:export')")
    @Log(title = "配置分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出配置分类列表")
    public void export(HttpServletResponse response, SysConfigTab sysConfigTab) {
        List<SysConfigTab> list = sysConfigTabService.selectSysConfigTabList(sysConfigTab);
        ExcelUtil<SysConfigTab> util = new ExcelUtil<SysConfigTab>(SysConfigTab.class);
        util.exportExcel(response, list, "配置分类数据");
    }

    /**
     * 获取配置分类详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:configTab:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取配置分类详细信息")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return success(sysConfigTabService.selectSysConfigTabById(id));
    }

    /**
     * 新增配置分类
     */
    @PreAuthorize("@ss.hasPermi('system:configTab:add')")
    @Log(title = "配置分类", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增配置分类")
    public AjaxResult add(@RequestBody SysConfigTab sysConfigTab) {
        return toAjax(sysConfigTabService.insertSysConfigTab(sysConfigTab));
    }

    /**
     * 修改配置分类
     */
    @PreAuthorize("@ss.hasPermi('system:configTab:edit')")
    @Log(title = "配置分类", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改配置分类")
    public AjaxResult edit(@RequestBody SysConfigTab sysConfigTab) {
        return toAjax(sysConfigTabService.updateSysConfigTab(sysConfigTab));
    }

    /**
     * 删除配置分类
     */
    @PreAuthorize("@ss.hasPermi('system:configTab:remove')")
    @Log(title = "配置分类", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除配置分类")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(sysConfigTabService.deleteSysConfigTabByIds(ids));
    }

    /**
     * 修改配置分类状态
     */
    @PreAuthorize("@ss.hasPermi('system:configTab:edit')")
    @Log(title = "配置分类", businessType = BusinessType.UPDATE)
    @PostMapping(value = "updateStatus")
    @ApiOperation(value = "修改配置分类状态")
    public AjaxResult updateSysConfigTabStatus(@RequestBody SysConfigTab sysConfigTab) {
        return toAjax(sysConfigTabService.updateSysConfigTabStatus(sysConfigTab));
    }

    /**
     * 获取组合数据详细信息
     */
    @GetMapping(value = "/setting/config")
    @ApiOperation(value = "获取参数配置字段列表")
    public AjaxResult settingConfig(Integer tab_id) {
        List<SysConfigRecord> sysConfigRecordList = sysConfigRecordService.list(new QueryWrapper<SysConfigRecord>().eq("config_tab_id", tab_id).orderByDesc("sort"));
        List list = new ArrayList();
        for (SysConfigRecord sysConfigRecord : sysConfigRecordList) {
            Map<String, Object> map = new HashMap<>();
            BeanUtil.copyProperties(sysConfigRecord, map);
            if (sysConfigRecord.getType().equals("upload") && sysConfigRecord.getValue() != null) {
                map.put("value", Arrays.asList(sysConfigRecord.getValue().toString()));
            }
            list.add(map);
        }
        return success(list);
    }

    /**
     * 查询组合数据列表
     */
    @PostMapping("/setting/set_status/{id}/{status}")
    @ApiOperation(value = "数据状态更新")
    public AjaxResult updateSysConfigRecordStatus(@PathVariable Integer id, @PathVariable Integer status) {
        sysConfigRecordService.update(new UpdateWrapper<SysConfigRecord>().eq("id", id).set("status", status));
        return success();
    }

    /**
     * 获取组合数据详细信息
     */
    @PostMapping(value = "/saveForm/{tabId}")
    @ApiOperation(value = "保存数据表单")
    public AjaxResult saveForm(@PathVariable Integer tabId, @RequestBody String body) {
        JSONObject jsonObject = JSONUtil.parseObj(body);
        SysConfigRecord sysConfigRecord = new SysConfigRecord();
        sysConfigRecord.setInfo(jsonObject.getStr("info"));
        sysConfigRecord.setDescition(jsonObject.getStr("descition"));
        sysConfigRecord.setHigh(jsonObject.getInt("high", 0));
        sysConfigRecord.setWidth(jsonObject.getInt("width", 0));
        sysConfigRecord.setType(jsonObject.getStr("type"));
        sysConfigRecord.setValue(jsonObject.getStr("value", ""));
        sysConfigRecord.setInputType(jsonObject.getStr("input_type"));
        sysConfigRecord.setMenuName(jsonObject.getStr("menu_name"));
        sysConfigRecord.setConfigTabId(tabId);
        sysConfigRecord.setParameter(jsonObject.getStr("parameter"));
        sysConfigRecord.setUploadType(jsonObject.getInt("upload_type", 1));
        sysConfigRecord.setRequired(jsonObject.getStr("required"));
        sysConfigRecord.setSort(jsonObject.getInt("sort", 0));
        sysConfigRecord.setStatus(jsonObject.getInt("status", 1));
        sysConfigRecordService.insertSysConfigRecord(sysConfigRecord);
        return success();
    }

    /**
     * 获取组合数据详细信息
     */
    @PostMapping(value = "/editForm/{id}")
    @ApiOperation(value = "保存数据表单")
    public AjaxResult editForm(@PathVariable Integer id, @RequestBody String body) {
        JSONObject jsonObject = JSONUtil.parseObj(body);
        SysConfigRecord sysConfigRecord = new SysConfigRecord();
        sysConfigRecord.setId(id);
        sysConfigRecord.setInfo(jsonObject.getStr("info"));
        sysConfigRecord.setDescition(jsonObject.getStr("descition"));
        sysConfigRecord.setHigh(jsonObject.getInt("high", 0));
        sysConfigRecord.setWidth(jsonObject.getInt("width", 0));
        sysConfigRecord.setType(jsonObject.getStr("type"));
        sysConfigRecord.setValue(jsonObject.getStr("value", ""));
        sysConfigRecord.setInputType(jsonObject.getStr("input_type"));
        sysConfigRecord.setMenuName(jsonObject.getStr("menu_name"));
        sysConfigRecord.setParameter(jsonObject.getStr("parameter"));
        sysConfigRecord.setUploadType(jsonObject.getInt("upload_type", 1));
        sysConfigRecord.setRequired(jsonObject.getStr("required"));
        sysConfigRecord.setSort(jsonObject.getInt("sort", 0));
        sysConfigRecord.setStatus(jsonObject.getInt("status", 1));
        sysConfigRecordService.updateSysConfigRecord(sysConfigRecord);
        return success();
    }

    /**
     * 查询配置分类列表
     */
    @PreAuthorize("@ss.hasPermi('system:configTab:list')")
    @GetMapping("/create")
    @ApiOperation(value = "查询配置分类列表")
    public AjaxResult configCreate(Integer type, Integer tabId) {
        Map map = new HashMap();
        map.put("title", "添加字段");
        map.put("status", true);
        map.put("method", "POST");
        map.put("info", "");
        map.put("action", "/mapi/system/configTab/saveForm/" + tabId);
        List<DataGroupRules> rulesList = new ArrayList<>();
        DataGroupRules info = DataGroupRules.create("input", "info", "配置名称", null, null);
        DataGroupRules menuName = DataGroupRules.create("input", "menu_name", "字段变量", "例如：site_url", null);
        DataGroupRules desc = DataGroupRules.create("input", "descition", "表单说明", null, null);
        DataGroupRules parameter = DataGroupRules.create("textarea", "parameter", "配置参数", "参数方式例如:\n1=男\n2=女\n3=保密", null);
        DataGroupRules value = DataGroupRules.create("input", "value", "默认值", null, null);
        DataGroupRules required = DataGroupRules.create("input", "required", "验证规则", "多个请用,隔开例如：required:true,url:true", null);
        DataGroupRules sort = DataGroupRules.createSortHeader(0);
        DataGroupRules status = DataGroupRules.createStatusHeader(1);
        if (type.equals(0)) {
            //单行文本框
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "text");
            DataGroupRules types = DataGroupRules.create("select", "input_type", "类型", "input=文本框\ndateTime=日期时间\ndate=日期\ntime=时间\ncolor=颜色\nnumber=数字", "");
            DataGroupRules width = DataGroupRules.create("inputNumber", "width", "文本框宽", "", 100);
            rulesList.add(hidden);
            rulesList.add(types);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(value);
            rulesList.add(width);
            rulesList.add(required);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals(1)) {
            //多行文本框
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "textarea");
            DataGroupRules width = DataGroupRules.create("inputNumber", "width", "文本框宽", "", 100);
            DataGroupRules high = DataGroupRules.create("inputNumber", "high", "多行文本框高", "", 5);
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(value);
            rulesList.add(width);
            rulesList.add(high);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals(2)) {
            //单选框
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "radio");
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(parameter);
            rulesList.add(value);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals(3)) {
            //文件上传
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "upload");
            DataGroupRules uploadType = DataGroupRules.create("radio", "upload_type", "上传类型", "1=单图\n2=多图\n3=文件", "1");
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(uploadType);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals(4)) {
            //多选框
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "checkbox");
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(parameter);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals(5)) {
            //下拉框
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "select");
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(parameter);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals(6)) {
            //开关
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "switch");
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(value);
            rulesList.add(sort);
            rulesList.add(status);
        }
        map.put("rules", rulesList);
        return success(map);
    }

    /**
     * 查询配置分类列表
     */
    @PreAuthorize("@ss.hasPermi('system:configTab:list')")
    @GetMapping("/update/{id}")
    @ApiOperation(value = "編輯表单")
    public AjaxResult configEdit(@PathVariable Integer id) {
        SysConfigRecord sysConfigRecord = sysConfigRecordService.getById(id);
        String type = sysConfigRecord.getType();
        Map map = new HashMap();
        map.put("title", "更新字段");
        map.put("status", true);
        map.put("method", "POST");
        map.put("info", "");
        map.put("action", "/mapi/system/configTab/editForm/" + id);
        List<DataGroupRules> rulesList = new ArrayList<>();
        DataGroupRules info = DataGroupRules.create("input", "info", "配置名称", null, sysConfigRecord.getInfo());
        DataGroupRules menuName = DataGroupRules.create("input", "menu_name", "字段变量", "例如：site_url", sysConfigRecord.getMenuName());
        DataGroupRules desc = DataGroupRules.create("input", "descition", "表单说明", null, sysConfigRecord.getDescition());
        DataGroupRules parameter = DataGroupRules.create("textarea", "parameter", "配置参数", "参数方式例如:\n1=男\n2=女\n3=保密", sysConfigRecord.getParameter());
        DataGroupRules value = DataGroupRules.create("input", "value", "默认值", null, sysConfigRecord.getValue());
        DataGroupRules required = DataGroupRules.create("input", "required", "验证规则", "多个请用,隔开例如：required:true,url:true", sysConfigRecord.getRequired());
        DataGroupRules sort = DataGroupRules.createSortHeader(0);
        DataGroupRules status = DataGroupRules.createStatusHeader(1);
        if (type.equals("text")) {
            //单行文本框
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "text");
            DataGroupRules types = DataGroupRules.create("select", "input_type", "类型", "input=文本框\ndateTime=日期时间\ndate=日期\ntime=时间\ncolor=颜色\nnumber=数字", sysConfigRecord.getInputType());
            DataGroupRules width = DataGroupRules.create("inputNumber", "width", "文本框宽", "", sysConfigRecord.getWidth());
            rulesList.add(hidden);
            rulesList.add(types);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(value);
            rulesList.add(width);
            rulesList.add(required);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals("textarea")) {
            //多行文本框
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "textarea");
            DataGroupRules width = DataGroupRules.create("inputNumber", "width", "文本框宽", "", sysConfigRecord.getWidth());
            DataGroupRules high = DataGroupRules.create("inputNumber", "high", "多行文本框高", "", sysConfigRecord.getHigh());
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(value);
            rulesList.add(width);
            rulesList.add(high);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals("radio")) {
            //单选框
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "radio");
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(parameter);
            rulesList.add(value);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals("upload")) {
            //文件上传
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "upload");
            DataGroupRules uploadType = DataGroupRules.create("radio", "upload_type", "上传类型", "1=单图\n2=多图\n3=文件", sysConfigRecord.getUploadType());
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(uploadType);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals("checkbox")) {
            //多选框
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "checkbox");
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(parameter);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals("select")) {
            //下拉框
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "select");
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(parameter);
            rulesList.add(sort);
            rulesList.add(status);
        } else if (type.equals("switch")) {
            //开关
            DataGroupRules hidden = DataGroupRules.create("hidden", "type", null, null, "switch");
            rulesList.add(hidden);
            rulesList.add(info);
            rulesList.add(menuName);
            rulesList.add(desc);
            rulesList.add(value);
            rulesList.add(sort);
            rulesList.add(status);
        }
        map.put("rules", rulesList);
        return success(map);
    }

    /**
     * 删除配置分类
     */
    @GetMapping("/config/header_basics")
    @ApiOperation(value = "基本信息")
    public AjaxResult header_basics(Integer tabId) {
        List<SysConfigTab> list = sysConfigTabService.selectSysConfigTabListByPid(tabId);
        if (list.size() > 0) {
            return success(list);
        }
        SysConfigTab sysConfigTab = sysConfigTabService.selectSysConfigTabById(tabId);
        return success(Arrays.asList(sysConfigTab));
    }

    /**
     * 删除配置分类
     */
    @GetMapping("/config/edit_basics")
    @ApiOperation(value = "基本信息")
    public AjaxResult edit_basics(Integer tabId) {
        List<SysConfigRecord> sysConfigRecordList = sysConfigRecordService.list(new QueryWrapper<SysConfigRecord>().eq("config_tab_id", tabId).eq("status", 1).orderByDesc("sort"));
        List<DataGroupRules> rulesList = new ArrayList<>();
        for (SysConfigRecord sysConfigRecord : sysConfigRecordList) {
            DataGroupRules dataGroupRules = DataGroupRules.createConfigForm(sysConfigRecord);
            rulesList.add(dataGroupRules);
        }
        Map map = new HashMap();
        map.put("method", "POST");
        map.put("info", "");
        map.put("action", "/mapi/system/configTab/save_basics/" + tabId);
        map.put("rules", rulesList);
        return success(map);
    }


    /**
     * 获取组合数据详细信息
     */
    @PostMapping(value = "/save_basics/{tabId}")
    @ApiOperation(value = "保存数据表单")
    public AjaxResult saveBasics(@PathVariable Integer tabId, @RequestBody String body) {
        Map<String, Object> map = JSONUtil.toBean(body, Map.class);
        for (String key : map.keySet()) {
            SysConfigRecord sysConfigRecord = sysConfigRecordService.getConfigRecordByKey(key, tabId);
            if (sysConfigRecord != null) {
                SysConfigRecord record = new SysConfigRecord();
                record.setId(sysConfigRecord.getId());
                record.setValue(map.get(key).toString());
                sysConfigRecordService.clearConfigCache(key);
                sysConfigRecordService.updateSysConfigRecord(record);
            }
        }
        return success();
    }

}
