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

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.license.vo.LicenseCodeImportExcelVO;
import org.agt.module.license.controller.admin.license.vo.LicenseDetailVO;
import org.agt.module.license.controller.admin.license.vo.LicenseImportExcelVO;
import org.agt.module.license.controller.admin.license.vo.LicensePageReqVO;
import org.agt.module.license.controller.admin.license.vo.LicensePageRespVO;
import org.agt.module.license.controller.admin.license.vo.LicenseRespVO;
import org.agt.module.license.controller.admin.license.vo.LicenseSaveReqVO;
import org.agt.module.license.service.license.LicenseService;
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.LocalDate;
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 = "管理后台 - License")
@RestController
@RequestMapping("/license/license")
@Validated
public class LicenseController {

    @Resource
    private LicenseService licenseService;

    @PostMapping("/create")
    @Operation(summary = "创建License")
    @PreAuthorize("@ss.hasPermission('license:license:apply')")
    public CommonResult<Long> createLicense(@Valid @RequestBody LicenseSaveReqVO createReqVO) {
        return success(licenseService.createLicense(createReqVO, false));
    }

    @PutMapping("/update")
    @Operation(summary = "更新License")
    @PreAuthorize("@ss.hasPermission('license:license:update')")
    public CommonResult<Boolean> updateLicense(@Valid @RequestBody LicenseSaveReqVO updateReqVO) {
        licenseService.updateLicense(updateReqVO);
        return success(true);
    }

    @PutMapping("/apply")
    @Operation(summary = "申请License")
    @PreAuthorize("@ss.hasPermission('license:license:apply')")
    public CommonResult<Boolean> applyLicense(@Valid @RequestBody LicenseSaveReqVO updateReqVO) {
        licenseService.applyLicense(updateReqVO, null);
        return success(true);
    }

    @PutMapping("/reapply")
    @Operation(summary = "重新申请License")
    @PreAuthorize("@ss.hasPermission('license:license:reapply')")
    public CommonResult<Boolean> reapplyLicense(@Valid @RequestBody LicenseSaveReqVO updateReqVO) {
        licenseService.reapplyLicense(updateReqVO);
        return success(true);
    }

    @GetMapping("/generate")
    @Operation(summary = "生成License")
    @PreAuthorize("@ss.hasPermission('license:license:generate')")
    public CommonResult<String> generate(@RequestParam("id") Long id) {
        String url = licenseService.generate(id);
        return success(url);
    }

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

    @GetMapping("/get")
    @Operation(summary = "获得License")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('license:license:query')")
    public CommonResult<LicenseRespVO> getLicense(@RequestParam("id") Long id) {
        LicenseRespVO license = licenseService.getLicense(id);
        return success(license);
    }

    @GetMapping("/history")
    @Operation(summary = "获得License历史列表")
    @PreAuthorize("@ss.hasPermission('license:license:query')")
    public CommonResult<List<LicenseRespVO>> getLicensePage(@RequestParam("id") Long id) {
        List<LicenseRespVO> licenseHistory = licenseService.getLicenseHistory(id);
        return success(licenseHistory);
    }

