package com.zt.plat.module.qms.common.data.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zt.plat.module.qms.common.data.controller.vo.*;
import com.zt.plat.module.qms.common.data.dal.dataobject.DataCollectionDO;
import com.zt.plat.module.qms.common.data.dal.mapper.DataTemplateMapper;
import com.zt.plat.module.qms.core.constant.DataTypeConstant;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import com.zt.plat.framework.business.interceptor.BusinessControllerMarker;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.zt.plat.framework.common.pojo.vo.BatchDeleteReqVO;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;

import static com.zt.plat.framework.common.pojo.CommonResult.success;

import com.zt.plat.framework.excel.core.util.ExcelUtils;

import com.zt.plat.framework.apilog.core.annotation.ApiAccessLog;
import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.*;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.DATA_TEMPLATE_NOT_EXISTS;

import com.zt.plat.module.qms.common.data.dal.dataobject.DataTemplateDO;
import com.zt.plat.module.qms.common.data.service.DataTemplateService;

@Tag(name = "管理后台 - 表单设计器模板")
@RestController
@RequestMapping("/qms/common/data/data-template")
@Validated
@DeptDataPermissionIgnore(enable = "true")
public class DataTemplateController implements BusinessControllerMarker {


    @Resource private DataTemplateService dataTemplateService;
    @Resource private DataTemplateMapper dataTemplateMapper;

//    @PostMapping("/create-temp-data")
//    @Operation(summary = "创建临时数据")
//    public CommonResult<DataTemplateRespVO> createTempData(@Valid @RequestBody DataTemplateSaveReqVO vo) {
//        vo.setCancelFlag("-1");
//        vo.setNodeType(DataTypeConstant.DATA_TYPE_DATA);
//        vo.setVersion(1);
//        return success(dataTemplateService.createDataTemplate(vo));
//    }

    @PostMapping("/saveData")
    @Operation(summary = "保存数据")
    @PreAuthorize("@ss.hasPermission('qms:data-template:create')")
    public CommonResult<String> saveData(@Valid @RequestBody DataTemplateSaveReqVO createReqVO) {
        return dataTemplateService.saveData(createReqVO);
    }

    @PostMapping("/saveClassify")
    @Operation(summary = "保存分类")
    @PreAuthorize("@ss.hasPermission('qms:data-template:create')")
    public CommonResult<DataTemplateRespVO> saveClassify(@Valid @RequestBody DataTemplateSaveReqVO createReqVO) {
        return dataTemplateService.saveClassify(createReqVO);
    }


    @PostMapping("/create")
    @Operation(summary = "创建表单设计器模板")
    @PreAuthorize("@ss.hasPermission('qms:data-template:create')")
    public CommonResult<DataTemplateRespVO> createDataTemplate(@Valid @RequestBody DataTemplateSaveReqVO createReqVO) {
        return success(dataTemplateService.createDataTemplate(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新表单设计器模板")
    @PreAuthorize("@ss.hasPermission('qms:data-template:update')")
    public CommonResult<Boolean> updateDataTemplate(@Valid @RequestBody DataTemplateSaveReqVO updateReqVO) {
        dataTemplateService.updateDataTemplate(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除表单设计器模板")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('qms:data-template:delete')")
    public CommonResult<Boolean> deleteDataTemplate(@RequestParam("id") Long id) {
        dataTemplateService.deleteDataTemplate(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除表单设计器模板")
                @PreAuthorize("@ss.hasPermission('qms:data-template:delete')")
    public CommonResult<Boolean> deleteDataTemplateList(@RequestBody BatchDeleteReqVO req) {
        dataTemplateService.deleteDataTemplateListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得表单设计器模板")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('qms:data-template:query')")
    public CommonResult<DataTemplateRespVO> getDataTemplate(@RequestParam("id") Long id) {
        DataTemplateDO dataTemplate = dataTemplateService.getDataTemplate(id);
        return success(BeanUtils.toBean(dataTemplate, DataTemplateRespVO.class));
    }

    @GetMapping("/getByKey")
    @Operation(summary = "获得表单设计器模板")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('qms:data-template:query')")
    public CommonResult<DataTemplateRespVO> getByKey(@RequestParam("dataKey") String dataKey) {
        LambdaQueryWrapper<DataTemplateDO> query = new LambdaQueryWrapper<>();
        query.eq(DataTemplateDO::getDataKey, dataKey);
        query.eq(DataTemplateDO::getCancelFlag, "0");
        query.eq(DataTemplateDO::getCurrentFlag, "1");
        query.eq(DataTemplateDO::getNodeType, DataTypeConstant.DATA_TYPE_DATA);
        query.orderByDesc(DataTemplateDO::getUpdateTime);
        List<DataTemplateDO> list = dataTemplateMapper.selectList(query);
        if(list.size()>0)
            return success(BeanUtils.toBean(list.get(0), DataTemplateRespVO.class));
        return CommonResult.error(DATA_TEMPLATE_NOT_EXISTS);
    }

    @GetMapping("/page")
    @Operation(summary = "获得表单设计器模板分页")
    @PreAuthorize("@ss.hasPermission('qms:data-template:query')")
    public CommonResult<PageResult<DataTemplateRespVO>> getDataTemplatePage(@Valid DataTemplatePageReqVO pageReqVO) {
        PageResult<DataTemplateDO> pageResult = dataTemplateService.getDataTemplatePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DataTemplateRespVO.class));
    }

    @GetMapping("/get-tree-data")
    @Operation(summary = "查询分类树")
    public CommonResult<List<DataTemplateRespVO>> getTreeData() {
        List<DataTemplateDO> list = dataTemplateService.getTreeData();
        return success(BeanUtils.toBean(list, DataTemplateRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出表单设计器模板 Excel")
    @PreAuthorize("@ss.hasPermission('qms:data-template:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDataTemplateExcel(@Valid DataTemplatePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DataTemplateDO> list = dataTemplateService.getDataTemplatePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "表单设计器模板.xls", "数据", DataTemplateRespVO.class,
                        BeanUtils.toBean(list, DataTemplateRespVO.class));
    }

}