package com.yiqi.web.controller.system;

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

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.system.domain.SysDataGroupInfo;
import com.yiqi.system.domain.dto.DataGroupFiled;
import com.yiqi.system.domain.dto.DataGroupHeader;
import com.yiqi.system.domain.dto.DataGroupRules;
import com.yiqi.system.service.ISysDataGroupInfoService;
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.SysDataGroup;
import com.yiqi.system.service.ISysDataGroupService;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.common.core.page.TableDataInfo;

/**
 * 组合数据Controller
 *
 * @author douya
 * @date 2024-10-29
 */
@Api(tags = "管理后台 - 组合数据")
@RestController
@RequestMapping(UrlConstants.managerApi + "/system/group")
public class SysDataGroupController extends BaseController {

    @Autowired
    private ISysDataGroupService sysDataGroupService;

    @Autowired
    private ISysDataGroupInfoService sysDataGroupInfoService;


    //<editor-folder desc="基础函数">

    /**
     * 查询组合数据列表
     */
    @PreAuthorize("@ss.hasPermi('system:group:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询组合数据列表")
    public TableDataInfo list(SysDataGroup sysDataGroup) {
        startPage();
        List<SysDataGroup> list = sysDataGroupService.selectSysDataGroupList(sysDataGroup);
        return getDataTable(list);
    }

    /**
     * 导出组合数据列表
     */
    @PreAuthorize("@ss.hasPermi('system:group:export')")
    @Log(title = "组合数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出组合数据列表")
    public void export(HttpServletResponse response, SysDataGroup sysDataGroup) {
        List<SysDataGroup> list = sysDataGroupService.selectSysDataGroupList(sysDataGroup);
        ExcelUtil<SysDataGroup> util = new ExcelUtil<SysDataGroup>(SysDataGroup.class);
        util.exportExcel(response, list, "组合数据数据");
    }

    /**
     * 获取组合数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:group:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取组合数据详细信息")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return success(sysDataGroupService.selectSysDataGroupById(id));
    }

    /**
     * 获取组合数据详细信息
     */
    @GetMapping(value = "/header/info")
    @ApiOperation(value = "获取组合数据头信息")
    public AjaxResult getHeaderInfo(Integer gid) {
        SysDataGroup sysDataGroup = sysDataGroupService.selectSysDataGroupById(gid);
        List<DataGroupFiled> dataGroupFileds = JSONUtil.toList(JSONUtil.parseArray(sysDataGroup.getFields()), DataGroupFiled.class);
        DataGroupHeader id = DataGroupHeader.createIdHeader();
        DataGroupHeader status = DataGroupHeader.createStatusHeader();
        DataGroupHeader action = DataGroupHeader.createActionHeader();
        DataGroupHeader sort = DataGroupHeader.createSortHeader();
        List<DataGroupHeader> headers = new ArrayList<>();
        headers.add(id);
        for (DataGroupFiled dataGroupFiled : dataGroupFileds) {
            DataGroupHeader dataGroupHeader = DataGroupHeader.create(dataGroupFiled.getTitle(), dataGroupFiled.getName(), dataGroupFiled.getType());
            headers.add(dataGroupHeader);
        }
        headers.add(status);
        headers.add(sort);
        headers.add(action);
        Map<String, List<DataGroupHeader>> map = new HashMap<>();
        map.put("header", headers);
        return success(map);
    }

