package com.hai.openApi.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.DataUtilConfig;
import com.hai.config.QianZhuConfig;
import com.hai.entity.*;
import com.hai.openApi.config.PriceComputeConfig;
import com.hai.openApi.service.ApiBlxCouponService;
import com.hai.openApi.service.ApiMchProductService;
import com.hai.openApi.service.ApiOrderCreateHandleService;
import com.hai.openApi.type.OperatorTypeEnum;
import com.hai.order.type.OrderProductType;
import com.hai.service.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service("apiOrderCreateHandleService")
public class ApiOrderCreateHandleServiceImpl implements ApiOrderCreateHandleService {

    @Resource
    private ApiMerchantsService apiMerchantsService;

    @Resource
    private HighGasOilPriceService highGasOilPriceService;

    @Resource
    private PriceComputeConfig priceComputeConfig;

    @Resource
    private HighMerchantStoreService highMerchantStoreService;

    @Resource
    private ApiMchProductService apiMchProductService;

    @Resource
    private ApiMemberProductService apiMemberProductService;

    @Resource
    private OutRechargePriceService rechargePriceService;

    @Resource
    private ApiProductService apiProductService;

    @Resource
    private ApiBlxCouponService apiBlxCouponService;

    @Override
    public ApiOrder oilHandle(JSONObject object) throws Exception {

        //  获取下单内容
        JSONObject dataObject = JSONObject.parseObject(object.getString("content"));

        // 查询油枪价
        HighGasOilPrice highGasOilPrice =  highGasOilPriceService.getGasOilPriceByStoreAndOilNo(dataObject.getLong("storeCode") , dataObject.getString("gasOilNo"));

        // 查询api商户
        ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

        // 查询加油门店
        HighMerchantStore merchantStore = highMerchantStoreService.getMerchantStoreById(dataObject.getLong("storeCode"));

        // 查询折扣比例
        Map<String , Object> mchProductMap = new HashMap<>();
        mchProductMap.put("productType" , object.getString("productType"));
        mchProductMap.put("mchId" , object.getString("merchId"));
        mchProductMap.put("merchantId" , merchantStore.getMerchantId());
        ApiMchProduct mchProduct = apiMchProductService.findByMap(mchProductMap);

        // 计算成本价格
        BigDecimal price = priceComputeConfig.computationPriceCost(mchProduct.getDiscount() , dataObject.getBigDecimal("refuelPrice"));

        // 判断金额是否充足
        if (apiMerchants.getAmounts().compareTo(price) < 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.INSUFFICIENT_BALANCE);
        }

        // 组装内容
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("oilNo" , highGasOilPrice.getOilNo());
        jsonObject.put("oilNoName" , highGasOilPrice.getOilNoName());
        jsonObject.put("priceGun" , highGasOilPrice.getPriceGun());
        jsonObject.put("priceCost" , highGasOilPrice.getPriceGun().multiply(mchProduct.getDiscount()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("oilTypeName" , highGasOilPrice.getOilTypeName());
        jsonObject.put("storeName" , merchantStore.getStoreName());
        jsonObject.put("address" , merchantStore.getAddress());
        jsonObject.put("regionName" , merchantStore.getRegionName());

        // 组装api订单
        ApiOrder apiOrder = new ApiOrder();
        apiOrder.setCreateTime(new Date());
        apiOrder.setTitle(apiMerchants.getMerchantName() + "|" + OrderProductType.PRODUCT_TYPE6.getName() + "｜扣款" + price);
        apiOrder.setFacePrice(dataObject.getBigDecimal("refuelPrice"));
        apiOrder.setCostPrice(price);
        apiOrder.setMchId(object.getString("merchId"));
        apiOrder.setMchName(apiMerchants.getMerchantName());
        apiOrder.setUpdateTime(new Date());
        apiOrder.setProductType(object.getInteger("productType"));
        apiOrder.setMchOrderNo(object.getString("orderNo"));
        apiOrder.setOrderPrice(dataObject.getBigDecimal("refuelPrice"));
        apiOrder.setNotifyUrl(object.getString("notifyUrl"));
        apiOrder.setContent(jsonObject.toJSONString());

        return apiOrder;
    }

    @Override
    public ApiOrder mobileHandle(JSONObject object) throws Exception {

        //  获取下单内容
        JSONObject dataObject = JSONObject.parseObject(object.getString("content"));

        // 查询api商户
        ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

        // 查询话费产品
        OutRechargePrice rechargePrice = rechargePriceService.findById(dataObject.getLong("productId") , null);

        // 查询折扣比例
        Map<String , Object> mchProductMap = new HashMap<>();
        mchProductMap.put("productType" , object.getString("productType"));
        mchProductMap.put("mchId" , object.getString("merchId"));
        ApiMchProduct mchProduct = apiMchProductService.findByMap(mchProductMap);

        // 计算成本价格
        BigDecimal price = priceComputeConfig.computationPriceCost(mchProduct.getDiscount() , rechargePrice.getRechargePrice());

        // 判断金额是否充足
        if (apiMerchants.getAmounts().compareTo(price) < 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.INSUFFICIENT_BALANCE);
        }

        // 组装内容
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("operatorType" , OperatorTypeEnum.getDataByType(rechargePrice.getOperatorType()).getName());
        jsonObject.put("rechargePrice" , rechargePrice.getRechargePrice());
        jsonObject.put("mobile" , dataObject.getString("mobile"));
        jsonObject.put("productId" , dataObject.getString("productId"));

        // 组装api订单
        ApiOrder apiOrder = new ApiOrder();
        apiOrder.setCreateTime(new Date());
        apiOrder.setTitle(apiMerchants.getMerchantName() + "|话费充值｜扣款" + price);
        apiOrder.setFacePrice(rechargePrice.getRechargePrice());
        apiOrder.setCostPrice(price);
        apiOrder.setMchId(object.getString("merchId"));
        apiOrder.setMchName(apiMerchants.getMerchantName());
        apiOrder.setUpdateTime(new Date());
        apiOrder.setProductType(object.getInteger("productType"));
        apiOrder.setMchOrderNo(object.getString("orderNo"));
        apiOrder.setOrderPrice(rechargePrice.getRechargePrice());
        apiOrder.setNotifyUrl(object.getString("notifyUrl"));
        apiOrder.setContent(jsonObject.toJSONString());

        return apiOrder;

    }

