package com.qmth.teachcloud.exchange.common.service.impl;

import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.teachcloud.exchange.common.config.DictionaryConfig;
import com.qmth.teachcloud.exchange.common.contant.SpringContextHolder;
import com.qmth.teachcloud.exchange.common.contant.SystemConstant;
import com.qmth.teachcloud.exchange.common.entity.BasicSchool;
import com.qmth.teachcloud.exchange.common.entity.TSAuth;
import com.qmth.teachcloud.exchange.common.enums.AuthEnum;
import com.qmth.teachcloud.exchange.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.exchange.common.enums.UploadFileEnum;
import com.qmth.teachcloud.exchange.common.service.AuthInfoService;
import com.qmth.teachcloud.exchange.common.service.BasicSchoolService;
import com.qmth.teachcloud.exchange.common.service.CommonCacheService;
import com.qmth.teachcloud.exchange.common.service.TSAuthService;
import com.qmth.teachcloud.exchange.common.util.FileStoreUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
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.io.File;
import java.io.FileInputStream;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Description: 授权信息service
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2022/5/17
 */
@Service
public class AuthInfoServiceImpl implements AuthInfoService {
    private final static Logger log = LoggerFactory.getLogger(AuthInfoServiceImpl.class);

    @Resource
    SolarProperties solarProperties;

    @Resource
    SolarService solarService;

    @Resource
    TSAuthService tsAuthService;

    @Resource
    BasicSchoolService basicSchoolService;

    @Resource
    FileStoreUtil fileStoreUtil;

    @Resource
    DictionaryConfig dictionaryConfig;

    @Resource
    CommonCacheService commonCacheService;

    /**
     * 授权信息初始化
     *
     * @return
     */
    @Override
    public AppInfo appInfoInit() {
        AuthInfoService authInfoService = SpringContextHolder.getBean(AuthInfoService.class);
        AppInfo appInfo = null;
        try {
            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(), "")) {//在线激活
                    authInfoService.saveAuthInfo(appInfo, AuthEnum.ON_LINE, null);
                } else if (Objects.nonNull(solarProperties.getLicense())
                        && !Objects.equals(solarProperties.getLicense().trim(), "")) {//离线激活
                    authInfoService.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());
                        authInfoService.saveAuthInfo(appInfo, AuthEnum.OFF_LINE, t.getFile());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return appInfo;
    }

    /**
     * app是否过期
     *
     * @param code
     * @return
     */
    @Override
    public void appHasExpired(String code) {
        BasicSchool basicSchool = commonCacheService.schoolCache(code);
        if ((Objects.nonNull(basicSchool) && Objects.nonNull(basicSchool.getEnable()) && !basicSchool.getEnable())
                || (Objects.isNull(solarService.getAppInfo()) || solarService.getAppInfo().getControl().hasExpired())
                || (Objects.isNull(solarService.getAppControl()) || solarService.getAppControl().hasExpired())) {
            throw ExceptionResultEnum.AUTH_INFO_ERROR.exception();
        }
    }

    /**
     * 离线激活
     *
     * @param licenseData
     */
    @Override
    public void updateLicense(byte[] licenseData) throws Exception {
        AppInfo appInfo = solarService.update(licenseData);
        if (Objects.isNull(appInfo)) {
            throw ExceptionResultEnum.ERROR.exception("激活失败");
        }
        AuthInfoService authInfoService = SpringContextHolder.getBean(AuthInfoService.class);
        authInfoService.saveAuthInfo(appInfo, AuthEnum.OFF_LINE, licenseData);
    }

    /**
     * 查询授权信息
     *
     * @return
     */
    @Override
    public Long selectAuthInfo() {
        Long expireTime = null;
        AppInfo appInfo = solarService.getAppInfo();
        if (Objects.nonNull(appInfo) && Objects.nonNull(appInfo.getControl())) {
            expireTime = Objects.nonNull(appInfo.getControl().getExpireTime()) ? appInfo.getControl().getExpireTime() : -1;
        }
        return expireTime;
    }

    /**
     * 保存鉴权信息
     *
     * @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;
        if (!CollectionUtils.isEmpty(orgInfoList)) {
            tsAuthList = new ArrayList<>();
            orgCodesMap = new HashMap<>();
            basicSchoolSet = new HashSet<>();
        }

        LocalDateTime nowTime = LocalDateTime.now();
        StringJoiner stringJoiner = new StringJoiner("");
        stringJoiner.add(UploadFileEnum.FILE.name().toLowerCase()).add(File.separator)
                .add(String.valueOf(nowTime.getYear())).add(File.separator)
                .add(String.format("%02d", nowTime.getMonthValue())).add(File.separator)
                .add(String.format("%02d", nowTime.getDayOfMonth())).add(File.separator);

        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, appInfo.getControl().getExpireTime()));
                } else {
                    tsAuthList.add(new TSAuth(o.getId(), file, authEnum, appInfo.getControl().getExpireTime()));
                }
            } else {
                tsAuthList.add(new TSAuth(o.getId(), solarProperties.getAccessKey(), solarProperties.getAccessSecret(), authEnum, appInfo.getControl().getExpireTime()));
            }

            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"))) {
//                    File fileTemp = null;
//                    String dirName = null;
//                    try {
////                        File fileNew = new File("/Users/king/Downloads/spring.jpg");
//                        fileTemp = File.createTempFile("temp", ".jpg");
//                        SystemConstant.base64ToImage(o.getLogo(), fileTemp.getPath());
////                        FileUtils.copyInputStreamToFile(new FileInputStream(fileNew), fileTemp);
//
//                        dirName = stringJoiner.toString() + NanoIdUtils.randomNanoId() + "." + FilenameUtils.getExtension(fileTemp.getPath());
//                        fileStoreUtil.ossUpload(dirName, fileTemp, DigestUtils.md5Hex(new FileInputStream(fileTemp)), UploadFileEnum.FILE.getFssType());
//                    } catch (Exception e) {
//                        log.error(SystemConstant.LOG_ERROR, e);
//                    } finally {
//                        if (Objects.nonNull(fileTemp)) {
//                            fileTemp.delete();
//                        }
//                        if (Objects.nonNull(dirName)) {
//                            basicSchool.setLogo(dictionaryConfig.fssPublicDomain().getServer() + File.separator + dirName);
//                        }
//                    }
//                } 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();
            }

            AuthInfoService authInfoService = SpringContextHolder.getBean(AuthInfoService.class);
            authInfoService.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);
                }
                commonCacheService.schoolCache(b.getId());
                commonCacheService.schoolCache(b.getCode());
                commonCacheService.removeSysSetting(b.getId());
                commonCacheService.getSysSetting(b.getId());
            }
            basicSchoolService.saveOrUpdateBatch(basicSchoolList);
        }
    }
}
