package com.jianshui.system.service.impl;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import com.jianshui.common.constant.Constants;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.redis.RedisCache;
import com.jianshui.common.exception.jianshui.JianshuiNoServiceException;
import com.jianshui.common.exception.jianshui.JianshuiServiceExpireException;
import com.jianshui.common.exception.jianshui.JianshuiServiceNoSurplusException;
import com.jianshui.common.utils.DateUtils;
import com.jianshui.common.utils.MessageUtils;
import com.jianshui.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jianshui.system.mapper.ServiceManageMapper;
import com.jianshui.system.domain.ServiceManage;
import com.jianshui.system.service.IServiceManageService;

import static com.jianshui.common.constant.Constants.SERVICE_MANAGE;

/**
 * 服务管理Service业务层处理
 *
 * @author Gong Quanlin
 * @date 2022-03-27
 */
@Service
public class ServiceManageServiceImpl implements IServiceManageService {
    @Autowired
    private ServiceManageMapper serviceManageMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询服务管理
     *
     * @param id 服务管理主键
     * @return 服务管理
     */
    @Override
    public ServiceManage selectServiceManageById(Long id) {
        return serviceManageMapper.selectServiceManageById(id);
    }

    /**
     * 查询服务管理列表
     *
     * @param serviceManage 服务管理
     * @return 服务管理
     */
    @Override
    public List<ServiceManage> selectServiceManageList(ServiceManage serviceManage) {
        return serviceManageMapper.selectServiceManageList(serviceManage);
    }

    /**
     * 新增服务管理
     *
     * @param serviceManage 服务管理
     * @return 结果
     */
    @Override
    public int insertServiceManage(ServiceManage serviceManage) {
        serviceManage.setCreateTime(DateUtils.getNowDate());
        int res = serviceManageMapper.insertServiceManage(serviceManage);
        reloadCache();
        return res;
    }

    /**
     * 修改服务管理
     *
     * @param serviceManage 服务管理
     * @return 结果
     */
    @Override
    public int updateServiceManage(ServiceManage serviceManage) {
        serviceManage.setUpdateTime(DateUtils.getNowDate());
        int res = serviceManageMapper.updateServiceManage(serviceManage);
        reloadCache();
        return res;
    }

    /**
     * 批量删除服务管理
     *
     * @param ids 需要删除的服务管理主键
     * @return 结果
     */
    @Override
    public int deleteServiceManageByIds(Long[] ids) {
        int res = serviceManageMapper.deleteServiceManageByIds(ids);
        reloadCache();
        return res;
    }

    /**
     * 删除服务管理信息
     *
     * @param id 服务管理主键
     * @return 结果
     */
    @Override
    public int deleteServiceManageById(Long id) {
        int res = serviceManageMapper.deleteServiceManageById(id);
        reloadCache();
        return res;
    }

    /**
     * 取servicemanager
     * @param serviceName
     * @param companyid
     * @return
     */
    @Override
    public ServiceManage selectServiceManageByCompanyIdAndServiceKey(String serviceName, Long companyid) {
        ServiceManage serviceManage = redisCache.getCacheObject(getCacheKey(serviceName, companyid));
        if (serviceManage != null) {
            return serviceManage;
        }

        serviceManage = serviceManageMapper.selectServiceManageByCompanyIdAndServiceKey(companyid, serviceName);
        if (serviceManage != null) {
            redisCache.setCacheObject(getCacheKey(serviceManage.getServiceKey(), serviceManage.getCompanyId()), serviceManage);
        }
        return serviceManage;
    }

    /**
     * 重新加载
     */
    private void reloadCache() {
        clearCache();
        loadCache();
    }

    /**
     * 剩余次数减一
     *
     * @param config
     */
    private void subOneSurplus(ServiceManage config) {
        config.setSurplus(config.getSurplus() - 1);
        // 更新记录
        serviceManageMapper.updateSurplus(config);
        setCache(config);
    }

    /**
     * 清空缓存
     */
    private void clearCache() {
        Collection<String> keys = redisCache.keys(SERVICE_MANAGE + "*");
        redisCache.deleteObject(keys);
    }

