package com.kmall.api.service.mk;

import com.google.common.collect.Maps;
import com.kmall.api.dao.ApiGoodsMapper;
import com.kmall.api.dao.mk.ApiMkStoreTicketDiscountGoodsMapper;
import com.kmall.api.dao.mk.ApiMkStoreTicketDiscountMapper;
import com.kmall.api.dto.UserCouponDto;
import com.kmall.api.entity.CartVo;
import com.kmall.api.entity.GoodsVo;
import com.kmall.api.entity.StoreVo;
import com.kmall.api.entity.ThirdMerchantBizVo;
import com.kmall.api.entity.mk.MkStoreTicketDiscountVo;
import com.kmall.api.service.ApiGoodsService;
import com.kmall.api.service.ApiStoreService;
import com.kmall.api.service.ApiThirdMerchantBizService;
import com.kmall.api.service.ApiUserCouponService;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.DateUtils;
import com.kmall.common.utils.RRException;
import com.kmall.common.utils.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 门店优惠券活动Service实现类
 *
 * @author emato
 * @email admin@qhdswl.com
 * @date 2019-05-07 16:06:28
 */
@Service
public class ApiMkStoreTicketDiscountService {
    private Log logger = LogFactory.getLog(ApiMkStoreTicketDiscountService.class);
    @Autowired
    private ApiMkStoreTicketDiscountMapper mkStoreTicketDiscountMapper;
    @Autowired
    private ApiMkStoreTicketDiscountGoodsMapper apiMkStoreTicketDiscountGoodsMapper;
    @Autowired
    private ApiGoodsMapper apiGoodsMapper;
    @Autowired
    private ApiMkStoreTicketDiscountGoodsService apiMkStoreTicketDiscountGoodsService;
    @Autowired
    private ApiThirdMerchantBizService apiThirdMerchantBizService;
    @Autowired
    private ApiStoreService apiStoreService;

    public MkStoreTicketDiscountVo queryObject(Integer tickDiscId) {
        return mkStoreTicketDiscountMapper.queryObject(tickDiscId);
    }

    public MkStoreTicketDiscountVo queryTickObjectByIdAndStoreIdAndUserId(Integer couponId, Long storeId, Long userId) {
        return mkStoreTicketDiscountMapper.queryTickObjectByIdAndStoreIdAndUserId(couponId, storeId, userId);
    }

    public MkStoreTicketDiscountVo queryDiscObjectByUserId(Integer tickDiscId, Long userId) {
        return mkStoreTicketDiscountMapper.queryDiscObjectByUserId(tickDiscId, userId);
    }

    public List<MkStoreTicketDiscountVo> queryList(Map<String, Object> map) {
        return mkStoreTicketDiscountMapper.queryList(map);
    }

    public int queryTotal(Map<String, Object> map) {
        return mkStoreTicketDiscountMapper.queryTotal(map);
    }


    public List<MkStoreTicketDiscountVo> queryStoreDiscountByUserId(Map<String, Object> map) {
        return mkStoreTicketDiscountMapper.queryStoreDiscountByUserId(map);
    }

    public List<MkStoreTicketDiscountVo> getDiscountByStoreIdList(Map<String, Object> map) {
        return mkStoreTicketDiscountMapper.getDiscountByStoreIdList(map);
    }

    public Integer getTotalByDiscountByStoreId(Map<String, Object> map) {
        return mkStoreTicketDiscountMapper.getTotalByDiscountByStoreId(map);
    }

    public MkStoreTicketDiscountVo getDiscountByUserCouponId(Integer userCouponId){
        return mkStoreTicketDiscountMapper.getDiscountByUserCouponId(userCouponId);
    }

    /**
     * 查询详情页商品所支持的优惠券
     * @param storeId
     * @param userId
     * @param goodsId
     * @return
     */
    public List<MkStoreTicketDiscountVo> queryStoreDiscountByGoodsId(Integer storeId, long userId, Integer goodsId){
        GoodsVo goodsVo = apiGoodsMapper.queryObjectByStoreId(Long.valueOf(goodsId),Long.valueOf(storeId));
        if(goodsVo == null){
            logger.error("商品信息不能为空");
            throw new RRException("商品信息不能为空");
        }
        //查询该门店下的所有优惠券
        Map discountMap = Maps.newHashMap();
        discountMap.put("storeId", storeId);
        discountMap.put("userId", userId);
        discountMap.put("goodsBizType", goodsVo.getGoodsBizType());
        discountMap.put("isPast", "0");//未过期
        //详情页根据门店id、用户id、业务类型获取当前门店所有的优惠券
        List<MkStoreTicketDiscountVo> mkStoreTicketDiscountList = mkStoreTicketDiscountMapper.getDiscountByStoreIdList(discountMap);
        List<MkStoreTicketDiscountVo> discountVoList = new ArrayList<>();
        for (MkStoreTicketDiscountVo discountEntity : mkStoreTicketDiscountList) {
            //查询商品是否满足该优惠券
            Integer total = queryDiscountGoodsTotal(storeId, goodsId, discountEntity);
            discountEntity.setGoodsId(goodsId);
            if(total > 0){
                discountVoList.add(discountEntity);
            }
        }
        return discountVoList;
    }

