package com.hai.service.impl;

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.common.utils.DateUtil;
import com.hai.dao.BsOrderRebateMapper;
import com.hai.entity.*;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("bsOrderRebateService")
public class BsOrderRebateServiceImpl implements BsOrderRebateService {

    @Resource
    private BsOrderRebateMapper bsOrderRebateMapper;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private BsIntegralRebateService bsIntegralRebateService;

    @Resource
    private BsDistributionUserRelService bsDistributionUserRelService;

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighGoldRecService highGoldRecService;

    @Override
    public List<BsOrderRebate> getOrderRebateByList(Map<String, Object> map) {

        BsOrderRebateExample example = new BsOrderRebateExample();

        return null;
    }

    @Override
    public void insertOrderRebate(BsOrderRebate bsOrderRebate) {
        bsOrderRebateMapper.insert(bsOrderRebate);
    }

    @Override
    public void updateOrderRebate(BsOrderRebate bsOrderRebate) {
        bsOrderRebateMapper.updateByPrimaryKey(bsOrderRebate);
    }

    @Override
    public BsOrderRebate findOrderRebate(Long id) {
        return bsOrderRebateMapper.selectByPrimaryKey(id);
    }

    @Override
    public void insertOrderRebate(HighOrder highOrder) {

        // 计算返利积分数量
        // 查询是否配置返利
        Map<String, Object> map = new HashMap<>();
        map.put("type" , highOrder.getProductType());
        map.put("companyId" , highOrder.getCompanyId());

        BsIntegralRebate bsIntegralRebate = bsIntegralRebateService.findIntegralRebateByMap(map);

        // 判断是否配置返利内容
        if (bsIntegralRebate != null) {

            // 判断是否在返利条件
            if (DateUtil.isEffectiveDate(highOrder.getCreateTime(), bsIntegralRebate.getStartTime() , bsIntegralRebate.getEndTime())) {

                // 积分返利积分
                BigDecimal integralNum = highOrder.getPayRealPrice().multiply(bsIntegralRebate.getPercentage()).setScale( 0, BigDecimal.ROUND_HALF_UP );
                // 1级分销
                BigDecimal integralNumFirst = highOrder.getPayRealPrice().multiply(bsIntegralRebate.getFirstDistribution()).setScale( 0, BigDecimal.ROUND_HALF_UP );
                // 2级分销
                BigDecimal integralNumSecond = highOrder.getPayRealPrice().multiply(bsIntegralRebate.getSecondDistribution()).setScale( 0, BigDecimal.ROUND_HALF_UP );

                // 定义请求对象
                JSONObject object = new JSONObject();
                // 拼接分销返利对象
                object.put("userId" , highOrder.getMemId());
                object.put("orderNo" , highOrder.getOrderNo());
                object.put("integralNumFirst" , integralNumFirst);
                object.put("integralNumSecond" , integralNumSecond);
                object.put("companyId", highOrder.getCompanyId());
                object.put("remark" , OrderProductType.getDataByType(highOrder.getProductType()).getName() + "订单:"+ highOrder.getTitle() + "-" + highOrder.getOrderNo() + "积分返利：");
                object.put("name" , "下单" + OrderProductType.getDataByType(highOrder.getProductType()).getName() + ":" + highOrder.getTitle());
                object.put("logoImg" , OrderProductType.getDataByType(highOrder.getProductType()).getImgUrl());

                bsDistributionUserRelService.distributionRebate(object);
                highUserService.goldHandle(highOrder.getMemId(), integralNum.intValue(), 1, 4, highOrder.getId(), object.getString("remark") + integralNum , highOrder.getOrderNo());

                // 查询积分返利记录
                BsOrderRebate orderRebate = new BsOrderRebate();
                orderRebate.setOrderId(highOrder.getId());
                orderRebate.setOrderNo(highOrder.getOrderNo());
                orderRebate.setCreateTime(new Date());
                orderRebate.setUpdateTime(new Date());
                orderRebate.setStatus(1);
                orderRebate.setIntegralNum(integralNum.intValue());
                orderRebate.setUserId(highOrder.getMemId());
                orderRebate.setUserName(highOrder.getMemName());
                bsOrderRebateMapper.insert(orderRebate);
            }

        }


    }

