package com.hai.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.config.TuanYouConfig;
import com.hai.dao.HighGasDiscountOilPriceMapper;
import com.hai.entity.HighGasDiscountOilPrice;
import com.hai.entity.HighGasDiscountOilPriceExample;
import com.hai.entity.HighGasOilPrice;
import com.hai.entity.HighTyAgentPrice;
import com.hai.enum_type.MerchantStoreSourceType;
import com.hai.model.GasPayPriceModel;
import com.hai.model.HighMerchantStoreModel;
import com.hai.service.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

@Service("gasDiscountOilPriceService")
public class HighGasDiscountOilPriceServiceImpl implements HighGasDiscountOilPriceService {

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private HighGasDiscountOilPriceService gasDiscountOilPriceService;

    @Resource
    private HighGasOilPriceService gasOilPriceService;

    @Resource
    private HighTyAgentPriceService tyAgentPriceService;

    @Resource
    private HighGasDiscountOilPriceMapper highGasDiscountOilPriceMapper;

    @Override
    public void editGasDiscountOilPrice(HighGasDiscountOilPrice highGasDiscountOilPrice) {
        if (highGasDiscountOilPrice.getId() != null) {
            highGasDiscountOilPriceMapper.updateByPrimaryKey(highGasDiscountOilPrice);
        } else {
            highGasDiscountOilPriceMapper.insert(highGasDiscountOilPrice);
        }
    }

    @Override
    public void delete(Long id) {
        highGasDiscountOilPriceMapper.deleteByPrimaryKey(id);
    }

    @Override
    public HighGasDiscountOilPrice getDetail(Long id) {
        return highGasDiscountOilPriceMapper.selectByPrimaryKey(id);
    }