    /**
     * 查询购物车商品所支持的优惠券
     * @param isUsed
     * @return
     */
    public Map queryStoreDiscountByCartGoodsId(UserCouponDto userCouponDto, String isUsed){
        Integer storeId = Integer.parseInt(String.valueOf(userCouponDto.getStoreId()));
        long userId= userCouponDto.getUserId();
        List<CartVo> cartList = userCouponDto.getCartGoodsList();
        String bizType = userCouponDto.getBizType();
        List<MkStoreTicketDiscountVo> discountVoList = new ArrayList<>();
        StringBuffer goodsIdStr = new StringBuffer();
        for(CartVo cartVo: cartList){
            if(bizType.equalsIgnoreCase(cartVo.getGoodsBizType())) {
                Integer goodsId = Integer.parseInt(String.valueOf(cartVo.getGoods_id()));
                GoodsVo goodsVo = apiGoodsMapper.queryObjectByStoreId(Long.valueOf(goodsId), Long.valueOf(storeId));
                if (goodsVo == null) {
                    logger.error("商品信息不能为空");
                    throw new RRException("商品信息不能为空");
                }
                //查询该门店下的所有优惠券
                Map discountMap = Maps.newHashMap();
                discountMap.put("storeId", storeId);
                discountMap.put("userId", userId);
                discountMap.put("goodsBizType", goodsVo.getGoodsBizType());
                discountMap.put("isPast", "0");//未过期
                if(userCouponDto.getTickDiscId() != null){
                    discountMap.put("tickDiscId", userCouponDto.getTickDiscId());
                }
                List<MkStoreTicketDiscountVo> mkStoreTicketDiscountList = new ArrayList<>();
                if (StringUtils.isNotEmpty(isUsed)) {
                    discountMap.put("isUsed", isUsed);
                    //获取购物车中根据门店id、用户id、业务类型，获取is_used已领取、is_valid有效、enabled可用、ticket_num有库存、isPast未过期、且失效时间没超时的优惠券，addTime
                    List<MkStoreTicketDiscountVo> resultDiscountList = mkStoreTicketDiscountMapper.getDiscountByCartGoodsIdList(discountMap);
                    //购物车返回的优惠券数据需根据领券时间校验优惠券是否有效
                    mkStoreTicketDiscountList = getValidDiscountList(resultDiscountList);
                }
                //根据领券时间筛选过的有效的优惠券list
                for (MkStoreTicketDiscountVo discountEntity : mkStoreTicketDiscountList) {
                    //查询商品是否满足该优惠券
                    Integer total = queryDiscountGoodsTotal(storeId, goodsId, discountEntity);
                    discountEntity.setGoodsId(goodsId);
                    if (total > 0) {
                        goodsIdStr.append(goodsId+",");
                        discountVoList.add(discountEntity);
                    }
                }
            }
        }
        //goodsIdStr为满足优惠券的多条商品id字符串，goodsIdStr不为空，将goodsList设置到discountVoList中
        if(goodsIdStr != null && !goodsIdStr.toString().equalsIgnoreCase("")) {
            String[] gid = goodsIdStr.toString().split(",");
            Integer[] goodsIds =  new Integer[gid.length];
            for(int i=0;i < gid.length;i++){
                goodsIds[i] = Integer.parseInt(gid[i]);
            }
            List goodsList = new ArrayList();
            for (Integer goods : goodsIds) {
                if (!goodsList.contains(goods)) {
                    goodsList.add(goods);
                }
            }
            for (MkStoreTicketDiscountVo vo : discountVoList) {
                vo.setGoodsList(goodsList);
            }
        }
        Map map = new HashMap();
        map.put("discountVoList", discountVoList);
        return map;
    }
    /**
     * 查询商品是否满足该优惠券
     * @param storeId
     * @param goodsId
     * @param discountEntity
     * @return
     */
    public List<GoodsVo> queryDiscountGoodsList(Integer storeId, Integer goodsId, MkStoreTicketDiscountVo discountEntity){
        if(storeId == null){
            logger.error("门店id不能为空");
            throw new RRException("门店id不能为空");
        }
        StoreVo storeVo = apiStoreService.queryObject(Long.valueOf(storeId));
        ThirdMerchantBizVo thirdMerchantBiz = new ThirdMerchantBizVo();
        if(storeVo != null) {
            thirdMerchantBiz = apiThirdMerchantBizService.getThirdMerchangByCode(storeVo.getThirdPartyMerchCode());
            if (null == thirdMerchantBiz) {
                logger.error("第三方商户为空");
                throw new RRException("第三方商户为空");
            }
        }
        Map params = Maps.newHashMap();
        params.put("fields", "psr1.category_id");
        params.put("store_id", storeId);
        params.put("tickDiscId", discountEntity.getTickDiscId());
        params.put("applyType", discountEntity.getApplyType());

        params.remove("fields");

        params.put("fields", "a.id,a.name,a.goods_brief,a.list_pic_url,psr1.retail_price," +
                "psr1.market_price,b.id as product_id,psr1.stock_num");
        params.put("is_hot", "1");
        params.put("is_delete", 0);
        params.put("store_id", storeId);
        params.put("isStockShare", thirdMerchantBiz.getIsStockShare());
        params.put("goodsId", goodsId);
        List<GoodsVo> goodsVoList = apiMkStoreTicketDiscountGoodsMapper.queryDiscountGoodsList(params);
        return goodsVoList;
    }

