package com.zt.plat.module.qms.resource.record.controller.admin.recordapply;

import com.zt.plat.framework.apilog.core.annotation.ApiAccessLog;
import com.zt.plat.framework.business.annotation.FileUploadController;
import com.zt.plat.framework.business.controller.AbstractFileUploadController;
import com.zt.plat.framework.business.interceptor.BusinessControllerMarker;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.vo.BatchDeleteReqVO;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;
import com.zt.plat.framework.excel.core.util.ExcelUtils;
import com.zt.plat.module.infra.api.businessfile.dto.BusinessFileWithUrlRespDTO;
import com.zt.plat.module.qms.common.service.BusinessFileService;
import com.zt.plat.module.qms.resource.record.controller.admin.recordapply.vo.RecordApplyPageReqVO;
import com.zt.plat.module.qms.resource.record.controller.admin.recordapply.vo.RecordApplyRespVO;
import com.zt.plat.module.qms.resource.record.controller.admin.recordapply.vo.RecordApplySaveReqVO;
import com.zt.plat.module.qms.resource.record.dal.dataobject.recordapply.RecordApplyDO;
import com.zt.plat.module.qms.resource.record.service.recordapply.RecordApplyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static com.zt.plat.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 文件记录通用申请")
@RestController
@RequestMapping("/qms/resource/record-apply")
@Validated
@DeptDataPermissionIgnore(enable = "true")
@FileUploadController(source = "qms.recordapply",codeKey = "data.fileUploadBusinessCode")
public class RecordApplyController extends AbstractFileUploadController implements BusinessControllerMarker{

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

    @Resource
    private RecordApplyService recordApplyService;

    @Resource
    private BusinessFileService businessFileService;


    @PostMapping("/create")
    @Operation(summary = "创建文件记录创建申请")
    //@PreAuthorize("@ss.hasPermission('qms:record-apply:create')")
    public CommonResult<RecordApplyRespVO> createRecordApply(@Valid @RequestBody RecordApplySaveReqVO createReqVO) {
        return success(recordApplyService.createRecordApply(createReqVO));
    }

    @PostMapping("/createApplyData")
    @Operation(summary = "创建文件申请数据")
    //@PreAuthorize("@ss.hasPermission('qms:record-apply:create')")
    public CommonResult<RecordApplyRespVO> createApplyData(@Valid @RequestBody RecordApplySaveReqVO respVO) {
        return recordApplyService.createApplyData(respVO);
    }

    @PostMapping("/submitApply")
    @Operation(summary = "创建文件记录通用申请")
    //@PreAuthorize("@ss.hasPermission('qms:record-apply:create')")
    public CommonResult<RecordApplyRespVO> submitApply(@Valid @RequestBody RecordApplySaveReqVO respVO) {
        return recordApplyService.submitRecordApply(respVO);
    }

    @PutMapping("/update")
    @Operation(summary = "更新文件记录通用申请")
    //@PreAuthorize("@ss.hasPermission('qms:record-apply:update')")
    public CommonResult<RecordApplyRespVO> updateRecordApply(@Valid @RequestBody RecordApplySaveReqVO updateReqVO) {
        RecordApplyRespVO recordApplyRespVO = recordApplyService.updateRecordApply(updateReqVO);
        return success(recordApplyRespVO);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除文件记录通用申请")
    @Parameter(name = "id", description = "编号", required = true)
    //@PreAuthorize("@ss.hasPermission('qms:record-apply:delete')")
    public CommonResult<Boolean> deleteRecordApply(@RequestParam("id") Long id) {
        recordApplyService.deleteRecordApply(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除文件记录通用申请")
                //@PreAuthorize("@ss.hasPermission('qms:record-apply:delete')")
    public CommonResult<Boolean> deleteRecordApplyList(@RequestBody BatchDeleteReqVO req) {
        recordApplyService.deleteRecordApplyListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得文件记录通用申请")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    //@PreAuthorize("@ss.hasPermission('qms:record-apply:query')")
    public CommonResult<RecordApplyRespVO> getRecordApply(@RequestParam("id") Long id) {
        RecordApplyDO recordApply = recordApplyService.getRecordApply(id);
        
        // 先转换为VO，避免JSONObject中包含ArrayList导致的转换错误
        RecordApplyRespVO respVO = BeanUtils.toBean(recordApply, RecordApplyRespVO.class);
        CommonResult<List<BusinessFileWithUrlRespDTO>> businessFileList = businessFileService.getBusinessFileList(id);
        if (businessFileList.getData() != null) {
            businessFileList.getData().forEach(item -> item.setFileUrl(null));
        }
        respVO.setBusinessFileRet(businessFileList);
        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得文件记录通用申请分页")
    //@PreAuthorize("@ss.hasPermission('qms:record-apply:query')")
    public CommonResult<PageResult<RecordApplyRespVO>> getRecordApplyPage(@Valid RecordApplyPageReqVO pageReqVO) {
        PageResult<RecordApplyDO> pageResult = recordApplyService.getRecordApplyPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, RecordApplyRespVO.class));
    }


    @GetMapping("/recordReviewPage")
    @Operation(summary = "文件评审分页")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:query')")
    public CommonResult<PageResult<RecordApplyPageReqVO>> recordReviewPage(@Valid RecordApplyPageReqVO pageReqVO) {
        PageResult<RecordApplyDO> pageResult = recordApplyService.getRecordApplyPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, RecordApplyPageReqVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出文件记录通用申请 Excel")
    //@PreAuthorize("@ss.hasPermission('qms:record-apply:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportRecordApplyExcel(@Valid RecordApplyPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<RecordApplyDO> list = recordApplyService.getRecordApplyPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "文件记录通用申请.xls", "数据", RecordApplyRespVO.class,
                        BeanUtils.toBean(list, RecordApplyRespVO.class));
    }

    /**
     * 通过定时任务，判断文件是否到期（到期自动作废）
     * @return
     */
    // 已由 XXL-Job 定时任务（XXX）驱动，此接口保留用于手动触发/测试
    @GetMapping("/timing-updateRecordStatus")
    @Operation(summary = "定时更新文件、模板、记录状态")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:update')")
    public CommonResult<Boolean> timingUpdateRecordStatus() {
//        recordApplyService.updateApplyStatus();
        return success(true);
    }

}