package com.hai.service.impl;

import com.alibaba.fastjson.JSON;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.dao.HighCouponHandselMapper;
import com.hai.dao.HighCouponMapper;
import com.hai.entity.*;
import com.hai.model.HighCouponHandselModel;
import com.hai.model.HighCouponModel;
import com.hai.service.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/11 22:07
 */
@Service("highCouponService")
public class HighCouponServiceImpl implements HighCouponService {

    @Resource
    private HighCouponMapper highCouponMapper;

    @Resource
    private HighCouponHandselService highCouponHandselService;

    @Resource
    private HighGoodsPriceReferService highGoodsPriceReferService;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private HighMerchantService highMerchantService;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighApproveService highApproveService;

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void insertCoupon(HighCoupon highCouponModel) {
        highCouponMapper.insert(highCouponModel);

        // 增加赠送卡卷
        if (highCouponModel.getHandselCouponList() != null && highCouponModel.getHandselCouponList().size() > 0) {
            for (HighCouponHandselModel handsel : highCouponModel.getHandselCouponList()) {
                handsel.setCouponId(highCouponModel.getId());
                highCouponHandselService.insertCouponHandsel(handsel);
            }
        }

        HighGoodsPriceRefer salePrice = new HighGoodsPriceRefer();
        salePrice.setObjectType(1);
        salePrice.setObjectId(highCouponModel.getId());
        salePrice.setPriceType(1);   // 价格类型 1：原价  2：折扣价
        salePrice.setOldSalePrice(highCouponModel.getSalesPrice());
        salePrice.setNewSalePrice(highCouponModel.getSalesPrice());
        salePrice.setPromptlyType(true);
        salePrice.setEffectiveTime(new Date());
        salePrice.setRemark("【创建产品】初始原价价格");
        salePrice.setStatus(1);  // 状态: 0:删除 1:待编辑  2:未生效  3:已生效  4:已失效  101.审批中  102.审批驳回
        salePrice.setCreateTime(new Date());
        salePrice.setOperatorId(highCouponModel.getOperatorId());
        salePrice.setOperatorName(highCouponModel.getOperatorName());
        highGoodsPriceReferService.insertPriceRefer(salePrice);


        HighGoodsPriceRefer discountPrice = new HighGoodsPriceRefer();
        discountPrice.setObjectType(1);
        discountPrice.setObjectId(highCouponModel.getId());
        discountPrice.setPriceType(2);   // 价格类型 1：原价  2：折扣价
        discountPrice.setOldSalePrice(highCouponModel.getDiscountPrice());
        discountPrice.setNewSalePrice(highCouponModel.getDiscountPrice());
        discountPrice.setPromptlyType(true);
        discountPrice.setEffectiveTime(new Date());
        discountPrice.setRemark("【创建产品】初始折扣价格");
        discountPrice.setStatus(1);  // 状态: 0:删除 1:待编辑  2:未生效  3:已生效  4:已失效  101.审批中  102.审批驳回
        discountPrice.setCreateTime(new Date());
        discountPrice.setOperatorId(highCouponModel.getOperatorId());
        discountPrice.setOperatorName(highCouponModel.getOperatorName());
        highGoodsPriceReferService.insertPriceRefer(discountPrice);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void updateCoupon(HighCoupon highCouponModel) {
        highCouponMapper.updateByPrimaryKey(highCouponModel);

        // 赠送卡卷
        if (highCouponModel.getHandselCouponList() != null && highCouponModel.getHandselCouponList().size() > 0) {
            for (HighCouponHandselModel handsel : highCouponModel.getHandselCouponList()) {
                // 状态标记为删除的，进行删除操作
                if (handsel.getStatus() == 0) {
                    highCouponHandselService.updateCouponHandsel(handsel);
                }
                // id为空的，进行增加操作
                if (handsel.getId() == null) {
                    handsel.setCouponId(highCouponModel.getId());
                    highCouponHandselService.insertCouponHandsel(handsel);
                }
            }
        }

        HighCoupon coupon = getCouponById(highCouponModel.getId());

        // 如果卡卷销售价格进行了修改
        if (!coupon.getSalesPrice().equals(highCouponModel.getSalesPrice())) {
            // 所有价格失效
            highGoodsPriceReferService.couponAllSalesPriceInvalid(highCouponModel.getId());
            // 增加新销售价格
            HighGoodsPriceRefer salePrice = new HighGoodsPriceRefer();
            salePrice.setObjectType(1);
            salePrice.setObjectId(highCouponModel.getId());
            salePrice.setPriceType(1);   // 价格类型 1：原价  2：折扣价
            salePrice.setOldSalePrice(coupon.getSalesPrice());
            salePrice.setNewSalePrice(highCouponModel.getSalesPrice());
            salePrice.setPromptlyType(true);
            salePrice.setEffectiveTime(new Date());
            salePrice.setRemark("【修改产品】初始原价价格");
            salePrice.setStatus(1);  // 状态: 0:删除 1:待编辑  2:未生效  3:已生效  4:已失效  101.审批中  102.审批驳回
            salePrice.setCreateTime(new Date());
            salePrice.setOperatorId(highCouponModel.getOperatorId());
            salePrice.setOperatorName(highCouponModel.getOperatorName());
            highGoodsPriceReferService.insertPriceRefer(salePrice);
        }

        if (!coupon.getDiscountPrice().equals(highCouponModel.getDiscountPrice())) {
            // 所有价格失效
            highGoodsPriceReferService.couponAllDiscountPriceInvalid(highCouponModel.getId());
            // 增加新价格
            HighGoodsPriceRefer salePrice = new HighGoodsPriceRefer();
            salePrice.setObjectType(1);
            salePrice.setObjectId(highCouponModel.getId());
            salePrice.setPriceType(2);   // 价格类型 1：原价  2：折扣价
            salePrice.setOldSalePrice(coupon.getDiscountPrice());
            salePrice.setNewSalePrice(highCouponModel.getDiscountPrice());
            salePrice.setPromptlyType(true);
            salePrice.setEffectiveTime(new Date());
            salePrice.setRemark("【修改产品】初始折扣价格");
            salePrice.setStatus(1);  // 状态: 0:删除 1:待编辑  2:未生效  3:已生效  4:已失效  101.审批中  102.审批驳回
            salePrice.setCreateTime(new Date());
            salePrice.setOperatorId(highCouponModel.getOperatorId());
            salePrice.setOperatorName(highCouponModel.getOperatorName());
            highGoodsPriceReferService.insertPriceRefer(salePrice);
        }
    }

    @Override
    public void update(HighCoupon highCoupon) {
        highCouponMapper.updateByPrimaryKey(highCoupon);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void upShelfApprove(Long id) {
        // 查询卡卷
        HighCoupon coupon = getCouponById(id);
        if (coupon == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
        }
        coupon.setStatus(101);  // 状态：0.删除 1.编辑中  2.已上架  3.已下架  101.上架审批中 102.上架审批驳回
        coupon.setUpdateTime(new Date());
        update(coupon);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void upShelfApproveResult(HighApprove highApprove) {
        // 查询卡卷
        HighCoupon couponDetail = getCouponDetail(highApprove.getObjectId());
        if (couponDetail == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
        }
        if (couponDetail.getStatus() != 101) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_UNABLE_UP_SHELF, "");
        }

        // 状态:  1:待审批  2:驳回  3:通过
        if (highApprove.getStatus() == 2) {
            couponDetail.setStatus(102);
        }

        if (highApprove.getStatus() == 3) {
            couponDetail.setStatus(2);
            Map<String, Object> map = new HashMap<>();
            map.put("objectType", 1);
            map.put("objectId", couponDetail.getId());
            map.put("status", 1);
            List<HighGoodsPriceRefer> list = highGoodsPriceReferService.getPriceList(map);
            if (list != null && list.size() > 0) {
                for (HighGoodsPriceRefer priceRefer : list) {
                    priceRefer.setEffectiveTime(new Date());
                    priceRefer.setStatus(3);
                    highGoodsPriceReferService.updatePriceRefer(priceRefer);
                }
            }
        }

        highCouponMapper.updateByPrimaryKey(couponDetail);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void ofShelfCoupon(Long id) {
        HighCoupon coupon = getCouponById(id);
        if (coupon == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
        }
        //状态：0.删除 1.编辑中  2.已上架  3.已下架   101.上架审批中 102.上架审批驳回
        if (coupon.getStatus() != 2) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_UNABLE_UP_SHELF, "");
        }
        coupon.setStatus(3);
        highCouponMapper.updateByPrimaryKey(coupon);

        // 卡卷价格全部失效。但保留当前生效的价格
        highGoodsPriceReferService.couponAllInvalidKeepCurrent(coupon.getId());
    }