    @Override
    public HighGasDiscountOilPrice getDetailByOilNo(String oilNo) {
        HighGasDiscountOilPriceExample example = new HighGasDiscountOilPriceExample();
        example.createCriteria().andOilNoEqualTo(oilNo);
        List<HighGasDiscountOilPrice> list = highGasDiscountOilPriceMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public HighGasDiscountOilPrice getDetailByOilNoName(String oilNoName) {
        HighGasDiscountOilPriceExample example = new HighGasDiscountOilPriceExample();
        example.createCriteria().andOilNoNameEqualTo(oilNoName);
        List<HighGasDiscountOilPrice> list = highGasDiscountOilPriceMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<HighGasDiscountOilPrice> getList(Map<String,Object> map) {
        HighGasDiscountOilPriceExample example = new HighGasDiscountOilPriceExample();
        HighGasDiscountOilPriceExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(MapUtils.getString(map, "oilNo"))) {
            criteria.andOilNoEqualTo(MapUtils.getString(map, "oilNo"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "oilNoName"))) {
            criteria.andOilNoNameEqualTo(MapUtils.getString(map, "oilNoName"));
        }
        example.setOrderByClause("create_time desc");
        return highGasDiscountOilPriceMapper.selectByExample(example);
    }

    @Override
    public GasPayPriceModel oilPriceDiscountCompute(BigDecimal oilingPrice, Long goodsId, String oilNo, Boolean isTyAgent) throws Exception {
        // 查询油站信息
        HighMerchantStoreModel store = merchantStoreService.getMerchantStoreById(goodsId);
        if (store == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油站");
        }
        // 是否是加油站
        if (!store.getType().equals(1)) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油站");
        }

        // 优惠比例
        BigDecimal discount = new BigDecimal("100");

        // 查询是否配置了【油站的】优惠比例
        HighTyAgentPrice tyAgentPrice = tyAgentPriceService.getDetail(1, goodsId, oilNo);
        if (tyAgentPrice != null) {
            discount = tyAgentPrice.getPriceRate();
        } else {
            // 查询是否配置了【油品】优惠比例
            HighGasDiscountOilPrice gasDiscountOilPrice = gasDiscountOilPriceService.getDetailByOilNo(oilNo);
            if (gasDiscountOilPrice != null) {
                discount = gasDiscountOilPrice.getPriceRate();
            }
        }

        if (isTyAgent != null && isTyAgent.equals(true)) {
            // 价格
            HighTyAgentPrice priceRate = tyAgentPriceService.getDetail(2, goodsId, oilNo);
            if (priceRate != null) {
                discount = priceRate.getPriceRate();
            }
        }
        discount = discount.divide(new BigDecimal("100"));

        // 查询油站价格
        HighGasOilPrice gasOilPrice = gasOilPriceService.getGasOilPriceByStoreAndOilNo(goodsId, Integer.parseInt(oilNo));
        if (gasOilPrice == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油站价格");
        }
        // 国标价
        BigDecimal priceOfficial = gasOilPrice.getPriceOfficial();
        // 油站价
        BigDecimal priceGun = gasOilPrice.getPriceGun();
        // 油站直降
        BigDecimal gasStationDrop = gasOilPrice.getGasStationDrop();
        // 油站优惠价
        BigDecimal priceVip = gasOilPrice.getPriceVip();
        // 平台优惠
        BigDecimal preferentialMargin = gasOilPrice.getPreferentialMargin();

        GasPayPriceModel payPriceModel = new GasPayPriceModel();

        // 1：平台自建   2：团油    3: 壳牌
        if (store.getSourceType().equals(MerchantStoreSourceType.type1.getNumber())
                || store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())
                || store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber())
        ) {

            // 嗨森逛平台价    油枪价 * 折扣
            BigDecimal pricePlatform = priceGun.multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP);

            // 加油金额
            payPriceModel.setOilingPrice(oilingPrice);

            // 油站枪价
            payPriceModel.setPriceGun(priceGun);

            // 油站优惠价
            payPriceModel.setPriceVip(priceVip);

            // 油站国标价
            payPriceModel.setPriceOfficial(priceOfficial);

            // 油站直降
            payPriceModel.setGasStationDrop(gasStationDrop);

            // 平台补贴
            payPriceModel.setPreferentialMargin(gasOilPrice.getPreferentialMargin());

            // 平台价
            payPriceModel.setPricePlatform(pricePlatform);

            // 加油升数，计算方式：加油金额 / 枪价
            payPriceModel.setOilLiters(oilingPrice.divide(priceGun, 2, BigDecimal.ROUND_HALF_DOWN));

            // 平台折扣，我们平台或者代理商设置的折扣
            payPriceModel.setDiscount(discount.compareTo(new BigDecimal("1.00")) == 0 ? new BigDecimal("1.00") : discount);

            // 加油补贴, 计算方式：加油站枪价 - 加油站VIP价
            // payPriceModel.setOilSubsidy(priceGun.subtract(priceVip));

            // 折扣，1 -平台折扣
            BigDecimal decimal1 = new BigDecimal("1").subtract(discount);

            // 油枪价 - 平台补贴
            // BigDecimal price = payPriceModel.getPriceGun().subtract(preferentialMargin);

            // 优惠价格  油站VIP价 * 系统折扣
            payPriceModel.setPricePreferences(priceVip.multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP));

            // 每升优惠  油站价 - 优惠价格
            payPriceModel.setLitersPreferences(payPriceModel.getPriceGun().subtract(payPriceModel.getPricePreferences()));

            // 本次优惠  加油升数 * 每升优惠
            payPriceModel.setTotalPreferences(payPriceModel.getOilLiters().multiply(payPriceModel.getLitersPreferences()).setScale(2, BigDecimal.ROUND_HALF_UP));

            // 支付价格  加油金额 - 本次优惠
            payPriceModel.setPayPrice(oilingPrice.subtract(payPriceModel.getTotalPreferences()));

        } else if (store.getSourceType().equals(MerchantStoreSourceType.type2.getNumber())) {
            // 查询油站油品价格
            JSONObject oilPriceObject = TuanYouConfig.queryCompanyPriceDetail(store.getStoreKey(), oilNo);
            if (oilPriceObject == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油站价格");
            }
            JSONArray oilPriceObjectArray = oilPriceObject.getJSONArray("result");
            if (oilPriceObjectArray.size() == 0) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油站价格");
            }
            JSONObject priceDetail = (JSONObject) oilPriceObjectArray.get(0);
            // 团油枪价
            priceGun = priceDetail.getBigDecimal("priceGun");
            // 团油优惠价
            priceVip = priceDetail.getBigDecimal("priceVip");

            // 嗨森逛平台价    国标价 * 折扣
            BigDecimal pricePlatform = priceGun.multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP);

            // 加油金额
            payPriceModel.setOilingPrice(oilingPrice);

            // 团油枪价
            payPriceModel.setPriceGun(priceGun);

            // 团油优惠价
            payPriceModel.setPriceVip(priceVip);

            // 团油国标价
            payPriceModel.setPriceOfficial(priceOfficial);

            // 油站直降
            payPriceModel.setGasStationDrop(gasStationDrop);

            // 平台补贴
            payPriceModel.setPreferentialMargin(gasOilPrice.getPreferentialMargin());

            // 平台价
            payPriceModel.setPricePlatform(pricePlatform);

            // 加油升数，计算方式：加油金额 / 枪价
            payPriceModel.setOilLiters(oilingPrice.divide(priceGun, 2, BigDecimal.ROUND_HALF_DOWN));

            // 平台折扣，我们平台或者代理商设置的折扣
            payPriceModel.setDiscount(discount.compareTo(new BigDecimal("1.00")) == 0 ? new BigDecimal("1.00") : discount);

            // 加油补贴, 计算方式：团油枪价 - 团油VIP价
            // payPriceModel.setOilSubsidy(priceGun.subtract(priceVip));

            // 折扣，1 -平台折扣
            BigDecimal decimal1 = new BigDecimal("1").subtract(discount);

            // 价格差价  团油枪价 - 团油VIP价
            BigDecimal oilPriceDifferences = priceGun.subtract(priceVip);

            // 每升优惠 团油枪价 *（1-平台折扣）+（国标价-团油VIP价 ）
            payPriceModel.setLitersPreferences(priceGun.multiply(decimal1).setScale(2, BigDecimal.ROUND_HALF_UP).add(oilPriceDifferences));

            // 优惠价格 团油枪价 * 平台折扣 -（国标价-团油VIP价 ）
            payPriceModel.setPricePreferences(pricePlatform.subtract(oilPriceDifferences));

            // 本次优惠
            payPriceModel.setTotalPreferences(payPriceModel.getOilLiters().multiply(payPriceModel.getLitersPreferences()).setScale(2, BigDecimal.ROUND_DOWN));

            // 支付价格
            payPriceModel.setPayPrice(oilingPrice.subtract(payPriceModel.getTotalPreferences()));
        }
        return payPriceModel;
    }
}
