package com.zt.plat.module.base.controller.admin.templtp;


import com.zt.plat.module.base.controller.admin.templtp.vo.*;
import com.zt.plat.module.base.dal.dataobject.tmpltp.TemplateInstanceDO;
import com.zt.plat.module.base.service.tmpltp.TemplateInstanceService;
import com.zt.plat.module.infra.api.file.FileApi;
import com.zt.plat.module.infra.api.file.dto.FileCreateReqDTO;
import jakarta.validation.constraints.NotEmpty;
import lombok.extern.slf4j.Slf4j;
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.annotation.FileUploadController;
import com.zt.plat.framework.business.controller.AbstractFileUploadController;

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 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 org.springframework.web.multipart.MultipartFile;


import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.*;


@Slf4j
@Tag(name = "管理后台 - 模板实例")
@RestController
@RequestMapping("/base/template-instance")
@Validated
@FileUploadController(source = "base.templateinstance")
public class TemplateInstanceController extends AbstractFileUploadController {

    static {
        FileUploadController annotation = TemplateInstanceController.class.getAnnotation(FileUploadController.class);
        if (annotation != null) {
            setFileUploadInfo(annotation);
        }
    }

    @Resource
    private TemplateInstanceService templateInstanceService;

    //上传文件
//    @PostMapping("/save-file")
//    @Operation(summary = "上传文件", description = "上传文件,传入文件对象和模版实例id")
//    public CommonResult<Map<String, Object>> uploadFile(@NotEmpty(message = "文件不能为空") @RequestParam("file") MultipartFile file,@RequestParam("id") String id) {
//        return success(templateInstanceService.saveFile(file,id));
//    }