    @Override
    public ApiOrder  memberRechargeHandle(JSONObject object) throws Exception {

        //  获取下单内容
        JSONObject dataObject = JSONObject.parseObject(object.getString("content"));

        // 查询api商户
        ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

        ApiMemberProduct memberProduct = apiMemberProductService.findByProductId(dataObject.getString("productId"));

        if (memberProduct == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前产品不可购买");
        }

        // 查询折扣比例
        Map<String , Object> mchProductMap = new HashMap<>();
        mchProductMap.put("productType" , object.getString("productType"));
        mchProductMap.put("mchId" , object.getString("merchId"));
        ApiMchProduct mchProduct = apiMchProductService.findByMap(mchProductMap);

        // 计算成本价格
        BigDecimal price = priceComputeConfig.computationPriceCost(mchProduct.getDiscount() , memberProduct.getPrice() , memberProduct.getCostPrice());

        // 判断金额是否充足
        if (apiMerchants.getAmounts().compareTo(price) < 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.INSUFFICIENT_BALANCE);
        }

        // 组装内容
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name" ,memberProduct.getName());
        jsonObject.put("rechargePrice" , memberProduct.getPrice());
        jsonObject.put("mobile" , dataObject.getString("mobile"));
        jsonObject.put("productId" , dataObject.getString("productId"));

        // 组装api订单
        ApiOrder apiOrder = new ApiOrder();
        apiOrder.setCreateTime(new Date());
        apiOrder.setTitle(apiMerchants.getMerchantName() + "|" + OrderProductType.PRODUCT_TYPE3.getName() + "｜扣款" + price);
        apiOrder.setFacePrice(memberProduct.getPrice());
        apiOrder.setCostPrice(price);
        apiOrder.setMchId(object.getString("merchId"));
        apiOrder.setMchName(apiMerchants.getMerchantName());
        apiOrder.setUpdateTime(new Date());
        apiOrder.setProductType(object.getInteger("productType"));
        apiOrder.setMchOrderNo(object.getString("orderNo"));
        apiOrder.setOrderPrice(memberProduct.getPrice());
        apiOrder.setNotifyUrl(object.getString("notifyUrl"));
        apiOrder.setContent(jsonObject.toJSONString());
        apiOrder.setExt1(memberProduct.getId().toString());

