package com.zbkj.service.service.bcx;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.constants.ProductConstants;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.bcx.BcxPlatformFeeConfig;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.bcx.BcxPlatformFeeConfigRequest;
import com.zbkj.service.dao.bcx.BcxPlatformFeeConfigDao;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.zbkj.common.constants.ProductConstants.SPEC_TYPE_LEASE;

/**
 * 平台服务费-配置表 服务实现类
 */
@Service
public class BcxPlatformFeeConfigServiceImpl extends ServiceImpl<BcxPlatformFeeConfigDao, BcxPlatformFeeConfig> implements BcxPlatformFeeConfigService {

    @Resource
    private BcxPlatformFeeConfigDao dao;

    @Override
    public BcxPlatformFeeConfig queryById(Integer id) {
        return dao.selectById(id);
    }

    @Override
    public BcxPlatformFeeConfig queryByProductId(Integer productId) {
        LambdaQueryWrapper<BcxPlatformFeeConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BcxPlatformFeeConfig::getProductId, productId);
        lqw.eq(BcxPlatformFeeConfig::getLevel, ProductConstants.PRODUCT_SHOW_CONFIG_LEVEL);
        lqw.orderByDesc(BcxPlatformFeeConfig::getUpdateTime);
        lqw.last("limit 1");
        return dao.selectOne(lqw);
    }

    @Override
    public BcxPlatformFeeConfig queryBySkuId(Integer skuId) {
        LambdaQueryWrapper<BcxPlatformFeeConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BcxPlatformFeeConfig::getSkuId, skuId);
        lqw.eq(BcxPlatformFeeConfig::getLevel, ProductConstants.SKU_SHOW_CONFIG_LEVEL);
        lqw.orderByDesc(BcxPlatformFeeConfig::getUpdateTime);
        lqw.last("limit 1");
        return dao.selectOne(lqw);
    }

    @Override
    public BcxPlatformFeeConfig queryByMerId(Integer merId) {
        LambdaQueryWrapper<BcxPlatformFeeConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BcxPlatformFeeConfig::getMerId, merId);
        lqw.eq(BcxPlatformFeeConfig::getLevel, ProductConstants.MERCHANT_SHOW_CONFIG_LEVEL);
        lqw.orderByDesc(BcxPlatformFeeConfig::getUpdateTime);
        lqw.last("limit 1");
        return dao.selectOne(lqw);
    }

    @Override
    public BcxPlatformFeeConfig queryByAnyId(Integer merId, Integer productId, Integer skuId) {
        if (skuId > 0) {
            BcxPlatformFeeConfig config = queryBySkuId(skuId);
            if (config != null) {
                return config;
            }
        }
        if (productId > 0) {
            BcxPlatformFeeConfig config = queryByProductId(productId);
            if (config != null) {
                return config;
            }
        }
        if (merId > 0) {
            return queryByMerId(merId);
        }
        return null;
    }

    @Override
    public PageInfo<BcxPlatformFeeConfig> queryPagedList(BcxPlatformFeeConfig request,
                                                         PageParamRequest pageParamRequest) {
        LambdaQueryWrapper<BcxPlatformFeeConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BcxPlatformFeeConfig::getId, request.getId());
        Page<BcxPlatformFeeConfig> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<BcxPlatformFeeConfig> sources = dao.selectList(lqw);
        if (CollUtil.isEmpty(sources)) {
            return CommonPage.copyPageInfo(page, CollUtil.newArrayList());
        }
        List<BcxPlatformFeeConfig> result = transform2target(sources);
        return CommonPage.copyPageInfo(page, result);
    }

    private List<BcxPlatformFeeConfig> transform2target(List<BcxPlatformFeeConfig> sources) {
        List<BcxPlatformFeeConfig> result = new ArrayList<>();
        for (BcxPlatformFeeConfig source : sources) {
            BcxPlatformFeeConfig target = new BcxPlatformFeeConfig();
            BeanUtils.copyProperties(source, target);
            result.add(target);
        }
        return result;
    }

    @Override
    public Boolean create(BcxPlatformFeeConfigRequest request) {
        if (ObjectUtil.isNull(request.getProductId())) {
            throw new CrmebException("商品id不能为空");
        }
        BcxPlatformFeeConfig exists = queryByProductId(request.getProductId());
        BcxPlatformFeeConfig config = new BcxPlatformFeeConfig();
        BeanUtils.copyProperties(request, config);
        config.setId(exists != null ? exists.getId() : null);
        config.setLevel(ProductConstants.PRODUCT_SHOW_CONFIG_LEVEL);
        return saveOrUpdate(config);
    }

    @Override
    public Boolean update(BcxPlatformFeeConfigRequest request) {
        if (ObjectUtil.isNull(request.getId())) {
            throw new CrmebException("id不能为空");
        }
        BcxPlatformFeeConfig config = queryById(request.getId());
        if (ObjectUtil.isNull(config)) {
            throw new CrmebException("未找到该配置" + request.getId());
        }
        BeanUtils.copyProperties(request, config);
        config.setLevel(ProductConstants.PRODUCT_SHOW_CONFIG_LEVEL);
        return updateById(config);
    }

    @Override
    public Boolean delete(Integer id) {
        return removeById(id);
    }

    @Override
    public BigDecimal calcSellPlatformFee(BcxPlatformFeeConfig config, BigDecimal payPrice, Integer payNum) {
        if (config.getSellFeeType() == 0) {
            //百分比,用订单总额算（因为存在改价）
            return payPrice.multiply(config.getSellFee());
        } else if (config.getSellFeeType() == 1) {
            //金额*数量
            return config.getSellFee().multiply(BigDecimal.valueOf(payNum));
        } else {
            log.error("未知的销售平台服务费类型：" + config.getSellFeeType());
            throw new CrmebException("未知的销售平台服务费类型");
        }
    }

    @Override
    public BigDecimal calcLeasePlatformFee(BcxPlatformFeeConfig config, BigDecimal payPrice, Integer payNum) {
        if (config.getLeaseFeeType() == 0) {
            //百分比,用订单总额算（因为存在改价）
            return payPrice.multiply(config.getLeaseFee());
        } else if (config.getLeaseFeeType() == 1) {
            //金额*数量
            return config.getLeaseFee().multiply(BigDecimal.valueOf(payNum));
        } else {
            log.error("未知的租赁平台服务费类型：" + config.getLeaseFeeType());
            throw new CrmebException("未知的租赁平台服务费类型");
        }
    }

    @Override
    public BigDecimal calcInstalmentPlatformFee(BcxPlatformFeeConfig config, BigDecimal payPrice, Integer payNum, Integer period) {
        BigDecimal fee;
        switch (period) {
            case 3:
                fee = config.getPeriod3Fee();
                break;
            case 6:
                fee = config.getPeriod6Fee();
                break;
            case 9:
                fee = config.getPeriod9Fee();
                break;
            case 12:
                fee = config.getPeriod12Fee();
                break;
            default:
                log.error("未知的分期数类型：" + period);
                throw new CrmebException("未知的分期服务费类型");
        }
        if (config.getInstalmentFeeType() == 0) {
            //百分比,用订单总额算（因为存在改价）
            return payPrice.multiply(fee);
        } else if (config.getInstalmentFeeType() == 1) {
            //金额*数量
            return fee.multiply(BigDecimal.valueOf(payNum));
        } else {
            log.error("未知的分期服务费类型：" + config.getInstalmentFeeType());
            throw new CrmebException("未知的分期服务费类型");
        }
    }

    @Override
    public BigDecimal calcPlatformFee(BcxPlatformFeeConfig platFeeConfig, Integer specType, BigDecimal payPrice, Integer payNum, Integer instalmentPeriod) {
        BigDecimal platformFee;
        if (specType.equals(SPEC_TYPE_LEASE)) {
            platformFee = calcLeasePlatformFee(platFeeConfig, payPrice, payNum);
        } else if (specType.equals(ProductConstants.SPEC_TYPE_INSTALMENT)) {
            platformFee = calcInstalmentPlatformFee(platFeeConfig, payPrice, payNum, instalmentPeriod);

        } else if (specType.equals(ProductConstants.SPEC_TYPE_SELL)) {
            platformFee = calcSellPlatformFee(platFeeConfig, payPrice, payNum);
        } else {
            throw new CrmebException("未知的订单业务类型：" + specType);
        }
        return platformFee;
    }

    @Override
    public Integer calcPlatformFeePriority(BcxPlatformFeeConfig platFeeConfig, Integer specType) {
        if (specType.equals(SPEC_TYPE_LEASE)) {
            return platFeeConfig.getLeaseFeePriority();
        } else if (specType.equals(ProductConstants.SPEC_TYPE_INSTALMENT)) {
            return platFeeConfig.getInstalmentFeePriority();
        } else if (specType.equals(ProductConstants.SPEC_TYPE_SELL)) {
            return platFeeConfig.getSellFeePriority();
        } else {
            throw new CrmebException("未知的订单业务类型" + specType);
        }
    }
}