    @Override
    public void insertOrderRebate(JSONObject jsonObject) {

        if (jsonObject.getInteger("productType") ==null
                || jsonObject.getString("phone") == null
                || jsonObject.getString("orderNo") == null
                || jsonObject.getLong("orderId") == null
                || jsonObject.getString("title") == null
                || jsonObject.getDate("createTime") == null
                || jsonObject.getBigDecimal("price") == null
        ) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "缺少参数！");
        }

        HighUser highUser = highUserService.findByPhone(jsonObject.getString("phone"));
        // 计算返利积分数量
        // 查询是否配置返利
        Map<String, Object> map = new HashMap<>();
        map.put("type" , jsonObject.getInteger("productType"));
        map.put("companyId" ,2);

        BsIntegralRebate bsIntegralRebate = bsIntegralRebateService.findIntegralRebateByMap(map);

        // 判断是否配置返利内容
        if (bsIntegralRebate != null) {

            // 查询是否存在积分记录
            Map<String, Object> mapGold = new HashMap<>();
            mapGold.put("goldType", 1);
            mapGold.put("resType", jsonObject.getInteger("productType"));
            mapGold.put("userId", highUser.getId());
            mapGold.put("resId", jsonObject.getLong("orderId"));

            List<HighGoldRec> goldRecs = highGoldRecService.getGoldRec(mapGold);

            // 判断是否重复赠送积分
            if (goldRecs.size() > 0) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "重复赠送！");
            }

            // 判断是否在返利条件
            if (DateUtil.isEffectiveDate(jsonObject.getDate("createTime"), bsIntegralRebate.getStartTime() , bsIntegralRebate.getEndTime())) {

                // 定义请求对象
                JSONObject object = new JSONObject();

                // 积分返利积分
                BigDecimal integralNum = jsonObject.getBigDecimal("price").multiply(bsIntegralRebate.getPercentage()).setScale( 0, BigDecimal.ROUND_HALF_UP );

                if (integralNum.compareTo(new BigDecimal(0)) < 1) {
                    integralNum = new BigDecimal(1);
                }

                if (bsIntegralRebate.getSecondDistribution() !=null || bsIntegralRebate.getFirstDistribution() != null) {
                    // 1级分销
                    BigDecimal integralNumFirst = jsonObject.getBigDecimal("price").multiply(bsIntegralRebate.getFirstDistribution()).setScale( 0, BigDecimal.ROUND_HALF_UP );
                    // 2级分销
                    BigDecimal integralNumSecond = jsonObject.getBigDecimal("price").multiply(bsIntegralRebate.getSecondDistribution()).setScale( 0, BigDecimal.ROUND_HALF_UP );
                    object.put("integralNumFirst" , integralNumFirst);
                    object.put("integralNumSecond" , integralNumSecond);

                }

                // 拼接分销返利对象
                object.put("userId" , highUser.getId());
                object.put("orderNo" , jsonObject.getString("orderNo"));

                object.put("companyId", 2);
                object.put("remark" , OrderProductType.getDataByType(jsonObject.getInteger("productType")).getName() + "下单:"+ jsonObject.getString("title") + "-" + jsonObject.getString("orderNo") + "积分返利：");
                object.put("name" , "下单" + OrderProductType.getDataByType(jsonObject.getInteger("productType")).getName() + ":" + jsonObject.getString("title"));
                object.put("logoImg" , OrderProductType.getDataByType(jsonObject.getInteger("productType")).getImgUrl());

                bsDistributionUserRelService.distributionRebate(object);
                highUserService.goldHandle(highUser.getId(), integralNum.intValue(), 1, jsonObject.getInteger("productType"), jsonObject.getLong("orderId"), object.getString("remark") + integralNum , jsonObject.getString("orderNo"));

                // 查询积分返利记录
                BsOrderRebate orderRebate = new BsOrderRebate();
                orderRebate.setOrderId(jsonObject.getLong("orderId"));
                orderRebate.setOrderNo(jsonObject.getString("orderNo"));
                orderRebate.setCreateTime(new Date());
                orderRebate.setUpdateTime(new Date());
                orderRebate.setStatus(1);
                orderRebate.setIntegralNum(integralNum.intValue());
                orderRebate.setUserId(highUser.getId());
                orderRebate.setUserName(highUser.getName());
                bsOrderRebateMapper.insert(orderRebate);
            }

        }
    }
}
