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

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.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.module.infra.api.businessfile.BusinessFileApi;
import com.zt.plat.module.infra.api.businessfile.dto.BusinessFileRespDTO;
import com.zt.plat.module.infra.api.businessfile.dto.BusinessFileWithUrlRespDTO;
import com.zt.plat.module.infra.api.file.FileApi;
import com.zt.plat.module.infra.api.file.dto.FileRespDTO;
import com.zt.plat.module.qms.common.service.BusinessFileService;
import com.zt.plat.module.qms.resource.record.constant.RecordConstants;
import com.zt.plat.module.qms.resource.record.controller.admin.recordapplydetail.vo.RecordApplyDetailPageReqVO;
import com.zt.plat.module.qms.resource.record.controller.admin.recordpermission.vo.RecordPermissionRespVO;
import com.zt.plat.module.qms.resource.record.controller.admin.recordrecord.vo.RecordRecordPageReqVO;
import com.zt.plat.module.qms.resource.record.controller.admin.recordrecord.vo.RecordRecordRespVO;
import com.zt.plat.module.qms.resource.record.controller.admin.recordrecord.vo.RecordRecordSaveReqVO;
import com.zt.plat.module.qms.resource.record.dal.dataobject.recordapplydetail.RecordApplyDetailDO;
import com.zt.plat.module.qms.resource.record.dal.dataobject.recordpermission.RecordPermissionDO;
import com.zt.plat.module.qms.resource.record.dal.dataobject.recordrecord.RecordRecordDO;
import com.zt.plat.module.qms.resource.record.service.recordapplydetail.RecordApplyDetailService;
import com.zt.plat.module.qms.resource.record.service.recordpermission.RecordPermissionService;
import com.zt.plat.module.qms.resource.record.service.recordrecord.RecordRecordService;
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.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

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

@Slf4j
@Tag(name = "管理后台 - 文件、模板、记录")
@RestController
@RequestMapping("/qms/resource/record-record")
@Validated
@DeptDataPermissionIgnore(enable = "true")
@FileUploadController(source = "qms.versionmanagement", codeKey = "data.fileUploadBusinessCode")
public class RecordRecordController extends AbstractFileUploadController implements BusinessControllerMarker {

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

    @Resource
    private RecordRecordService recordRecordService;

    @Resource
    private RecordPermissionService recordPermissionService;
    @Resource
    private BusinessFileService businessFileService;

    @Resource
    private RecordApplyDetailService recordApplyDetailService;

    @Resource
    private FileApi fileApi;


