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

import com.baomidou.mybatisplus.core.metadata.IPage;
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.qms.resource.record.constant.RecordConstants;
import com.zt.plat.module.qms.resource.record.controller.admin.recordpermission.vo.RecordPermissionPageReqVO;
import com.zt.plat.module.qms.resource.record.controller.admin.recordpermission.vo.RecordPermissionRespVO;
import com.zt.plat.module.qms.resource.record.controller.admin.recordpermission.vo.RecordPermissionSaveReqVO;
import com.zt.plat.module.qms.resource.record.controller.admin.recordrecord.vo.RecordJoinPermissionRespVO;
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.dal.dataobject.recordpermission.RecordPermissionDO;
import com.zt.plat.module.qms.resource.record.service.recordpermission.RecordPermissionService;
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-permission")
@Validated
@DeptDataPermissionIgnore(enable = "true")
@FileUploadController(source = "qms.recordpermission")
public class RecordPermissionController extends AbstractFileUploadController implements BusinessControllerMarker{

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

    @Resource
    private RecordPermissionService recordPermissionService;

    @PostMapping("/create")
    @Operation(summary = "创建记录权限")
    //@PreAuthorize("@ss.hasPermission('qms:record-permission:create')")
    public CommonResult<RecordPermissionRespVO> createRecordPermission(@Valid @RequestBody RecordPermissionSaveReqVO createReqVO) {
        return success(recordPermissionService.createRecordPermission(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新记录权限")
    //@PreAuthorize("@ss.hasPermission('qms:record-permission:update')")
    public CommonResult<Boolean> updateRecordPermission(@Valid @RequestBody RecordPermissionSaveReqVO updateReqVO) {
        recordPermissionService.updateRecordPermission(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除记录权限")
    @Parameter(name = "id", description = "编号", required = true)
    //@PreAuthorize("@ss.hasPermission('qms:record-permission:delete')")
    public CommonResult<Boolean> deleteRecordPermission(@RequestParam("id") Long id) {
        recordPermissionService.deleteRecordPermission(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除记录权限")
                //@PreAuthorize("@ss.hasPermission('qms:record-permission:delete')")
    public CommonResult<Boolean> deleteRecordPermissionList(@RequestBody BatchDeleteReqVO req) {
        recordPermissionService.deleteRecordPermissionListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得记录权限")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    //@PreAuthorize("@ss.hasPermission('qms:record-permission:query')")
    public CommonResult<RecordPermissionRespVO> getRecordPermission(@RequestParam("id") Long id) {
        RecordPermissionDO recordPermission = recordPermissionService.getRecordPermission(id);
        return success(BeanUtils.toBean(recordPermission, RecordPermissionRespVO.class));
    }

    @GetMapping("/isPermissionByUserId")
    @Operation(summary = "通过分类Id判断当前用户是否有管理员权限")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    //@PreAuthorize("@ss.hasPermission('qms:record-category:query')")
    public CommonResult<Boolean> isAdminByUserId(@RequestParam("categoryId") Long categoryId,@RequestParam("permission") String permission) {
        boolean b = false;
        boolean isAdmin = recordPermissionService.judgeIsSuperAdmin();
        if (isAdmin) return success(isAdmin);
        if (permission.equals(RecordConstants.PermissionType.ADMIN)) {
            b = recordPermissionService.hasAdminPermissionByCategoryId(categoryId);
        } else if (permission.equals(RecordConstants.PermissionType.EDIT)) {
            b = recordPermissionService.hasEditPermissionByUserId(categoryId);
        }
        return success(b);
    }

    @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));
    }

//    @GetMapping("/page")
//    @Operation(summary = "获得记录权限分页")
    //@PreAuthorize("@ss.hasPermission('qms:record-permission:query')")
    public CommonResult<PageResult<RecordPermissionRespVO>> getRecordPermissionPage(@Valid RecordPermissionPageReqVO pageReqVO) {
        PageResult<RecordPermissionDO> pageResult = recordPermissionService.getRecordPermissionPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, RecordPermissionRespVO.class));
    }


    /**
     * 通过权限查文件
     */
    @GetMapping("/selectRecordByPermission")
    @Operation(summary = "获得文件、模板、记录分页")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:query')")
    public CommonResult<PageResult<RecordJoinPermissionRespVO>> selectRecordByPermission(RecordPermissionPageReqVO pageReqVO) {
        IPage<RecordJoinPermissionRespVO> recordPermissionPageReqVOIPage = recordPermissionService.selectRecordByPermission(pageReqVO);
        PageResult<RecordJoinPermissionRespVO> pageResult =
                new PageResult<>(recordPermissionPageReqVOIPage.getRecords(), recordPermissionPageReqVOIPage.getTotal());
        return success(pageResult);
    }


    /**
     * 通过记录查权限列表
     */
    @GetMapping("/selectPermissionByRecord")
    @Operation(summary = "获得文件、模板、记录分页")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:query')")
    public CommonResult<PageResult<RecordJoinPermissionRespVO>> selectPermissionByRecord(RecordRecordPageReqVO pageReqVO) {
        IPage<RecordJoinPermissionRespVO> recordPermissionPageReqVOIPage = recordPermissionService.selectPermissionByRecord(pageReqVO);
        PageResult<RecordJoinPermissionRespVO> pageResult =
                new PageResult<>(recordPermissionPageReqVOIPage.getRecords(), recordPermissionPageReqVOIPage.getTotal());
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出记录权限 Excel")
    //@PreAuthorize("@ss.hasPermission('qms:record-permission:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportRecordPermissionExcel(@Valid RecordPermissionPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<RecordPermissionDO> list = recordPermissionService.getRecordPermissionPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "记录权限.xls", "数据", RecordPermissionRespVO.class,
                        BeanUtils.toBean(list, RecordPermissionRespVO.class));
    }

    /**
     * 定时更新 权限到期，定时回收权限
     * @return
     */
    @GetMapping("/timing-withdrawPermissionJob")
    @Operation(summary = "定时更新文件、模板、记录状态")
    //@PreAuthorize("@ss.hasPermission('qms:record-record:update')")
    public CommonResult<Boolean> timingWithdrawPermissionJob() {
        recordPermissionService.withdrawPermissionJob();
        return success(true);
    }

}