package com.dayou.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dayou.common.BaseEntity;
import com.dayou.entity.GlobalConfig;
import com.dayou.enums.CodeMsgEnumInterface;
import com.dayou.enums.GlobalConfigEnum;
import com.dayou.exception.ErrorCode;
import com.dayou.mapper.GlobalConfigMapper;
import com.dayou.service.IGlobalConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayou.vo.BrokerageConfigVO;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.util.CollectionUtils;


import java.math.BigDecimal;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Pattern;

import static com.dayou.common.Constants.MATH_REGULAR;

/**
 * <p>
 * 全局配置 服务实现类
 * </p>
 *
 * @author wucl
 * @since 2022-12-07
 */
@Slf4j
@Service
public class GlobalConfigServiceImpl extends ServiceImpl<GlobalConfigMapper, GlobalConfig> implements IGlobalConfigService , InitializingBean {

    private static final List<String> globalConfigExcelTitles= new ArrayList();

    static{
            globalConfigExcelTitles.add("键");
            globalConfigExcelTitles.add("");
            globalConfigExcelTitles.add("值");
            globalConfigExcelTitles.add("描述");
    }


    @Autowired
    private GlobalConfigMapper globalConfigMapper;

    @Override
    @SuppressWarnings("unchecked")
    public Page<GlobalConfig> selectPage(Page page,GlobalConfig globalConfig){
        return this.page(page, new QueryWrapper<GlobalConfig>(globalConfig));
    }


    @Override
    public GlobalConfig detail(Long id){
        return this.getById(id);
    }

    @Override
    public Boolean add(GlobalConfig globalConfig){
        GlobalConfig config = this.getOne(new LambdaQueryWrapper<GlobalConfig>()
                .eq(GlobalConfig::getKey, globalConfig.getKey())
                .eq(GlobalConfig::getField, globalConfig.getField())
                .eq(BaseEntity::getDeleted, Boolean.FALSE));

        if (config == null){
            return  this.save(globalConfig);
        }
        globalConfig.setId(config.getId());
        return this.update(globalConfig);
    }

    @Override
    public Boolean update(GlobalConfig globalConfig){
        if (globalConfig != null && globalConfig.getKey().equals(GlobalConfigEnum.FINANCE.getCode())){
            Pattern pattern = Pattern.compile(MATH_REGULAR);
            String value = globalConfig.getValue();
            boolean isNumber = pattern.matcher(value).matches();
            if (!isNumber){
                ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"参数格式不正确，请配置正确参数类型。");
            }
        }
        boolean b = globalConfigMapper.updateBatchByKey(Lists.newArrayList(globalConfig));
        return  b;
    }

    @Override
    public Boolean delete(Long id){
        //逻辑删除
        return this.removeById(id);
    }

    @Override
    public String getValue(String key, String field) {
        return globalConfigMapper.getValueByKeyFiled(key, field);
    }

    @Override
    public BigDecimal getMathValue(String key, String field){
        String value = getValue(key, field);
        if (StrUtil.isNotBlank(value)){
            Pattern pattern = Pattern.compile(MATH_REGULAR);
            return pattern.matcher(value).matches()? new BigDecimal(value) : BigDecimal.ZERO;
        }
        return BigDecimal.ZERO;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        List<GlobalConfig> list = Lists.newLinkedList();
        GlobalConfigEnum[] globalConfigEnums = GlobalConfigEnum.values();
        for(GlobalConfigEnum globalConfigEnum:globalConfigEnums){
            List<GlobalConfig> fieldList = Lists.newLinkedList();
            String key = globalConfigEnum.getCode();
            CodeMsgEnumInterface<String,String>[] fields = globalConfigEnum.getMsg();
            for(CodeMsgEnumInterface<String,String> c:fields){
                String field = c.getCode();
                String description = c.getMsg();
                GlobalConfig g = new GlobalConfig();
                g.setKey(key);
                g.setField(field);
                g.setDescription(description);
                fieldList.add(g);
            }
            list.addAll(fieldList);
        }
        if (!CollectionUtils.isEmpty(list)){
            baseMapper.insertOrUpdateBatch(list);
        }
    }

    @Override
    public BigDecimal getValueByFiled(String filed) {
        try {
            String value = globalConfigMapper.getValueByFiled(filed);
            if (StrUtil.isNotBlank(value)){
                Pattern pattern = Pattern.compile(MATH_REGULAR);
                return pattern.matcher(value).matches()? new BigDecimal(value) : BigDecimal.ZERO;
            }
        } catch (Exception e) {
            log.error("根据filed获取值发生错误，可能是存在相同的filed字段，也可能是值格式化异常。");

        }
        return BigDecimal.ZERO;
    }

    @Override
    public GlobalConfig getGlobalConfig(String key, String field) {
        return globalConfigMapper.getGlobalConfig(key,field);
    }

    @Override
    public List<GlobalConfig> getConfigByKey(String key){
        return globalConfigMapper.getConfigByKey(key);
    }
}
