package com.qmth.sop.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.core.solar.config.SolarProperties;
import com.qmth.boot.core.solar.model.AppInfo;
import com.qmth.boot.core.solar.model.OrgInfo;
import com.qmth.boot.core.solar.service.SolarService;
import com.qmth.sop.business.cache.CommonCacheService;
import com.qmth.sop.business.entity.BasicSchool;
import com.qmth.sop.business.entity.TSAuth;
import com.qmth.sop.business.mapper.TSAuthMapper;
import com.qmth.sop.business.service.BasicSchoolService;
import com.qmth.sop.business.service.TSAuthService;
import com.qmth.sop.common.contant.SpringContextHolder;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.AuthEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 激活授权配置表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2023-08-07
 */
@Service
public class TSAuthServiceImpl extends ServiceImpl<TSAuthMapper, TSAuth> implements TSAuthService {
    private final static Logger log = LoggerFactory.getLogger(TSAuthServiceImpl.class);

    @Resource
    SolarProperties solarProperties;

    @Resource
    SolarService solarService;

    @Resource
    CommonCacheService commonCacheService;

    @Resource
    BasicSchoolService basicSchoolService;

    /**
     * 授权信息初始化
     *
     * @return
     */
    @Override
    public AppInfo appInfoInit() {
        AppInfo appInfo = null;
        try {
            TSAuthService tsAuthService = SpringContextHolder.getBean(TSAuthService.class);
            appInfo = solarService.getAppInfo();
            if (Objects.nonNull(appInfo) && Objects.nonNull(solarProperties)) {
                if (Objects.nonNull(solarProperties.getAccessKey())
                        && !Objects.equals(solarProperties.getAccessKey().trim(), "")
                        && Objects.nonNull(solarProperties.getAccessSecret())
                        && !Objects.equals(solarProperties.getAccessSecret().trim(), "")) {//在线激活
                    tsAuthService.saveAuthInfo(appInfo, AuthEnum.ON_LINE, null);
                } else if (Objects.nonNull(solarProperties.getLicense())
                        && !Objects.equals(solarProperties.getLicense().trim(), "")) {//离线激活
                    tsAuthService.saveAuthInfo(appInfo, AuthEnum.OFF_LINE, null);
                }
            } else {
                QueryWrapper<TSAuth> tsAuthQueryWrapper = new QueryWrapper<>();
                tsAuthQueryWrapper.lambda().isNotNull(TSAuth::getFile);
                List<TSAuth> tsAuthList = tsAuthService.list(tsAuthQueryWrapper);
                if (!CollectionUtils.isEmpty(tsAuthList)) {
                    for (TSAuth t : tsAuthList) {
                        appInfo = solarService.update(t.getFile());
                        tsAuthService.saveAuthInfo(appInfo, AuthEnum.OFF_LINE, t.getFile());
                    }
                }
            }
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
        }
        return appInfo;
    }

    /**
     * 保存鉴权信息
     *
     * @param appInfo
     * @param authEnum
     * @param file
     * @throws Exception
     */
    @Override
    @Transactional
    public void saveAuthInfo(AppInfo appInfo, AuthEnum authEnum, byte[] file) throws Exception {
        List<OrgInfo> orgInfoList = solarService.getOrgList();
        List<TSAuth> tsAuthList = null;
        Map<String, String> orgCodesMap = null;
        Set<BasicSchool> basicSchoolSet = null;
        TSAuthService tsAuthService = SpringContextHolder.getBean(TSAuthService.class);
        if (!CollectionUtils.isEmpty(orgInfoList)) {
            tsAuthList = new ArrayList<>();
            basicSchoolSet = new HashSet<>();
            orgCodesMap = new HashMap<>();
        }

        Long expireTime = null;
        if (Objects.nonNull(appInfo) && Objects.nonNull(appInfo.getControl())) {
            expireTime = Objects.nonNull(appInfo.getControl().getExpireTime()) ? appInfo.getControl().getExpireTime() : -1;
        }
        for (OrgInfo o : orgInfoList) {
            orgCodesMap.put(o.getCode(), o.getCode());
            if (authEnum == AuthEnum.OFF_LINE) {
                if (Objects.isNull(file)) {
                    tsAuthList.add(new TSAuth(o.getId(), solarProperties.getLicense(), authEnum, expireTime));
                } else {
                    tsAuthList.add(new TSAuth(o.getId(), file, authEnum, expireTime));
                }
            } else {
                tsAuthList.add(new TSAuth(o.getId(), solarProperties.getAccessKey(), solarProperties.getAccessSecret(), authEnum, expireTime));
            }
            QueryWrapper<BasicSchool> basicSchoolQueryWrapper = new QueryWrapper<>();
            basicSchoolQueryWrapper.lambda().eq(BasicSchool::getCode, o.getCode());
            BasicSchool basicSchool = basicSchoolService.getOne(basicSchoolQueryWrapper);
            if (Objects.isNull(basicSchool)) {//不存在则创建学校
                basicSchool = new BasicSchool(o.getId(), o.getCode(), o.getName(), o.getAccessKey(), o.getAccessSecret());
                if (Objects.nonNull(o.getLogo()) && (!o.getLogo().startsWith("https:") || !o.getLogo().startsWith("http"))) {
                    basicSchool.setLogo("data:image/png;base64," + o.getLogo());
                } else {
                    basicSchool.setLogo(o.getLogoUrl());
                }
                basicSchoolSet.add(basicSchool);
            } else {
                basicSchool.setAccessKey(o.getAccessKey());
                basicSchool.setAccessSecret(o.getAccessSecret());
                basicSchool.setLogo(Objects.nonNull(o.getLogoUrl()) ? o.getLogoUrl() : basicSchool.getLogo());
                basicSchoolSet.add(basicSchool);
            }
        }

        if (!CollectionUtils.isEmpty(tsAuthList) && !CollectionUtils.isEmpty(orgCodesMap)) {
            tsAuthService.remove(new QueryWrapper<TSAuth>().lambda().ge(TSAuth::getId, 0L));
            tsAuthService.saveOrUpdateBatch(tsAuthList);

            if (!CollectionUtils.isEmpty(basicSchoolSet)) {
                basicSchoolService.saveOrUpdateBatch(basicSchoolSet);
                commonCacheService.removeSchoolIdCache();
                commonCacheService.removeSchoolCodeCache();
            }

            tsAuthService.updateSchoolEnable(orgCodesMap);
        }
    }

    /**
     * 更新学校启用/禁用
     *
     * @param orgCodesMap
     */
    @Override
    public void updateSchoolEnable(Map<String, String> orgCodesMap) {
        List<BasicSchool> basicSchoolList = basicSchoolService.list();
        if (!CollectionUtils.isEmpty(basicSchoolList)) {
            for (BasicSchool b : basicSchoolList) {
                if (orgCodesMap.containsKey(b.getCode())) {
                    b.setEnable(true);
                } else {
                    b.setEnable(false);
                }
            }
            basicSchoolService.saveOrUpdateBatch(basicSchoolList);
            commonCacheService.removeSchoolIdCache();
            commonCacheService.removeSchoolCodeCache();
        }
    }

    /**
     * 查询最后激活信息
     *
     * @param authEnum
     * @return
     */
    @Override
    public TSAuth lastAuthInfo(AuthEnum authEnum) {
        return this.baseMapper.lastAuthInfo(Objects.nonNull(authEnum) ? authEnum.name() : null);
    }
}