    @PostMapping("/create")
    @Operation(summary = "创建文件、模板、记录->分类明细")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:create')")
    public CommonResult<RecordRecordRespVO> createRecordRecord(@Valid @RequestBody RecordRecordSaveReqVO createReqVO) {
        return success(recordRecordService.createRecordRecord(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新文件、模板、记录")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:update')")
    public CommonResult<RecordRecordRespVO> updateRecordRecord(@Valid @RequestBody RecordRecordSaveReqVO updateReqVO) {
        RecordRecordRespVO recordRecordRespVO = recordRecordService.updateRecordRecord(updateReqVO);
        return success(recordRecordRespVO);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除文件、模板、记录")
    @Parameter(name = "id", description = "编号", required = true)
    //@PreAuthorize("@ss.hasPermission('qms:record-record:delete')")
    public CommonResult<Boolean> deleteRecordRecord(@RequestParam("id") Long id) {
        recordRecordService.deleteRecordRecord(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除文件、模板、记录")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:delete')")
    public CommonResult<Boolean> deleteRecordRecordList(@RequestBody BatchDeleteReqVO req) {
        recordRecordService.deleteRecordRecordListByIds(req.getIds());
        return success(true);
    }


    @GetMapping("/get")
    @Operation(summary = "获得文件、模板、记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:query')")
    public CommonResult<RecordRecordRespVO> getRecordRecord(@RequestParam("id") Long id, @RequestParam(value = "changNoticeFlag", required = false) Long changNoticeFlag) {
        RecordRecordDO recordRecord = recordRecordService.getRecordRecord(id);
        RecordRecordRespVO vo = BeanUtils.toBean(recordRecord, RecordRecordRespVO.class);
        CommonResult<List<BusinessFileWithUrlRespDTO>> businessFileList = businessFileService.getBusinessFileList(id);

        if (businessFileList.getData() != null) {
            businessFileList.getData().forEach(item -> item.setFileUrl(null));
        }
        vo.setBusinessFileRet(businessFileList);
        // 获取修改通知单
        if (changNoticeFlag == null || changNoticeFlag == 0) return success(vo);
        RecordApplyDetailPageReqVO pageReqVO = new RecordApplyDetailPageReqVO();
        pageReqVO.setPageSize(-1);
        pageReqVO.setDocumentId(id);
        pageReqVO.setTargetType(RecordConstants.TargetType.FILE);
        List<RecordApplyDetailDO> recordApplyDetailDOS = recordApplyDetailService.selectList(pageReqVO);
        if (ObjectUtils.isEmpty(recordApplyDetailDOS)) return success(vo);
        Set<Long> targetIds = recordApplyDetailDOS.stream().map(RecordApplyDetailDO::getTargetId).collect(Collectors.toSet());
        if (!ObjectUtils.isEmpty(targetIds)){
            targetIds.forEach(targetId -> {
                CommonResult<FileRespDTO> fileInfo = fileApi.getFileInfo(targetId);
                if (fileInfo.getData() != null) {
                    FileRespDTO data = fileInfo.getData();
                    data.setUrl(null);
                    if (vo.getChangeNoticeList() == null) {
                        vo.setChangeNoticeList(new ArrayList<>());
                    }
                    vo.getChangeNoticeList().add(fileInfo.getData());
                }
            });
        }
        return success(vo);
    }

    @GetMapping("/page")
    @Operation(summary = "获得文件、模板、记录分页")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:query')")
    public CommonResult<PageResult<RecordRecordRespVO>> getRecordRecordPage(@Valid RecordRecordPageReqVO pageReqVO) {
        PageResult<RecordRecordDO> pageResult;
        Integer isQueryHistory = pageReqVO.getIsQueryHistory();
        if (isQueryHistory != null && isQueryHistory == 1) { // 查询历史分页
            pageResult = recordRecordService.getRecordHistoryPage(pageReqVO);
        } else {
            pageResult = recordRecordService.getRecordRecordPage(pageReqVO);
        }
        return success(BeanUtils.toBean(pageResult, RecordRecordRespVO.class));
    }

    /**
     * 查询有效和即将生效的文件记录
     * 分发、作废、更改
     *
     * @param pageReqVO
     * @return
     */
    @GetMapping("/getEffectiveRecordPage")
    @Operation(summary = "获得文件、模板、记录分页")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:query')")
    public CommonResult<PageResult<RecordRecordRespVO>> getEffectiveRecordPage(@Valid RecordRecordPageReqVO pageReqVO) {
        PageResult<RecordRecordDO> pageResult;
        pageResult = recordRecordService.getEffectiveRecordPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, RecordRecordRespVO.class));
    }
    @GetMapping("/getMatchedPermissionList")
    @Operation(summary = "获得记录权限列表")
    //@PreAuthorize("@ss.hasPermission('qms:record-permission:query')")
    public CommonResult<List<RecordPermissionRespVO>> getMatchedPermissionList(@RequestParam("sourceId") Long sourceId) {
//        Long sourceId = pageReqVO.getSourceId();
        if (sourceId == null) return success(null);
        List<RecordPermissionDO> matchedPermissionList = recordPermissionService.getMatchedPermissionList(sourceId);
        return success(BeanUtils.toBean(matchedPermissionList, RecordPermissionRespVO.class));
    }


    /**
     * 流程-查看申请--查询记录列表
     *  参数：
     *      categoryId
     */
    @GetMapping("/getLookRecordList")
    @Operation(summary = "获得文件、模板、记录分页")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:query')")
    public CommonResult<PageResult<RecordRecordRespVO>> getLookRecordList(RecordRecordPageReqVO pageReqVO) {
        PageResult<RecordRecordRespVO> result = recordRecordService.getLookRecordList(pageReqVO);
        return success(BeanUtils.toBean(result, RecordRecordRespVO.class));
    }

    /**
     * 文件记录提交（不走流程）
     */
//    @GetMapping("/recordSubmit")
//    @Operation(summary = "获得文件、模板、记录分页")
//    //@PreAuthorize("@ss.hasPermission('qms:record-record:query')")
//    public CommonResult<RecordRecordRespVO> recordSubmitStatus(RecordRecordPageReqVO pageReqVO) {
//        RecordRecordDO bean = BeanUtils.toBean(pageReqVO, RecordRecordDO.class);
//        RecordRecordDO recordRecordDO = recordRecordService.recordSubmitStatus(bean);
//        return success(BeanUtils.toBean(recordRecordDO, RecordRecordRespVO.class));
//    }

    @GetMapping("/selectRecordRecordPage")
    @Operation(summary = "获得文件、模板、记录分页")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:query')")
    public CommonResult<PageResult<RecordRecordRespVO>> selectRecordRecordPage(RecordRecordPageReqVO pageReqVO) {
        PageResult<RecordRecordRespVO> result = recordRecordService.selectRecordRecordPage(pageReqVO);
        return success(BeanUtils.toBean(result, RecordRecordRespVO.class));
    }

    // 已由 XXL-Job 定时任务（updateRecordStatusJob）驱动，此接口保留用于手动触发/测试

    /**
     * 定时更新文件记录生效状态
     * @return
     */
    @GetMapping("/timing-updateRecordStatus")
    @Operation(summary = "定时更新文件、模板、记录状态")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:update')")
    public CommonResult<Boolean> timingUpdateRecordStatus() {
        recordRecordService.updateRecordStatus();
        return success(true);
    }

    /**
     * 定时更新文件到期状态（到期自动作废）
     * @return
     */
    @GetMapping("/timing-updateExpireRecordJob")
    @Operation(summary = "定时更新文件、模板、记录状态")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:update')")
    public CommonResult<Boolean> timingUpdateExpireRecordJob() {
        recordRecordService.updateExpireRecordJob();
        return success(true);
    }

}