package com.sqx.modules.common.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.RedisUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.common.dao.CommonInfoDao;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.course.service.CourseService;
import com.sqx.modules.oss.cloud.OSSFactory;
import com.sqx.modules.oss.entity.SysOssEntity;
import com.sqx.modules.oss.service.SysOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author fang
 * @date 2020/7/8
 */
@CacheConfig(cacheNames = "common")
@Service
public class CommonInfoServiceImpl extends ServiceImpl<CommonInfoDao, CommonInfo> implements CommonInfoService {

    @Autowired
    private CommonInfoDao commonInfoDao;
    @Autowired
    private CourseService courseService;

    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private SysOssService sysOssService;
    @Autowired
    private RedisUtils redisUtils;


    @CacheEvict(key = "#commonInfo.id")
    @Override
    public Result update(CommonInfo commonInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        commonInfo.setCreateAt(sdf.format(now));
        if (commonInfo.getType() == 820) {
            Result result = courseService.setDyNotifyUrl(commonInfo.getValue());
            String code = String.valueOf(result.get("code"));
            if (!"0".equals(code)) {
                return result;
            }
        }
        commonInfoDao.updateById(commonInfo);
        cleanAppKv();
        //cleanAppOssKv(commonInfo.getType());
        return Result.success();
    }

    @Override
    public CommonInfo findOne(int type) {
        return commonInfoDao.findOne(type);
    }

    @CacheEvict(key = "#id")
    @Override
    public Result delete(long id) {
        CommonInfo commonInfo = commonInfoDao.selectById(id);
        if(commonInfo != null){
            //cleanAppOssKv(commonInfo.getType());
        }
        commonInfoDao.deleteById(id);
        cleanAppKv();
        return Result.success();
    }

    @CacheEvict(key = "#commonInfo.id")
    @Override
    public Result updateBody(CommonInfo commonInfo) {
        commonInfoDao.updateById(commonInfo);

        cleanAppKv();
        //cleanAppOssKv(commonInfo.getType());
        return Result.success();
    }

    @Override
    public Result findByType(Integer type) {
        return Result.success().put("data", commonInfoDao.findOne(type));
    }

    @Override
    public Result findByTypeAndCondition(String condition) {
        return Result.success().put("data", commonInfoDao.findByCondition(condition));
    }

    @Override
    @Cacheable("commonInfoAppKv")
    public Map<Integer, String> findAppKv() {
        List<CommonInfo> list = commonInfoDao.selectList(Wrappers.<CommonInfo>lambdaQuery()
                .eq(CommonInfo::getIsAppUse, 1)
                .orderByAsc(CommonInfo::getType)
                .orderByAsc(CommonInfo::getId));
        if (CollUtil.isEmpty(list)) {
            return new HashMap<>(0);
        }
        Map<Integer, String> data = list.stream().collect(Collectors.toMap(CommonInfo::getType, CommonInfo::getValue));
        //String url = putOss();
        // 移除 条款、服务协议、隐私政策 这些长text字段，为减缓宽带消耗，放到oss中加载
        //data.put(154, url);
        //data.put(155, url);
        //data.put(246, url);
        return data;
    }

    @Override
    public void cleanAppKv() {
        cacheManager.getCache("commonInfoAppKv").clear();
    }

    private void cleanAppOssKv(Integer key) {
        if (ArrayUtil.contains(PUT_OSS_KEYS, key)) {
            redisUtils.delete(SYS_OSS_CONFIG_JSON_URL_KEY);
        }
    }

    private static final String SYS_OSS_CONFIG_JSON_URL_KEY = "SYS_OSS_CONFIG_JSON_URL";
    private static final Integer[] PUT_OSS_KEYS = {154, 155, 246};

    @Override
    public String putOss() {
        String url = redisUtils.get(SYS_OSS_CONFIG_JSON_URL_KEY);
        if (StrUtil.isNotBlank(url)) {
            return url;
        }
        List<CommonInfo> list = commonInfoDao.selectList(Wrappers.<CommonInfo>lambdaQuery()
                .eq(CommonInfo::getIsAppUse, 1)
                .in(CommonInfo::getType, PUT_OSS_KEYS));
        if (CollUtil.isEmpty(list)) {
            return "";
        }
        Map<Integer, String> data = list.stream().collect(Collectors.toMap(CommonInfo::getType, CommonInfo::getValue));
        String jsonStr = JSONUtil.toJsonStr(data);
        File file = FileUtil.createTempFile("hutool", ".json", null, true);
        FileUtil.writeUtf8String(jsonStr, file);
        //上传文件
        String suffix = FileUtil.extName(file);
        url = OSSFactory.build().uploadSuffix(FileUtil.readBytes(file), "." + suffix);
        file.delete();
        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(url);
        ossEntity.setCreateDate(new Date());
        sysOssService.save(ossEntity);
        redisUtils.set(SYS_OSS_CONFIG_JSON_URL_KEY, url);
        return url;
    }

}