    /**
     * 查询组合数据列表
     */
    @PreAuthorize("@ss.hasPermi('system:group:list')")
    @GetMapping("/data/list")
    @ApiOperation(value = "查询组合数据结果列表")
    public TableDataInfo dataList(Integer gid, Integer status) {
        startPage();
        List<SysDataGroupInfo> list = sysDataGroupInfoService.getDataList(gid, status);
        SysDataGroup sysDataGroup = sysDataGroupService.selectSysDataGroupById(gid);
        List<DataGroupFiled> dataGroupFileds = JSONUtil.toList(JSONUtil.parseArray(sysDataGroup.getFields()), DataGroupFiled.class);
        Map<String, DataGroupRules> rulesMap = new HashMap<>();
        for (DataGroupFiled dataGroupFiled : dataGroupFileds) {
            DataGroupRules dataGroupHeader = DataGroupRules.create(dataGroupFiled.getType(), dataGroupFiled.getTitle(), dataGroupFiled.getName(), dataGroupFiled.getParam(), null);
            rulesMap.put(dataGroupHeader.getField(), dataGroupHeader);
        }
        List<Map<String, Object>> objectList = new ArrayList<>();
        for (SysDataGroupInfo sysDataGroupInfo : list) {
            JSONObject jsonObject = JSONUtil.parseObj(sysDataGroupInfo.getValue());
            Map<String, Object> map = new HashMap<>();
            for (DataGroupFiled dataGroupFiled : dataGroupFileds) {
                if (jsonObject.get(dataGroupFiled.getTitle()) != null) {
                    if (dataGroupFiled.getType().equals("input") || dataGroupFiled.getType().equals("textarea")) {
                        map.put(dataGroupFiled.getTitle(), jsonObject.get(dataGroupFiled.getTitle()));
                    } else if (dataGroupFiled.getType().equals("radio") || dataGroupFiled.getType().equals("select")) {
                        map.put(dataGroupFiled.getTitle(), DataGroupRules.getSigleOptionValue(jsonObject.get(dataGroupFiled.getTitle()).toString(), dataGroupFiled.getParam()));
                    } else if (dataGroupFiled.getType().equals("checkbox")) {
                        map.put(dataGroupFiled.getTitle(), DataGroupRules.getMuliteOptionValue(jsonObject.get(dataGroupFiled.getTitle()).toString(), dataGroupFiled.getParam()));
                    } else if (dataGroupFiled.getType().equals("upload")) {
                        map.put(dataGroupFiled.getTitle(), jsonObject.get(dataGroupFiled.getTitle()));
                    }
                }
            }
            map.put("sort", sysDataGroupInfo.getSort());
            map.put("id", sysDataGroupInfo.getId());
            map.put("status", sysDataGroupInfo.getStatus());
            map.put("createTime", sysDataGroupInfo.getCreateTime());
            objectList.add(map);
        }
        return getDataTable(objectList, new PageInfo(list).getTotal());
    }

    /**
     * 查询组合数据列表
     */
    @GetMapping("/data/select/{gid}")
    @ApiOperation(value = "查询组合数据结果(下拉筛选)")
    public AjaxResult dataList(@PathVariable("gid") Integer gid) {
        SysDataGroup sysDataGroup = sysDataGroupService.selectSysDataGroupById(gid);
        List<SysDataGroupInfo> list = sysDataGroupInfoService.getDataList(gid, 1);
        List<DataGroupFiled> dataGroupFileds = JSONUtil.toList(JSONUtil.parseArray(sysDataGroup.getFields()), DataGroupFiled.class);
        Map<String, DataGroupRules> rulesMap = new HashMap<>();
        for (DataGroupFiled dataGroupFiled : dataGroupFileds) {
            DataGroupRules dataGroupHeader = DataGroupRules.create(dataGroupFiled.getType(), dataGroupFiled.getTitle(), dataGroupFiled.getName(), dataGroupFiled.getParam(), null);
            rulesMap.put(dataGroupHeader.getField(), dataGroupHeader);
        }
        List<Map<String, Object>> objectList = new ArrayList<>();
        for (SysDataGroupInfo sysDataGroupInfo : list) {
            JSONObject jsonObject = JSONUtil.parseObj(sysDataGroupInfo.getValue());
            Map<String, Object> map = new HashMap<>();
            for (DataGroupFiled dataGroupFiled : dataGroupFileds) {
                if (jsonObject.get(dataGroupFiled.getTitle()) != null) {
                    if (dataGroupFiled.getType().equals("input") || dataGroupFiled.getType().equals("textarea")) {
                        map.put(dataGroupFiled.getTitle(), jsonObject.get(dataGroupFiled.getTitle()));
                    } else if (dataGroupFiled.getType().equals("radio") || dataGroupFiled.getType().equals("select")) {
                        map.put(dataGroupFiled.getTitle(), DataGroupRules.getSigleOptionValue(jsonObject.get(dataGroupFiled.getTitle()).toString(), dataGroupFiled.getParam()));
                    } else if (dataGroupFiled.getType().equals("checkbox")) {
                        map.put(dataGroupFiled.getTitle(), DataGroupRules.getMuliteOptionValue(jsonObject.get(dataGroupFiled.getTitle()).toString(), dataGroupFiled.getParam()));
                    } else if (dataGroupFiled.getType().equals("upload")) {
                        map.put(dataGroupFiled.getTitle(), jsonObject.get(dataGroupFiled.getTitle()));
                    }
                }
            }
            map.put("sort", sysDataGroupInfo.getSort());
            map.put("id", sysDataGroupInfo.getId());
            map.put("status", sysDataGroupInfo.getStatus());
            map.put("createTime", sysDataGroupInfo.getCreateTime());
            objectList.add(map);
        }
        return success(objectList);
    }