        return apiOrder;
    }


    @Override
    public ApiOrder kfcHandle(JSONObject object) throws Exception {

        //  获取下单内容
        JSONObject dataObject = JSONObject.parseObject(object.getString("content"));

        JSONArray dataArray = dataObject.getJSONArray("data");

        // 查询api商户
        ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

        // 查询肯德基门店菜单
        JSONObject jsonObject = QianZhuConfig.listByStoreCode(dataObject.getString("storeCode"));
        JSONArray array = jsonObject.getJSONArray("data");
        if (array == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "门店编码错误");
        }

        // 查询折扣比例
        Map<String, Object> mapProduct = new HashMap<>();
        mapProduct.put("mchId" , object.getString("merchId"));
        mapProduct.put("productType" , OrderProductType.PRODUCT_TYPE2.getNumber());

        ApiMchProduct apiMchProducts = apiMchProductService.findByMap(mapProduct);

        StringBuffer orderItems = new StringBuffer();

        BigDecimal priceTotal = new BigDecimal(0);
        BigDecimal facePrice = new BigDecimal(0);

        Map<String , String> map = new HashMap<>();

        for (Object o : dataArray) {
            JSONObject itemData = (JSONObject) o;

            orderItems.append(itemData.getString("productId")).append("|").append(itemData.getInteger("num")).append(",");
            for (Object data : array) {
                JSONObject kfcObject = (JSONObject) data;
                JSONObject kfcData = DataUtilConfig.dataFindByKfc(kfcObject , itemData.getString("productId"));
                if (kfcData != null) {
                    if (map.containsKey(itemData.getString("productId"))) {
                        break;
                    }
                    map.put(itemData.getString("productId") , itemData.getString("productId"));
                    priceTotal = priceTotal.add(priceComputeConfig.computationPriceCost(apiMchProducts.getDiscount() , kfcData.getBigDecimal("originalPrice") , kfcData.getBigDecimal("price")).multiply(itemData.getBigDecimal("num")));
                    facePrice = facePrice.add(kfcData.getBigDecimal("originalPrice").multiply(itemData.getBigDecimal("num")));
                }
            }

        }

        dataObject.put("orderItems" , orderItems);

        // 组装api订单
        ApiOrder apiOrder = new ApiOrder();
        apiOrder.setCreateTime(new Date());
        apiOrder.setTitle(apiMerchants.getMerchantName() + "|" + OrderProductType.PRODUCT_TYPE2.getName() + "｜扣款" + priceTotal);
        apiOrder.setFacePrice(facePrice);
        apiOrder.setCostPrice(priceTotal);
        apiOrder.setMchId(object.getString("merchId"));
        apiOrder.setMchName(apiMerchants.getMerchantName());
        apiOrder.setUpdateTime(new Date());
        apiOrder.setProductType(object.getInteger("productType"));
        apiOrder.setMchOrderNo(object.getString("orderNo"));
        apiOrder.setOrderPrice(facePrice);
        apiOrder.setNotifyUrl(object.getString("notifyUrl"));
        apiOrder.setContent(dataObject.toJSONString());
        return apiOrder;
    }

    @Override
    public ApiOrder starbucksHandle(JSONObject object) throws Exception {

        //  获取下单内容
        JSONObject dataObject = JSONObject.parseObject(object.getString("content"));

        JSONArray dataArray = dataObject.getJSONArray("data");

        // 查询api商户
        ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

        // 查询折扣比例
        Map<String, Object> mapProduct = new HashMap<>();
        mapProduct.put("mchId" , object.getString("merchId"));
        mapProduct.put("productType" , OrderProductType.PRODUCT_TYPE2.getNumber());

        ApiMchProduct apiMchProducts = apiMchProductService.findByMap(mapProduct);

        BigDecimal priceTotal = new BigDecimal(0);
        BigDecimal facePrice = new BigDecimal(0);


        for (Object starbucksObject : dataArray) {

            JSONObject starbucksData = (JSONObject) starbucksObject;
            ApiStarbucksProducts starbucksProducts = apiProductService.findStarbucksProductsByGoodsId(starbucksData.getLong("productId"));

            BigDecimal marketPrice = priceComputeConfig.getStarbucksCpuSizePriceMarket(starbucksProducts , starbucksData.getString("cupSize"));
            BigDecimal salesPrice = priceComputeConfig.getStarbucksCpuSizePriceSales(starbucksProducts , starbucksData.getString("cupSize"));

            priceTotal = priceTotal.add(priceComputeConfig.computationPriceCost(apiMchProducts.getDiscount() , marketPrice , salesPrice).multiply(starbucksData.getBigDecimal("num")));
            facePrice = facePrice.add(marketPrice.multiply(starbucksData.getBigDecimal("num")));

        }

        // 组装api订单
        ApiOrder apiOrder = new ApiOrder();
        apiOrder.setCreateTime(new Date());
        apiOrder.setTitle(apiMerchants.getMerchantName() + "|" + OrderProductType.PRODUCT_TYPE1.getName() + "｜扣款" + priceTotal);
        apiOrder.setFacePrice(facePrice);
        apiOrder.setCostPrice(priceTotal);
        apiOrder.setMchId(object.getString("merchId"));
        apiOrder.setMchName(apiMerchants.getMerchantName());
        apiOrder.setUpdateTime(new Date());
        apiOrder.setProductType(object.getInteger("productType"));
        apiOrder.setMchOrderNo(object.getString("orderNo"));
        apiOrder.setOrderPrice(facePrice);
        apiOrder.setNotifyUrl(object.getString("notifyUrl"));
        apiOrder.setContent(dataObject.toJSONString());
        return apiOrder;


    }

    @Override
    public ApiOrder blxCouponHandle(JSONObject object) throws Exception {

        //  获取下单内容
        JSONObject dataObject = JSONObject.parseObject(object.getString("content"));

        JSONArray dataArray = dataObject.getJSONArray("data");

        // 查询api商户
        ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

        ApiBlxCoupon apiBlxCoupon = apiBlxCouponService.findBlxCoupon(object.getString("couponCode"));

        // 查询折扣比例
        Map<String, Object> mapProduct = new HashMap<>();
        mapProduct.put("mchId" , object.getString("merchId"));
        mapProduct.put("productType" , OrderProductType.PRODUCT_TYPE13.getNumber());

        ApiMchProduct apiMchProducts = apiMchProductService.findByMap(mapProduct);

        BigDecimal priceTotal = new BigDecimal(0);
        BigDecimal facePrice = new BigDecimal(0);



        return null;
    }
}