    // 设置缓存
    private void setCache(ServiceManage config) {
        redisCache.setCacheObject(getCacheKey(config.getServiceKey(), config.getCompanyId()), config);
    }

    /**
     * 加载缓存
     */
    private void loadCache() {
        List<ServiceManage> configsList = serviceManageMapper.selectServiceManageList(new ServiceManage());
        for (ServiceManage config : configsList) {
            redisCache.setCacheObject(getCacheKey(config.getServiceKey(), config.getCompanyId()), config);
        }
    }

    private String getCacheKey(String serviceName, Long companyid) {
        return SERVICE_MANAGE + serviceName + "-" + Long.toString(companyid);
    }



    /**
     * 获取服务商对应的信息
     *
     * @param serviceKey
     * @param companyid
     * @return
     */
    @Override
    public String getCompanyServiceSupplier(String serviceKey, Long companyid) throws Exception {
        ServiceManage serviceManage = selectServiceManageByCompanyIdAndServiceKey(serviceKey, companyid);
        if (serviceManage == null) {
            throw new JianshuiNoServiceException("此销方未配置应用服务", serviceKey, companyid);
        }
        return serviceManage.getServiceSupplierKey() + "_" + serviceKey;
    }

    /**
     * 对指定服务进行消费
     *
     * @param serviceKey
     * @param companyid
     * @return
     */
    @Override
    public AjaxResult companyConsume(String serviceKey, Long companyid) {
        ServiceManage serviceManage = selectServiceManageByCompanyIdAndServiceKey(serviceKey, companyid);
        if (serviceManage == null) {
            throw new JianshuiNoServiceException("此销方未配置应用服务", serviceKey, companyid);
        }

        // 处理扣费逻辑
        // 如果过期时间不为Null
        Date expireTime = serviceManage.getExpireTime();
        Date now = DateUtils.getNowDate();

        // 如果过期了
        if (expireTime != null) {
            if (expireTime.getTime() < now.getTime()) {
                throw new JianshuiServiceExpireException("服务已过期", serviceKey, companyid);
            }
        }

        // 免费
        if (StringUtils.equals("0", serviceManage.getServiceMode())) {
            // 调用次数 -1
            subOneSurplus(serviceManage);
            return AjaxResult.success("消费成功");
        }

        // 预付费
        if (StringUtils.equals("1", serviceManage.getServiceMode())) {
            // 调用次数 -1
            if (serviceManage.getSurplus() <= 0) {
                throw new JianshuiServiceNoSurplusException("服务次数不足", serviceKey, companyid);
            }
            subOneSurplus(serviceManage);
            return AjaxResult.success("消费成功");
        }

        // 定期结算
        if (StringUtils.equals("2", serviceManage.getServiceMode())) {
            subOneSurplus(serviceManage);
            return AjaxResult.success("消费成功");
        }

        return AjaxResult.error("未知的消费模式");

    }

    /**
     * 获得入口请求适配器
     *
     * @param serviceKey
     * @param companyid
     * @return
     * @throws Exception
     */
    public String getRequestAdapterKey(String serviceKey, Long companyid) throws Exception {
        ServiceManage serviceManage = selectServiceManageByCompanyIdAndServiceKey(serviceKey, companyid);
        if (serviceManage == null) {
            throw new JianshuiNoServiceException("此销方未配置应用服务", serviceKey, companyid);
        }

        return serviceManage.getRequestMessageKey() + "_" + serviceKey + "_request_adapter";
    }


    /**
     * 获得出口请求适配器
     *
     * @param serviceKey
     * @param companyid
     * @return
     * @throws Exception
     */
    public String getResponseAdapterKey(String serviceKey, Long companyid) throws Exception {
        ServiceManage serviceManage = selectServiceManageByCompanyIdAndServiceKey(serviceKey, companyid);
        if (serviceManage == null) {
            throw new JianshuiNoServiceException("此销方未配置应用服务", serviceKey, companyid);
        }

        return serviceManage.getResponseMessageKey() + "_" + serviceKey + "_response_adapter";
    }





}
