package com.zt.plat.module.qms.resource.clientManage.controller.admin;

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.clientManage.controller.vo.VersionManagementPageReqVO;
import com.zt.plat.module.qms.resource.clientManage.controller.vo.VersionManagementRespVO;
import com.zt.plat.module.qms.resource.clientManage.controller.vo.VersionManagementSaveReqVO;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import com.zt.plat.framework.business.interceptor.BusinessControllerMarker;
import com.zt.plat.framework.business.annotation.FileUploadController;
import com.zt.plat.framework.business.controller.AbstractFileUploadController;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.zt.plat.framework.common.pojo.vo.BatchDeleteReqVO;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;

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

import com.zt.plat.framework.excel.core.util.ExcelUtils;
import com.alibaba.fastjson.JSONObject;
import com.zt.plat.framework.apilog.core.annotation.ApiAccessLog;
import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.*;

import com.zt.plat.module.qms.resource.clientManage.dal.dataobject.VersionManagementDO;
import com.zt.plat.module.qms.resource.clientManage.service.VersionManagementService;

@Tag(name = "管理后台 - 客户端版本管理")
@RestController
@RequestMapping("/qms/version-management")
@Validated
@FileUploadController(source = "qms.versionmanagement", codeKey = "data.fileUploadBusinessCode")
@DeptDataPermissionIgnore(enable = "true")
public class VersionManagementController extends AbstractFileUploadController implements BusinessControllerMarker{

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

    @Resource
    private VersionManagementService systemVersionManagementService;
    @Resource private BusinessFileService businessFileService;
    
    @Resource
    private FileApi fileApi;

    @PostMapping("/create")
    @Operation(summary = "创建客户端版本管理")
//    @PreAuthorize("@ss.hasPermission('qms:version-management:create')")
    public CommonResult<VersionManagementRespVO> createSystemVersionManagement(@Valid @RequestBody VersionManagementSaveReqVO createReqVO) {
        return success(systemVersionManagementService.createVersionManagement(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新客户端版本管理")
//    @PreAuthorize("@ss.hasPermission('qms:version-management:update')")
    public CommonResult<VersionManagementRespVO> updateSystemVersionManagement(@Valid @RequestBody VersionManagementSaveReqVO updateReqVO) {
        systemVersionManagementService.updateVersionManagement(updateReqVO);
        return success(BeanUtils.toBean(updateReqVO, VersionManagementRespVO.class));
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除客户端版本管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('qms:version-management:delete')")
    public CommonResult<Boolean> deleteSystemVersionManagement(@RequestParam("id") Long id) {
        systemVersionManagementService.deleteVersionManagement(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除客户端版本管理")
    @PreAuthorize("@ss.hasPermission('qms:version-management:delete')")
    public CommonResult<Boolean> deleteSystemVersionManagementList(@RequestBody BatchDeleteReqVO req) {
        systemVersionManagementService.deleteSystemVersionManagementListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得客户端版本管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('qms:version-management:query')")
    public CommonResult<VersionManagementRespVO> getSystemVersionManagement(@RequestParam("id") Long id) {
        VersionManagementDO systemVersionManagement = systemVersionManagementService.getVersionManagement(id);
        VersionManagementRespVO vo = BeanUtils.toBean(systemVersionManagement, VersionManagementRespVO.class);
        vo.setBusinessFileRet(businessFileService.getBusinessFileList(id));
        return success(vo);
    }

    @GetMapping("/page")
    @Operation(summary = "获得客户端版本管理分页")
//    @PreAuthorize("@ss.hasPermission('qms:version-management:query')")
    public CommonResult<PageResult<VersionManagementRespVO>> getSystemVersionManagementPage(@Valid VersionManagementPageReqVO pageReqVO) {
        PageResult<VersionManagementDO> pageResult = systemVersionManagementService.getVersionManagementPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, VersionManagementRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出客户端版本管理 Excel")
    @PreAuthorize("@ss.hasPermission('qms:version-management:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSystemVersionManagementExcel(@Valid VersionManagementPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<VersionManagementDO> list = systemVersionManagementService.getVersionManagementPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "客户端版本管理.xls", "数据", VersionManagementRespVO.class,
                        BeanUtils.toBean(list, VersionManagementRespVO.class));
    }


    @GetMapping("/checkUpdate")
    @Operation(summary = "根据更新平台和安装包类型获取最新客户端版本管理信息")
    public Object checkUpdate(@Valid VersionManagementPageReqVO pageReqVO) {

        if (pageReqVO.getApplicationCode() == null ) {
            return CommonResult.error(400, "客户端编号不能为空");
        }
        if (pageReqVO.getUpdatePlatform() == null ) {
            return CommonResult.error(400, "更新平台不能为空");
        }
        PageResult<VersionManagementDO> pageResult = systemVersionManagementService.getList(pageReqVO);
        if ("pc".equals(pageReqVO.getUpdatePlatform())) {
            String version = "0.0.0";
            String minVersion = "0.0.0";
            String checksumSha1 = "";
            String url = "";
            String log = "";
            if (pageResult.getList().size() != 0) {
                VersionManagementDO versionManagementDO = pageResult.getList().get(0);
                //处理文件下载url
                Long fileId = Long.parseLong(versionManagementDO.getDownloadId());
                CommonResult<FileRespDTO> fileRet = fileApi.getFileInfo(fileId);
                FileRespDTO file = fileRet.getData();
                if(fileRet.isSuccess() && file != null) {
                	versionManagementDO.setDownloadUrl(file.getUrl());
                }
                
                version = versionManagementDO.getCurrentVersion();
                minVersion = versionManagementDO.getMinimumVersion();
                url = versionManagementDO.getDownloadUrl();
                log = versionManagementDO.getUpdateContent();
                checksumSha1 = versionManagementDO.getFileEncryptAlgorithm();
            }
            
            JSONObject resultJson = new JSONObject();
            resultJson.put("version", version);
            resultJson.put("url", url);
            resultJson.put("changelog", log);
            JSONObject mandatory = new JSONObject();
            mandatory.put("value", true);
            mandatory.put("minVersion", minVersion);
            mandatory.put("mode", 2);
            resultJson.put("mandatory", mandatory);
            JSONObject checksum = new JSONObject();
            checksum.put("hashingAlgorithm", "SHA1");
            checksum.put("value", checksumSha1);
            resultJson.put("checksum", checksum);
            return resultJson;
		}
        
        if (pageResult.getList().size() == 0) {
            return CommonResult.error(400, "没有可更新版本");
        }
        VersionManagementDO versionManagementDO = pageResult.getList().get(0);
        //处理文件下载url
        Long fileId = Long.parseLong(versionManagementDO.getDownloadId());
        CommonResult<FileRespDTO> fileRet = fileApi.getFileInfo(fileId);
        FileRespDTO file = fileRet.getData();
        if(fileRet.isSuccess() && file != null) {
        	versionManagementDO.setDownloadUrl(file.getUrl());
        }
        
        return success(BeanUtils.toBean(versionManagementDO, VersionManagementRespVO.class));
    }

    @GetMapping("/executePublish")
    CommonResult<String> executePublish(@RequestParam("id") Long id) {
        systemVersionManagementService.executePublish(id);
        return success("发布成功");
    }
}