package com.qmth.themis.admin.api;

import com.qmth.themis.business.bean.exam.VersionBean;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dto.response.TBOrgDownloadBean;
import com.qmth.themis.business.entity.TBClientVersion;
import com.qmth.themis.business.entity.TBOrg;
import com.qmth.themis.business.service.AuthInfoService;
import com.qmth.themis.business.service.TBClientVersionService;
import com.qmth.themis.business.service.ThemisCacheService;
import com.qmth.themis.common.enums.ExceptionResultEnum;
import com.qmth.themis.common.exception.BusinessException;
import com.qmth.themis.common.util.GsonUtil;
import com.qmth.themis.common.util.Result;
import com.qmth.themis.common.util.ResultUtil;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * @Description: 下载信息 前端控制器
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2023/2/8
 */
@Api(tags = "下载信息Controller")
@RestController
@RequestMapping(SystemConstant.PREFIX_URL_ADMIN)
public class DownloadController {

    @Resource
    ThemisCacheService themisCacheService;

    @Resource
    AuthInfoService authInfoService;

    @Resource
    TBClientVersionService tbClientVersionService;

    @ApiOperation(value = "根据机构代码查询下载安装包信息接口")
    @RequestMapping(value = "/download/package", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "机构信息", response = TBOrgDownloadBean.class)})
    public Result downloadPackage(@ApiParam(value = "机构code", required = true) @RequestParam String code) {
        Optional.ofNullable(code).orElseThrow(() -> new BusinessException(ExceptionResultEnum.ORG_CODE_IS_NULL));
        if (!Objects.equals(code.toUpperCase(), SystemConstant.ADMIN)) {
            TBOrg tbOrg = themisCacheService.addOrgCodeCache(code);
            Optional.ofNullable(tbOrg).orElseThrow(() -> new BusinessException(ExceptionResultEnum.ORG_NO));
            authInfoService.appHasExpired(code);

            TBOrgDownloadBean tbOrgDownloadBean = GsonUtil.fromJson(GsonUtil.toJson(tbOrg), TBOrgDownloadBean.class);
            TBClientVersion tbClientVersion = tbClientVersionService.getLastUploadClientVersion(tbOrg.getId());
            if (Objects.nonNull(tbClientVersion)) {
                VersionBean v = new VersionBean(tbClientVersion.getName(), tbClientVersion.getValue(), tbClientVersion.getUrl());
                tbOrgDownloadBean.setVersion(v);
                tbOrgDownloadBean.setPackagePath(v.getUrl());
            }
            return ResultUtil.ok(tbOrgDownloadBean);
        } else {
            throw new BusinessException("超级管理员无需下载");
        }
    }
}