    @Override
    public void deleteCoupon(Long id) {
        HighCoupon coupon = getCouponById(id);
        if (coupon == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
        }
        //状态：0.删除 1.编辑中  2.已上架  3.已下架   101.上架审批中 102.上架审批驳回
        if (coupon.getStatus() != 1 && coupon.getStatus() != 102) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_UNABLE_UP_SHELF, "");
        }
        coupon.setStatus(0);
        highCouponMapper.updateByPrimaryKey(coupon);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void priceApproveResult(HighApprove highApprove) {
        HighGoodsPriceRefer highGoodsPriceRefer = highGoodsPriceReferService.getPriceReferById(highApprove.getObjectId());
        if (highGoodsPriceRefer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.GOODS_PRICE_REFER_ERROR, "");
        }
        // 状态: 0:删除 1:待编辑  2:待生效  3:已生效  4:已失效  101.审批中  102.审批驳回
        if (highGoodsPriceRefer.getStatus() != 101) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
        }
        // 卡卷信息
        HighCoupon coupon = getCouponById(highGoodsPriceRefer.getObjectId());
        if (coupon == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
        }

        // 状态:  1:待审批  2:驳回  3:通过
        // 价格类型 1：原价  2：折扣价
        if (highApprove.getStatus() == 2) {
            // 及时生效  0：否  1：是
            if (highGoodsPriceRefer.getPromptlyType() == true) {
                coupon.setCouponPrice(highGoodsPriceRefer.getNewSalePrice());
                update(coupon);
            }
            highGoodsPriceRefer.setStatus(3);
        }
        if (highApprove.getStatus() == 3) {
            highGoodsPriceRefer.setStatus(102);
        }
        highGoodsPriceReferService.updatePriceRefer(highGoodsPriceRefer);
    }

    @Override
    public HighCoupon getCouponById(Long id) {
        HighCoupon highCoupon = highCouponMapper.selectByPrimaryKey(id);
        if (highCoupon == null) {
            return null;
        }
        HighCoupon model = new HighCoupon();
        BeanUtils.copyProperties(highCoupon, model);
        // 查询有效库存
        model.setStockCount(highCouponCodeService.getStockCountByCoupon(highCoupon.getId()));

        // 查询赠送卡卷列表
        List<HighCouponHandselModel> coupon = highCouponHandselService.getHandselListByCoupon(highCoupon.getId());
        model.setHandselCouponList(coupon);

        // 组装赠送卡卷id
        List<Long> handselCouponId = new ArrayList<>();
        if (coupon.size() > 0) {
            for (HighCouponHandsel handsel : coupon) {
                handselCouponId.add(handsel.getHandselCouponId());
            }
        }
        model.setHandselCouponId(handselCouponId);

        return model;
    }

    @Override
    public HighCoupon getCouponDetail(Long id) {
        HighCoupon highCoupon = highCouponMapper.selectByPrimaryKey(id);
        if (highCoupon == null) {
            return null;
        }
        HighCoupon model = new HighCoupon();
        BeanUtils.copyProperties(highCoupon, model);
        // 查询有效库存
        model.setSalesCount(highCouponCodeService.getStockCountByCoupon(highCoupon.getId()));
        return model;
    }

    @Override
    public HighCoupon getCouponDetail(String couponKey) {
        HighCouponExample example = new HighCouponExample();
        example.createCriteria().andCouponKeyEqualTo(couponKey).andStatusNotEqualTo(0);
        List<HighCoupon> list = highCouponMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<HighCoupon> getCouponList(Map<String, Object> map) {
        HighCouponExample example = new HighCouponExample();
        HighCouponExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "companyId") != null) {
            criteria.andCompanyIdEqualTo(MapUtils.getLong(map, "companyId"));
        }

        if (MapUtils.getLong(map, "merchantId") != null) {
            criteria.andMerchantIdEqualTo(MapUtils.getLong(map, "merchantId"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "couponName"))) {
            criteria.andCouponNameLike("%" + MapUtils.getString(map, "couponName") + "%");
        }

        if (MapUtils.getInteger(map, "couponType") != null) {
            criteria.andCouponTypeEqualTo(MapUtils.getInteger(map, "couponType"));
        }

        if (MapUtils.getInteger(map, "displayArea") != null) {
            criteria.andDisplayAreaEqualTo(MapUtils.getInteger(map, "displayArea"));
        }

        if (MapUtils.getInteger(map, "displayArea") != null) {
            criteria.andDisplayAreaEqualTo(MapUtils.getInteger(map, "displayArea"));
        }

        if (MapUtils.getInteger(map, "brandId") != null) {
            criteria.andBrandIdEqualTo(MapUtils.getInteger(map, "brandId"));
        }

        if (MapUtils.getInteger(map, "goodsTypeId") != null) {
            criteria.andGoodsTypeIdEqualTo(MapUtils.getInteger(map, "goodsTypeId"));
        }

        if (MapUtils.getInteger(map, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(map, "status"));
        }

        if (MapUtils.getInteger(map, "couponSource") != null) {
            criteria.andCouponSourceEqualTo(MapUtils.getInteger(map, "status"));
        }

        if (MapUtils.getInteger(map, "notCouponSource") != null) {
            criteria.andCouponSourceNotEqualTo(MapUtils.getInteger(map, "notCouponSource"));
        }

        example.setOrderByClause("create_time");
        List<HighCoupon> coupons = highCouponMapper.selectByExample(example);
        if (coupons != null && coupons.size() > 0) {
            for (HighCoupon highCoupon : coupons) {
                highCoupon.setMerchantName(highMerchantService.getMerchantById(highCoupon.getMerchantId()).getMerchantName());
                highCoupon.setStockCount(highCouponCodeService.getStockCountByCoupon(highCoupon.getId()));
            }
        }
        return coupons;
    }

    @Override
    public Long getCouponByCouponName(Long companyId,String couponName) {
        HighCouponExample example = new HighCouponExample();
        example.createCriteria().andCompanyIdEqualTo(companyId).andCouponNameEqualTo(couponName);
        return highCouponMapper.countByExample(example);
    }

    @Override
    public List<HighCoupon> getCouponListByMerchant(Long merchantId) {
        HighCouponExample example = new HighCouponExample();
        example.createCriteria().andMerchantIdEqualTo(merchantId).andStatusEqualTo(1).andStatusNotEqualTo(0);
        return highCouponMapper.selectByExample(example);
    }

    @Override
    public Boolean userBuyLimitNumber(Long userId, Long couponId) {
        Boolean status = false;
        HighCoupon coupon = getCouponById(couponId);

        Map<String, Object> map = new HashMap<>();
        map.put("memId", userId);
        map.put("goodsType", 1);
        map.put("goodsId", couponId);
        map.put("childOrdeStatusList", "2,3");
        List<HighChildOrder> childOrderList = highOrderService.getChildOrderList(map);

        // 限购数量 大于购买数量
        if (coupon != null && childOrderList.size() > coupon.getLimitNumber()) {
            status = true;
        }

        return status;
    }


}