    /**
     * 查询商品是否满足该优惠券
     * @param storeId
     * @param goodsId
     * @param discountEntity
     * @return
     */
    public Integer queryDiscountGoodsTotal(Integer storeId, Integer goodsId, MkStoreTicketDiscountVo discountEntity){
        if(storeId == null){
            logger.error("门店id不能为空");
            throw new RRException("门店id不能为空");
        }
        StoreVo storeVo = apiStoreService.queryObject(Long.valueOf(storeId));
        ThirdMerchantBizVo thirdMerchantBiz = new ThirdMerchantBizVo();
        if(storeVo != null) {
            thirdMerchantBiz = apiThirdMerchantBizService.getThirdMerchangByCode(storeVo.getThirdPartyMerchCode());
            if (null == thirdMerchantBiz) {
                logger.error("第三方商户为空");
                throw new RRException("第三方商户为空");
            }
        }
        Map params = Maps.newHashMap();
        params.put("tickDiscId", discountEntity.getTickDiscId());
        params.put("applyType", discountEntity.getApplyType());
        params.put("is_hot", "1");
        params.put("is_delete", 0);
        params.put("store_id", storeId);
        params.put("isStockShare", thirdMerchantBiz.getIsStockShare());
        params.put("goodsId", goodsId);

        return apiMkStoreTicketDiscountGoodsMapper.queryDiscountGoodsTotal(params);
    }


    /**
     * 校验优惠券时间是否可用
     * @param discountVoParamList
     * @return
     */
    private List<MkStoreTicketDiscountVo> getValidDiscountList(List<MkStoreTicketDiscountVo> discountVoParamList){
        List<MkStoreTicketDiscountVo> discountVoList = new ArrayList<>();
        for (MkStoreTicketDiscountVo discountVo : discountVoParamList) {
            if (discountVo.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_00.getItem())) {
                if (!DateUtils.compareDate(discountVo.getFixEndTime(), new Date())) {//有效
                    discountVoList.add(discountVo);
                }
            }
            if (discountVo.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_01.getItem())) {
                String validDayNum = com.kmall.common.utils.StringUtils.isNotEmpty(discountVo.getValidDayNum()) ? discountVo.getValidDayNum() : "0";
                String postponeNum = com.kmall.common.utils.StringUtils.isNotEmpty(discountVo.getPostponeNum()) ? discountVo.getPostponeNum() : "0";
                Integer day = Integer.parseInt(postponeNum) + Integer.parseInt(validDayNum);
                Date endDate = DateUtils.addDay(discountVo.getAddTime(), day);
                if (!DateUtils.compareDate(endDate, new Date())) {//结束时间超过当前时间则过期
                    discountVoList.add(discountVo);
                }
            }
        }
        return discountVoList;
    }

    public Integer updateDiscount(MkStoreTicketDiscountVo discountVo){
        return mkStoreTicketDiscountMapper.update(discountVo);
    }
}