    /**
     * 查询组合数据列表
     */
    @GetMapping("/data/selectByKey")
    @ApiOperation(value = "查询组合数据结果(下拉筛选)")
    public AjaxResult dataListByKey(String key) {
        SysDataGroup sysDataGroup = sysDataGroupService.selectSysDataGroupByKey(key);
        List<SysDataGroupInfo> list = sysDataGroupInfoService.getDataList(sysDataGroup.getId(), 1);
        List<DataGroupFiled> dataGroupFileds = JSONUtil.toList(JSONUtil.parseArray(sysDataGroup.getFields()), DataGroupFiled.class);
        Map<String, DataGroupRules> rulesMap = new HashMap<>();
        for (DataGroupFiled dataGroupFiled : dataGroupFileds) {
            DataGroupRules dataGroupHeader = DataGroupRules.create(dataGroupFiled.getType(), dataGroupFiled.getTitle(), dataGroupFiled.getName(), dataGroupFiled.getParam(), null);
            rulesMap.put(dataGroupHeader.getField(), dataGroupHeader);
        }
        List<Map<String, Object>> objectList = new ArrayList<>();
        for (SysDataGroupInfo sysDataGroupInfo : list) {
            JSONObject jsonObject = JSONUtil.parseObj(sysDataGroupInfo.getValue());
            Map<String, Object> map = new HashMap<>();
            for (DataGroupFiled dataGroupFiled : dataGroupFileds) {
                if (jsonObject.get(dataGroupFiled.getTitle()) != null) {
                    if (dataGroupFiled.getType().equals("input") || dataGroupFiled.getType().equals("textarea")) {
                        map.put(dataGroupFiled.getTitle(), jsonObject.get(dataGroupFiled.getTitle()));
                    } else if (dataGroupFiled.getType().equals("radio") || dataGroupFiled.getType().equals("select")) {
                        map.put(dataGroupFiled.getTitle(), DataGroupRules.getSigleOptionValue(jsonObject.get(dataGroupFiled.getTitle()).toString(), dataGroupFiled.getParam()));
                    } else if (dataGroupFiled.getType().equals("checkbox")) {
                        map.put(dataGroupFiled.getTitle(), DataGroupRules.getMuliteOptionValue(jsonObject.get(dataGroupFiled.getTitle()).toString(), dataGroupFiled.getParam()));
                    } else if (dataGroupFiled.getType().equals("upload")) {
                        map.put(dataGroupFiled.getTitle(), jsonObject.get(dataGroupFiled.getTitle()));
                    }
                }
            }
            map.put("sort", sysDataGroupInfo.getSort());
            map.put("id", sysDataGroupInfo.getId());
            map.put("status", sysDataGroupInfo.getStatus());
            map.put("createTime", sysDataGroupInfo.getCreateTime());
            objectList.add(map);
        }
        return success(objectList);
    }

    /**
     * 查询组合数据列表
     */
    @DeleteMapping("/data/delete/{id}")
    @ApiOperation(value = "数据删除")
    public AjaxResult dataDelete(@PathVariable Integer id) {
        sysDataGroupInfoService.removeById(id);
        return success();
    }

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

    /**
     * 获取组合数据详细信息
     */
    @PostMapping(value = "/data/saveForm")
    @ApiOperation(value = "保存数据表单")
    public AjaxResult saveForm(@RequestBody String body) {
        JSONObject jsonObject = JSONUtil.parseObj(body);
        Integer gid = jsonObject.getInt("gid");
        SysDataGroupInfo sysDataGroupInfo = new SysDataGroupInfo();
        sysDataGroupInfo.setGid(gid);
        sysDataGroupInfo.setStatus(jsonObject.getInt("status", 1));
        sysDataGroupInfo.setSort(jsonObject.getInt("sort", 0));
        sysDataGroupInfo.setCreateTime(new Date());
        sysDataGroupInfo.setValue(body);
        sysDataGroupInfoService.save(sysDataGroupInfo);
        return success();
    }

    /**
     * 获取组合数据详细信息
     */
    @PostMapping(value = "/data/updateForm/{id}")
    @ApiOperation(value = "保存数据表单")
    public AjaxResult updateForm(@PathVariable Integer id, @RequestBody String body) {
        JSONObject jsonObject = JSONUtil.parseObj(body);
        Integer gid = jsonObject.getInt("gid");
        SysDataGroupInfo sysDataGroupInfo = sysDataGroupInfoService.getById(id);
        sysDataGroupInfo.setGid(gid);
        sysDataGroupInfo.setStatus(jsonObject.getInt("status", 1));
        sysDataGroupInfo.setSort(jsonObject.getInt("sort", 0));
        sysDataGroupInfo.setCreateTime(new Date());
        sysDataGroupInfo.setValue(body);
        sysDataGroupInfoService.updateById(sysDataGroupInfo);
        return success();
    }