    @PostMapping("/create")
    @Operation(summary = "创建模板实例")
    //@PreAuthorize("@ss.hasPermission('base:template-instance:create')")
    public CommonResult<TemplateInstanceRespVO> createTemplateInstance(@Valid @RequestBody TemplateInstanceSaveReqVO createReqVO) {
        return success(templateInstanceService.createTemplateInstance(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新模板实例")
    //@PreAuthorize("@ss.hasPermission('base:template-instance:update')")
    public CommonResult<Boolean> updateTemplateInstance(@Valid @RequestBody TemplateInstanceSaveReqVO updateReqVO) {
        templateInstanceService.updateTemplateInstance(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除模板实例")
    @Parameter(name = "id", description = "编号", required = true)
    //@PreAuthorize("@ss.hasPermission('base:template-instance:delete')")
    public CommonResult<Boolean> deleteTemplateInstance(@RequestParam("id") Long id) {
        templateInstanceService.deleteTemplateInstance(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除模板实例")
    //@PreAuthorize("@ss.hasPermission('base:template-instance:delete')")
    public CommonResult<Boolean> deleteTemplateInstanceList(@RequestBody BatchDeleteReqVO req) {
        templateInstanceService.deleteTemplateInstanceListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得模板实例")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public CommonResult<TemplateInstanceRespVO> getTemplateInstance(@Valid @NotEmpty(message = "编号不能为空") @RequestParam("id") String id) {
        TemplateInstanceDO templateInstance = templateInstanceService.getTemplateInstance(Long.valueOf(id));
        TemplateInstanceRespVO templateInstanceRespVO = BeanUtils.toBean(templateInstance, TemplateInstanceRespVO.class);
        if (templateInstanceRespVO != null) {
            templateInstanceService.getDetailedInfo(templateInstanceRespVO);
            log.info("==================模板实例详情查询成功=================");
            return success(templateInstanceRespVO);
        }

        return success(null);
    }

    @GetMapping("/page")
    @Operation(summary = "获得模板实例分页")
    @PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public CommonResult<PageResult<TemplateInstanceRespVO>> getTemplateInstancePage(@Valid TemplateInstancePageReqVO pageReqVO) {
        PageResult<TemplateInstanceDO> pageResult = templateInstanceService.getTemplateInstancePage(pageReqVO);
        PageResult<TemplateInstanceRespVO> templateInstanceRespVOPageResult = BeanUtils.toBean(pageResult, TemplateInstanceRespVO.class);
        templateInstanceRespVOPageResult.getList().forEach(templateInstanceRespVO -> {
            if (templateInstanceRespVO != null) {
                templateInstanceService.getDetailedInfo(templateInstanceRespVO);
            }
        });
        return success(templateInstanceRespVOPageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出模板实例 Excel")
    //@PreAuthorize("@ss.hasPermission('base:template-instance:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportTemplateInstanceExcel(@Valid TemplateInstancePageReqVO pageReqVO,
                                            HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<TemplateInstanceDO> list = templateInstanceService.getTemplateInstancePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "模板实例.xls", "数据", TemplateInstanceRespVO.class,
                BeanUtils.toBean(list, TemplateInstanceRespVO.class));
    }

    //模版实例发布
    @PostMapping("/publish-batch")
    @Operation(summary = "模版实例发布")
    //@PreAuthorize("@ss.hasPermission('base:template-instance:update')")
    public CommonResult<Boolean> publishTemplateInstance(@Valid @RequestBody List<PublishTemplateInstanceReqVO> publishReqVOS) {
        templateInstanceService.publishTemplateInstance(publishReqVOS);
        return success(true);
    }

    //不显示停用状态的查询接口
    @GetMapping("/list-excluding-disabled")
    @Operation(summary = "获得模板实例")
    //@PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public CommonResult<PageResult<TemplateInstanceRespVO>> listExcludingDisabled(@Valid TemplateInstancePageReqVO pageReqVO) {
        PageResult<TemplateInstanceRespVO> templateInstanceRespVOPageResult = BeanUtils.toBean(templateInstanceService.listExcludingDisabled(pageReqVO), TemplateInstanceRespVO.class);
        templateInstanceRespVOPageResult.getList().forEach(
                templateInstanceRespVO -> {
                    if (templateInstanceRespVO != null) {
                        templateInstanceService.getDetailedInfo(templateInstanceRespVO);
                    }
                }
        );
        return success(templateInstanceRespVOPageResult);
    }

    //停用和启用接口
    @PostMapping("/disable-enable")
    @Operation(summary = "实例停用和启用接口", description = "实例停用和启用接口")
    //@PreAuthorize("@ss.hasPermission('base:template-instance:update')")
    public CommonResult<Boolean> setDisableOrEnable(@Valid @RequestBody DisableEnableReqVO reqVO) {
        templateInstanceService.setDisableOrEnable(reqVO);
        return success(true);
    }

    //根据id获取实例版本号
    @GetMapping("/get-version")
    @Operation(summary = "根据id获取实例版本号")
    @PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public CommonResult<Map<String, Object>> getVersion(@Valid @NotEmpty(message = "模版实例id不能为空") @RequestParam("id") String id) {
        return success(templateInstanceService.getVersion(id));
    }

    //创建版本
    @PostMapping("/create-version")
    @Operation(summary = "创建版本")
    //@PreAuthorize("@ss.hasPermission('base:template-instance:create')")
    public CommonResult<TemplateInstanceRespVO> createVersion(@Valid @NotEmpty(message = "模版实例id不能为空") String id) {
        return success(templateInstanceService.createVersion(id));
    }

    //通过模版编码查看历史版本
    @GetMapping("/list-by-template-cdg")
    @Operation(summary = "通过模版编码(cdg)查看历史版本", description = "通过模版编码查看历史版本,已按照发布时间和创建时间降序排序")
    @PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public CommonResult<List<TemplateInstanceRespVO>> listByTemplateCode(@RequestParam("cdg") @Valid @NotEmpty(message = "模版编号不能为空") String templateCode) {
        return success(templateInstanceService.listByCdg(templateCode));
    }

    //通过实例id获取字段和条款详情
    @GetMapping("/field-and-clause-detail")
    @Operation(summary = "通过实例id获取字段和条款详情")
    @PreAuthorize("@ss.hasPermission('base:template-instance:query')")
    public CommonResult<FieldAndClauseRespVO> getFieldAndClauseDetail(@Valid @NotEmpty(message = "模版实例id不能为空") @RequestParam("id") String id) {
        return success(templateInstanceService.getFieldAndClauseDetail(id));
    }
}