    @GetMapping("/page")
    @Operation(summary = "获得License分页")
    @PreAuthorize("@ss.hasPermission('license:license:query')")
    public CommonResult<PageResult<LicensePageRespVO>> getLicensePage(@Valid LicensePageReqVO pageReqVO) {
        PageResult<LicensePageRespVO> pageResult = licenseService.getLicensePage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/list-expiry")
    @Operation(summary = "获得License到期列表")
//    @PreAuthorize("@ss.hasPermission('license:license:query')")
    public CommonResult<List<LicenseRespVO>> getLicenseByExpiryDate() {
        List<LicenseRespVO> licenseHistory = licenseService.getLicenseByExpiryDate();
        return success(licenseHistory);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出License Excel")
    @PreAuthorize("@ss.hasPermission('license:license:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportLicenseExcel(@Valid LicensePageReqVO pageReqVO,
                                   HttpServletResponse response) throws IOException {
        if ("all".equals(pageReqVO.getMode())) {
            CommonExportReqVO exportReqVO = BeanUtils.toBean(pageReqVO, CommonExportReqVO.class);
            pageReqVO = BeanUtils.toBean(exportReqVO, LicensePageReqVO.class);
            pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        }
        List<LicensePageRespVO> voList = licenseService.getLicensePage(pageReqVO).getList();

//        List<LicenseRespVO> results = new ArrayList<>();
//        for (LicenseRespVO license : voList) {
//            license.setExpiryDateExt(license.getExpiryDate().toLocalDate());
//            List<LicenseDetailVO> neCodeList = license.getNeCodeList();
//            if (CollUtil.isEmpty(neCodeList)) {
//                results.add(license);
//            } else {
//                for (LicenseDetailVO licenseDetailVO : neCodeList) {
//                    LicenseRespVO licenseVO = new LicenseRespVO();
//                    BeanUtils.copyProperties(license, licenseVO);
//
//                    List<String> neLabels = new ArrayList<>();
//                    for (Integer ne : licenseDetailVO.getNeList()) {
//                        String label = DictFrameworkUtils.parseDictDataLabel("lic_ne_all", ne.toString());
//                        if (StrUtil.isBlank(label)) {
//                            label = DictFrameworkUtils.parseDictDataLabel("lic_ne_5g", ne.toString());
//                            if (StrUtil.isBlank(label)) {
//                                label = DictFrameworkUtils.parseDictDataLabel("lic_ne_4g", ne.toString());
//                                if (StrUtil.isBlank(label)) {
//                                    label = DictFrameworkUtils.parseDictDataLabel("lic_ne_23g", ne.toString());
//                                    if (StrUtil.isBlank(label)) {
//                                        label = DictFrameworkUtils.parseDictDataLabel("lic_ne_add", ne.toString());
//                                    }
//                                }
//                            }
//                        }
//                        neLabels.add(label);
//                    }
//                    String neListStr = StrUtil.join("_", neLabels);
//
//                    licenseVO.setNeListStr(neListStr);
//                    licenseVO.setActivationCode(licenseDetailVO.getActivationCode());
//                    results.add(licenseVO);
//                }
//            }
//
//        }
        // 导出 Excel
        ExcelUtils.writeSelected(response, "", pageReqVO.getSheetName(), LicensePageRespVO.class,
                TranslateUtils.translate(voList), pageReqVO.getIncludeFields());
    }

    @GetMapping("/sn-unique")
    @Operation(summary = "校验License的sn是否唯一")
    public CommonResult<Boolean> validateLicenseSnUnique(@RequestParam(value = "sn", required = false) String sn, @RequestParam(value = "id", required = false) Long id) {
        Boolean isExists = licenseService.validateLicenseSnUnique(sn, id);
        return success(isExists);
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入License模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<LicenseImportExcelVO> list = Arrays.asList(
                LicenseImportExcelVO.builder()
                        .customerName("测试客户")
                        .projectName("测试项目")
                        .applicationTime(LocalDate.of(2025, 2, 10))
                        .serialNo("20002000")
                        .expiryDateExt("2026/5/1").neListStr("AMF+IMS")
                        .operatingSystem(1)
                        .contractCode("0")
                        .businessStatus(1)
                        .status(1)
                        .businessOwner(143L)
                        .technicalOwnerA(143L)
                        .technicalOwnerB(143L)
                        .build(),
                LicenseImportExcelVO.builder()
                        .customerName("测试客户2")
                        .projectName("测试项目2")
                        .applicationTime(LocalDate.of(2025, 2, 10))
                        .serialNo("20002000")
                        .expiryDateExt("2028/5/1").neListStr("AMF")
                        .operatingSystem(1)
                        .contractCode("0")
                        .businessStatus(1)
                        .status(1)
                        .businessOwner(143L)
                        .technicalOwnerA(143L)
                        .technicalOwnerB(143L)
                        .build()
        );
        // 输出
        ExcelUtils.write(response, "License导入模板.xlsx", "License列表", LicenseImportExcelVO.class, list);
    }

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

    @PostMapping("/code-import")
    @Operation(summary = "导入License的激活码")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    @PreAuthorize("@ss.hasPermission('license:license:import')")
    public CommonResult<ImportRespVO> importCodeExcel(@RequestParam("file") MultipartFile file,
                                                      @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<LicenseCodeImportExcelVO> list = ExcelUtils.read(file, LicenseCodeImportExcelVO.class);
        return success(licenseService.importCodeList(list, updateSupport));
    }

    @PutMapping("/update-detail")
    @Operation(summary = "更新License明细")
    @PreAuthorize("@ss.hasPermission('license:license:update')")
    public CommonResult<Boolean> updateDetailById(@Valid @RequestBody LicenseDetailVO updateReqVO) {
        licenseService.updateDetailById(updateReqVO);
        return success(true);
    }

    @Operation(summary = "下载")
    @GetMapping("/download")
    @Parameter(name = "tableId", description = "id", required = true, example = "1024")
    public void download(@RequestParam("id") Long id,
                         HttpServletResponse response) {
        licenseService.download(response, id);
    }
}