    /**
     * 获取组合数据详细信息
     */
    @GetMapping(value = "/data/createForm")
    @ApiOperation(value = "创建数据表单")
    public AjaxResult createForm(Integer gid) {
        SysDataGroup sysDataGroup = sysDataGroupService.selectSysDataGroupById(gid);
        List<DataGroupFiled> dataGroupFileds = JSONUtil.toList(JSONUtil.parseArray(sysDataGroup.getFields()), DataGroupFiled.class);
        Map map = new HashMap();
        map.put("title", "添加数据");
        map.put("status", true);
        map.put("method", "POST");
        map.put("info", "");
        map.put("action", "/mapi/system/group/data/saveForm");
        List<DataGroupRules> rulesList = new ArrayList<>();
        DataGroupRules status = DataGroupRules.createStatusHeader(1);
        DataGroupRules sort = DataGroupRules.createSortHeader(1);
        DataGroupRules gidRules = DataGroupRules.createGidHeader(gid);
        for (DataGroupFiled dataGroupFiled : dataGroupFileds) {
            DataGroupRules dataGroupHeader = DataGroupRules.create(dataGroupFiled.getType(), dataGroupFiled.getTitle(), dataGroupFiled.getName(), dataGroupFiled.getParam(), null);
            rulesList.add(dataGroupHeader);
        }
        rulesList.add(gidRules);
        rulesList.add(sort);
        rulesList.add(status);
        map.put("rules", rulesList);
        return success(map);
    }

    /**
     * 获取组合数据详细信息
     */
    @GetMapping(value = "/data/editForm")
    @ApiOperation(value = "创建数据表单")
    public AjaxResult editForm(Integer id) {
        SysDataGroupInfo sysDataGroupInfo = sysDataGroupInfoService.getById(id);
        SysDataGroup sysDataGroup = sysDataGroupService.selectSysDataGroupById(sysDataGroupInfo.getGid());
        List<DataGroupFiled> dataGroupFileds = JSONUtil.toList(JSONUtil.parseArray(sysDataGroup.getFields()), DataGroupFiled.class);
        Map map = new HashMap();
        map.put("title", "添加数据");
        map.put("status", true);
        map.put("method", "POST");
        map.put("info", "");
        map.put("action", "/mapi/system/group/data/updateForm/" + id);
        JSONObject jsonObject = JSONUtil.parseObj(sysDataGroupInfo.getValue());
        List<DataGroupRules> rulesList = new ArrayList<>();
        DataGroupRules status = DataGroupRules.createStatusHeader(sysDataGroupInfo.getStatus());
        DataGroupRules sort = DataGroupRules.createSortHeader(sysDataGroupInfo.getSort());
        DataGroupRules gidRules = DataGroupRules.createGidHeader(sysDataGroupInfo.getGid());
        for (DataGroupFiled dataGroupFiled : dataGroupFileds) {
            DataGroupRules dataGroupHeader = DataGroupRules.create(dataGroupFiled.getType(), dataGroupFiled.getTitle(), dataGroupFiled.getName(), dataGroupFiled.getParam(), jsonObject.get(dataGroupFiled.getTitle()));
            rulesList.add(dataGroupHeader);
        }
        rulesList.add(gidRules);
        rulesList.add(sort);
        rulesList.add(status);
        map.put("rules", rulesList);
        return success(map);
    }

    /**
     * 新增组合数据
     */
    @PreAuthorize("@ss.hasPermi('system:group:add')")
    @PostMapping
    @ApiOperation(value = "新增组合数据")
    public AjaxResult add(@RequestBody SysDataGroup sysDataGroup) {
        return toAjax(sysDataGroupService.insertSysDataGroup(sysDataGroup));
    }

    /**
     * 修改组合数据
     */
    @PreAuthorize("@ss.hasPermi('system:group:edit')")
    @PostMapping(value = "/{id}")
    @ApiOperation(value = "修改组合数据")
    public AjaxResult edit(@PathVariable Integer id, @RequestBody SysDataGroup sysDataGroup) {
        sysDataGroup.setId(id);
        return toAjax(sysDataGroupService.updateSysDataGroup(sysDataGroup));
    }

    /**
     * 删除组合数据
     */
    @PreAuthorize("@ss.hasPermi('system:group:remove')")
    @Log(title = "组合数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除组合数据")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(sysDataGroupService.deleteSysDataGroupByIds(ids));
    }


}
