package org.agt.module.license.controller.admin.project;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.agt.framework.apilog.core.annotation.ApiAccessLog;
import org.agt.framework.common.pojo.CommonResult;
import org.agt.framework.common.pojo.PageParam;
import org.agt.framework.common.pojo.PageResult;
import org.agt.framework.common.util.object.BeanUtils;
import org.agt.framework.excel.core.util.ExcelUtils;
import org.agt.framework.translate.core.TranslateUtils;
import org.agt.module.license.controller.admin.common.vo.CommonExportReqVO;
import org.agt.module.license.controller.admin.license.vo.ImportRespVO;
import org.agt.module.license.controller.admin.project.vo.ProjectImportRespVO;
import org.agt.module.license.controller.admin.project.vo.ProjectListReqVO;
import org.agt.module.license.controller.admin.project.vo.ProjectPageReqVO;
import org.agt.module.license.controller.admin.project.vo.ProjectRespVO;
import org.agt.module.license.controller.admin.project.vo.ProjectSaveReqVO;
import org.agt.module.license.dal.dataobject.project.ProjectDO;
import org.agt.module.license.service.project.ProjectService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import static org.agt.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static org.agt.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 项目")
@RestController
@RequestMapping("/license/project")
@Validated
public class ProjectController {

    @Resource
    private ProjectService projectService;

    @PostMapping("/create")
    @Operation(summary = "创建项目")
    @PreAuthorize("@ss.hasPermission('license:project:create')")
    public CommonResult<Long> createProject(@Valid @RequestBody ProjectSaveReqVO createReqVO) {
        return success(projectService.createProject(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新项目")
    @PreAuthorize("@ss.hasPermission('license:project:update')")
    public CommonResult<Boolean> updateProject(@Valid @RequestBody ProjectSaveReqVO updateReqVO) {
        projectService.updateProject(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除项目")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('license:project:delete')")
    public CommonResult<Boolean> deleteProject(@RequestParam("id") Long id) {
        projectService.deleteProject(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得项目")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('license:project:query')")
    public CommonResult<ProjectRespVO> getProject(@RequestParam("id") Long id) {
        ProjectDO project = projectService.getProject(id);
        return success(BeanUtils.toBean(project, ProjectRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得项目分页")
    @PreAuthorize("@ss.hasPermission('license:project:query')")
    public CommonResult<PageResult<ProjectRespVO>> getProjectPage(@Valid ProjectPageReqVO pageReqVO) {
        PageResult<ProjectRespVO> pageResult = projectService.getProjectPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/list")
    @Operation(summary = "获得项目列表")
    @PreAuthorize("@ss.hasPermission('license:project:query')")
    public CommonResult<List<ProjectRespVO>> getProjectPage(@Valid ProjectListReqVO pageReqVO) {
        List<ProjectRespVO> listResult = projectService.getProjectList(pageReqVO);
        return success(listResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出项目 Excel")
    @PreAuthorize("@ss.hasPermission('license:project:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProjectExcel(@Valid ProjectPageReqVO pageReqVO,
                                   HttpServletResponse response) throws IOException {
        if ("all".equals(pageReqVO.getMode())) {
            CommonExportReqVO exportReqVO = BeanUtils.toBean(pageReqVO, CommonExportReqVO.class);
            pageReqVO = BeanUtils.toBean(exportReqVO, ProjectPageReqVO.class);
            pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        }
        List<ProjectRespVO> list = projectService.getProjectPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.writeSelected(response, "项目.xlsx", pageReqVO.getSheetName(), ProjectRespVO.class,
                TranslateUtils.translate(list), pageReqVO.getIncludeFields());
    }

    @GetMapping("/name-unique")
    @Operation(summary = "校验项目名称是否唯一")
    public CommonResult<Boolean> validateProjectNameUnique(@RequestParam(value = "name", required = false) String name, @RequestParam(value = "id", required = false) Long id) {
        Boolean isExists = projectService.validateProjectNameUnique(name, id);
        return success(isExists);
    }

    @GetMapping("/code-unique")
    @Operation(summary = "校验项目编号是否唯一")
    public CommonResult<Boolean> validateProjectCodeUnique(@RequestParam(value = "code", required = false) String code, @RequestParam(value = "id", required = false) Long id) {
        Boolean isExists = projectService.validateProjectCodeUnique(code, id);
        return success(isExists);
    }

    @GetMapping("/max-sn")
    @Operation(summary = "返回当前最大项目sn")
    public CommonResult<Integer> selectMaxCode() {
        return success(projectService.selectMaxCode());
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入项目模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<ProjectImportRespVO> list = Arrays.asList(
                ProjectImportRespVO.builder().name("测试项目").serialNo("20002000").startTime(LocalDateTime.now())
                        .contractCode("111111").status(1).businessOwner(143L).technicalOwnerA(143L)
                        .businessStatus(1).customerOwner("小丽").envInfo(1).softwareVersion(1).operatingSystem(1)
                        .build(),
                ProjectImportRespVO.builder().name("测试项目2").serialNo("20002001").startTime(LocalDateTime.now())
                        .contractCode("222222").status(1).businessOwner(143L).technicalOwnerA(143L)
                        .businessStatus(1).customerOwner("小丽").envInfo(2).softwareVersion(2).operatingSystem(2)
                        .build()
        );
        // 输出
        ExcelUtils.write(response, "项目导入模板.xlsx", "项目列表", ProjectImportRespVO.class, TranslateUtils.translate(list));
    }

    @PostMapping("/import")
    @Operation(summary = "导入项目")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    @PreAuthorize("@ss.hasPermission('license:project:import')")
    public CommonResult<ImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                  @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<ProjectImportRespVO> list = ExcelUtils.read(file, ProjectImportRespVO.class);
        return success(projectService.importList(list, updateSupport));
    }

    @GetMapping("/license-list")
    @Operation(summary = "获得申请license可选择的项目列表")
    @PreAuthorize("@ss.hasPermission('license:project:query')")
    public CommonResult<List<ProjectRespVO>> getLicenseProjects(@Valid ProjectListReqVO reqVO) {
        return success(projectService.getLicenseProjects(reqVO));
    }
}