package com.izouma.nineth.service;

import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.config.Constants;
import com.izouma.nineth.config.SysConstants;
import com.izouma.nineth.domain.SysConfig;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.SysConfigRepo;
import com.izouma.nineth.service.pay.UniformPayConstants;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;

@Service
@AllArgsConstructor
public class SysConfigService {
    private SysConfigRepo sysConfigRepo;

    private final RedisTemplate<String, Object> redisTemplate;


    public Page<SysConfig> all(PageQuery pageQuery) {
        return sysConfigRepo.findAll(JpaUtils.toSpecification(pageQuery, SysConfig.class), JpaUtils.toPageRequest(pageQuery));
    }

    @Cacheable("SysConfigServiceGetBigDecimal")
    public BigDecimal getBigDecimal(String name) {
        return sysConfigRepo.findByName(name).map(sysConfig -> new BigDecimal(sysConfig.getValue()))
                .orElse(BigDecimal.ZERO);
    }

    @Cacheable("SysConfigServiceGetTime")
    public LocalTime getTime(String name) {
        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue)
                .orElseThrow(new BusinessException("配置不存在"));
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
        return LocalTime.from(dateTimeFormatter.parse(str));
    }

    @Cacheable("SysConfigServiceGetTime")
    public long getDateTime(String name) {
        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue)
                .orElseThrow(new BusinessException("配置不存在"));
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sf.parse(str).getTime();
        }catch (Exception e){
            throw  new BusinessException("检查【"+name+"】配置是否存在错误");
        }
    }


    @Cacheable("SysConfigServiceGetBoolean")
    public boolean getBoolean(String name) {
        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue)
                .orElseThrow(new BusinessException("配置不存在"));
        return str.equals("1");
    }

    @Cacheable("SysConfigServiceGetInt")
    public int getInt(String name) {
        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue)
                .orElseThrow(new BusinessException("配置不存在"));
        return Integer.parseInt(str);
    }

    @Cacheable("SysConfigServiceGetString")
    public String getString(String name) {
        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue)
                .orElseThrow(new BusinessException("配置不存在"));
        return str;
    }

    @Cacheable("SysConfigServiceGetString")
    public String getStringDefault(String name) {
        String str = sysConfigRepo.findByName(name).map(SysConfig::getValue).orElse("");
        return str;
    }

    @PostConstruct
    public void init() {
        if (!sysConfigRepo.findByName(SysConstants.GAS_FEE).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.GAS_FEE)
                    .desc("gas费")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("1")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.FOUR_ELEMENT_SWITCH).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.FOUR_ELEMENT_SWITCH)
                    .desc("银行卡实名认证四要素开关")
                    .type(SysConfig.ValueType.BOOLEAN)
                    .value("0")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.BINDING_BANK_CARD_SWITCH).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.BINDING_BANK_CARD_SWITCH)
                    .desc("汇付绑定银行卡开关")
                    .type(SysConfig.ValueType.BOOLEAN)
                    .value("0")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.DAYS_FOUR_ELEMENT_COUNT).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.DAYS_FOUR_ELEMENT_COUNT)
                    .desc("用户每天银行卡实名认证次数")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("3")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.DEFAULT_AVATAR).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.DEFAULT_AVATAR)
                    .desc("用户默认头像")
                    .type(SysConfig.ValueType.STRING)
                    .value(Constants.DEFAULT_AVATAR)
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.GIFT_GAS_FEE).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.GIFT_GAS_FEE)
                    .desc("转赠gas费")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("1")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.ENABLE_WX_PUB).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.ENABLE_WX_PUB)
                    .desc("使用公众号支付")
                    .type(SysConfig.ValueType.BOOLEAN)
                    .value("0")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.ENABLE_WX_LITE).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.ENABLE_WX_LITE)
                    .desc("使用小程序支付")
                    .type(SysConfig.ValueType.BOOLEAN)
                    .value("0")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.HOLD_DAYS).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.HOLD_DAYS)
                    .desc("持有满几天可销售")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("0")
                    .build());
        }

        Optional<SysConfig> payPlatformOptional = sysConfigRepo.findByName(SysConstants.PAY_PLATFORM);
        if (!payPlatformOptional.isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.PAY_PLATFORM)
                    .desc("默认的支付平台")
                    .type(SysConfig.ValueType.LIST)
                    .optionMap(JSONObject.toJSONString(payPlatformOptionMap()))
                    .value(UniformPayConstants.ADAPAY_PLATFORM)
                    .build());
        }else{
            //设置选项
            SysConfig payPlatformConfig = payPlatformOptional.get();
            payPlatformConfig.setType(SysConfig.ValueType.LIST);
            payPlatformConfig.setOptionMap(JSONObject.toJSONString(payPlatformOptionMap()));
            sysConfigRepo.save(payPlatformConfig);
        }

        //二手交易支付配置初始化
        Optional<SysConfig> secondHandPayPlatformOptional = sysConfigRepo.findByName(SysConstants.SECOND_HAND_PAY_PLATFORM);
        if (!secondHandPayPlatformOptional.isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.SECOND_HAND_PAY_PLATFORM)
                    .desc("二手交易的支付平台")
                    .type(SysConfig.ValueType.LIST)
                    .optionMap(JSONObject.toJSONString(payPlatformOptionMap()))
                    .value(UniformPayConstants.ADAPAY_PLATFORM)
                    .build());
        }else{
            //设置选项
            SysConfig payPlatformConfig = secondHandPayPlatformOptional.get();
            payPlatformConfig.setType(SysConfig.ValueType.LIST);
            payPlatformConfig.setOptionMap(JSONObject.toJSONString(payPlatformOptionMap()));
            sysConfigRepo.save(payPlatformConfig);
        }

        //二手交易支付配置初始化
        Optional<SysConfig> giftHandPayPlatformOptional = sysConfigRepo.findByName(SysConstants.GIFT_HAND_PAY_PLATFORM);
        if (!giftHandPayPlatformOptional.isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.GIFT_HAND_PAY_PLATFORM)
                    .desc("转赠交易的支付平台")
                    .type(SysConfig.ValueType.LIST)
                    .optionMap(JSONObject.toJSONString(payPlatformOptionMap()))
                    .value(UniformPayConstants.ADAPAY_PLATFORM)
                    .build());
        }else{
            //设置选项
            SysConfig payPlatformConfig = giftHandPayPlatformOptional.get();
            payPlatformConfig.setType(SysConfig.ValueType.LIST);
            payPlatformConfig.setOptionMap(JSONObject.toJSONString(payPlatformOptionMap()));
            sysConfigRepo.save(payPlatformConfig);
        }



        if (!sysConfigRepo.findByName(SysConstants.GIFT_PAY_SWITCH).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.GIFT_PAY_SWITCH)
                    .desc("转赠支付开关")
                    .type(SysConfig.ValueType.BOOLEAN)
                    .value("1")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.BLACK_USER_ID).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.BLACK_USER_ID)
                    .desc("默认的黑洞账户")
                    .type(SysConfig.ValueType.NUMBER)
                    .value(Constants.DEFAULT_BLACK_USER)
                    .build());
        }


        if (!sysConfigRepo.findByName(SysConstants.ASSET_SHELF_CHECK).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.ASSET_SHELF_CHECK)
                    .desc("二手交易藏品上架检查")
                    .type(SysConfig.ValueType.STRING)
                    .value("")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.TEST_NAMED_USER).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.TEST_NAMED_USER)
                    .desc("指定用户ID,多藏品逗号隔开")
                    .type(SysConfig.ValueType.STRING)
                    .value("")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.TEST_NAMED_COLLECTIONID).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.TEST_NAMED_COLLECTIONID)
                    .desc("指定藏品,多藏品逗号隔开")
                    .type(SysConfig.ValueType.STRING)
                    .value("")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.WX_MP_SWITCH).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.WX_MP_SWITCH)
                    .desc("微信公众号调用开关")
                    .type(SysConfig.ValueType.BOOLEAN)
                    .value("0")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.ORDER_EXPIRE_INTERVAL).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.ORDER_EXPIRE_INTERVAL)
                    .desc("订单失效时间间隔（分钟）")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("3")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.REGISTERED_NUMBER).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.REGISTERED_NUMBER)
                    .desc("同一个身份证可注册账号个数")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("1")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.REGISTERED_INTEGRAL).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.REGISTERED_INTEGRAL)
                    .desc("用户注册自动获得积分")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("0")
                    .build());
        }


        if (!sysConfigRepo.findByName(SysConstants.BANK_CARD_CAN_BE_BOUND).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.BANK_CARD_CAN_BE_BOUND)
                    .desc("同一个银行卡可以绑定的次数")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("1")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.LOCK_ORDER_LIMIT_NUMBER).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.LOCK_ORDER_LIMIT_NUMBER)
                    .desc("锁单上限次数")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("5")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.LOCK_ORDER_PUNISH_TIME).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.LOCK_ORDER_PUNISH_TIME)
                    .desc("超过锁单上限禁止购买时间(小时)")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("5")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.TESTER_USER_ID).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.TESTER_USER_ID)
                    .desc("测试人员ID")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("1")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.LOCK_ORDER_COUNT_INTERVAL).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.LOCK_ORDER_COUNT_INTERVAL)
                    .desc("统计锁单次数周期")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("24")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.RANKING_ACTIVITY_START_TIME).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.RANKING_ACTIVITY_START_TIME)
                    .desc("成交量排行榜活动开始时间")
                    .type(SysConfig.ValueType.DATETIME)
                    .value("2022-03-21 11:10:36")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.RANKING_ACTIVITY_END_TIME).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.RANKING_ACTIVITY_END_TIME)
                    .desc("成交量排行榜活动结束时间")
                    .type(SysConfig.ValueType.DATETIME)
                    .value("2022-05-24 20:10:36")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.ASSET_SHELF_PRICE_LIMIT).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.ASSET_SHELF_PRICE_LIMIT)
                    .desc("资产上架价格限制")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("50000")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.FALSE_DATA_PHONE_NUMBER).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.FALSE_DATA_PHONE_NUMBER)
                    .desc("邀请排行榜测试数据的手机号（多号用逗号隔开）")
                    .type(SysConfig.ValueType.STRING)
                    .value("0")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.FALSE_DATA).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.FALSE_DATA)
                    .desc("排行榜测试数据（与手机号对应）")
                    .type(SysConfig.ValueType.STRING)
                    .value("0")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.GRAPH_AUTHCODE_EXPIRATION_TIME).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.GRAPH_AUTHCODE_EXPIRATION_TIME)
                    .desc("图形验证码过期时间（秒）")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("120")
                    .build());
        }



        if (!sysConfigRepo.findByName(SysConstants.CONSUME_PHONE).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.CONSUME_PHONE)
                    .desc("活动消费排行榜需要补全数据的手机号（多号用逗号隔开）")
                    .type(SysConfig.ValueType.STRING)
                    .value("0")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.CONSUME_DATA).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.CONSUME_DATA)
                    .desc("活动消费排行榜需要补全的数据（与手机号对应）")
                    .type(SysConfig.ValueType.STRING)
                    .value("0")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.MEMBER_PREFIX).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.MEMBER_PREFIX)
                    .desc("钱包账户会员ID前缀（多个平台隔离）")
                    .type(SysConfig.ValueType.STRING)
                    .value("")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.WALLET_FREE_TIPS).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.WALLET_FREE_TIPS)
                    .desc("钱包免费提示信息")
                    .type(SysConfig.ValueType.STRING)
                    .value("")
                    .build());
        }
        if (!sysConfigRepo.findByName(SysConstants.PICTURE_COMPRESSION).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.PICTURE_COMPRESSION)
                    .desc("图片压缩开关")
                    .type(SysConfig.ValueType.BOOLEAN)
                    .value("0")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.WALLET_REGISTER_COST).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.WALLET_REGISTER_COST)
                    .desc("钱包首次开户费用")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("5")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.WALLET_MANAGE_COST).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.WALLET_MANAGE_COST)
                    .desc("钱包管理费用")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("10")
                    .build());
        }

        if (!sysConfigRepo.findByName(SysConstants.WALLET_WITHDRAW_CHARGE).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.WALLET_WITHDRAW_CHARGE)
                    .desc("钱包提现手续费")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("1")
                    .build());
        }


        if (!sysConfigRepo.findByName(SysConstants.TRANSFORM_INTEGRAL_RATIO).isPresent()) {
            sysConfigRepo.save(SysConfig.builder()
                    .name(SysConstants.TRANSFORM_INTEGRAL_RATIO)
                    .desc("用户消费转换积分比例(0-1)")
                    .type(SysConfig.ValueType.NUMBER)
                    .value("1")
                    .build());
        }






    }


    /**
     * 获取系统配置选项
     * @return
     */
    public Map<String,Object> payPlatformOptionMap(){
        Map<String,Object> optionMap = new LinkedHashMap<>();
        optionMap.put(UniformPayConstants.ADAPAY_PLATFORM, "汇付支付");
        optionMap.put(UniformPayConstants.CUSTOM_PLATFORM, "官方支付宝");
        optionMap.put(UniformPayConstants.SANDPAY_PLATFORM, "杉德支付");
        optionMap.put(UniformPayConstants.IKUDOTPAY_PLATFORM, "酷点支付");
        optionMap.put(UniformPayConstants.SUMPAY_PLATFORM, "商盟支付");
        optionMap.put(UniformPayConstants.PAYEASENET_PLATFORM, "首信易支付");
        optionMap.put(UniformPayConstants.NOTPAY_PLATFORM, "--关闭通道--");
        return optionMap;
    }



}
