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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
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.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.dict.core.DictFrameworkUtils;
import org.agt.framework.excel.core.util.ExcelUtils;
import org.agt.framework.translate.core.TranslateUtils;
import org.agt.module.license.controller.admin.license.vo.LicenseDetailVO;
import org.agt.module.license.controller.admin.license.vo.LicensePageReqVO;
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 java.io.IOException;
import java.util.ArrayList;
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:create')")
    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:apply')")
    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<LicenseRespVO>> getLicensePage(@Valid LicensePageReqVO pageReqVO) {
        PageResult<LicenseRespVO> pageResult = licenseService.getLicensePage(pageReqVO);
        return success(pageResult);
    }

    @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 {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<LicenseRespVO> voList = licenseService.getLicensePage(pageReqVO).getList();

        List<LicenseRespVO> results = new ArrayList<>();
        for (LicenseRespVO license : voList) {
            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.write(response, "License.xls", "数据", LicenseRespVO.class,
                TranslateUtils.translate(results));
    }

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