package com.kmall.api.api;

import com.google.common.collect.Maps;
import com.kmall.api.annotation.LoginUser;
import com.kmall.api.dto.CheckOutDto;
import com.kmall.api.dto.UserCouponDto;
import com.kmall.api.entity.*;
import com.kmall.api.entity.mk.MkStoreTicketDiscountVo;
import com.kmall.api.entity.mk.MkStoreTopicStatVo;
import com.kmall.api.entity.mk.MkStoreTopicVisitorsVo;
import com.kmall.api.entity.mk.StoreTopicVo;
import com.kmall.api.service.ApiCartService;
import com.kmall.api.service.ApiStoreService;
import com.kmall.api.service.ApiThirdMerchantBizService;
import com.kmall.api.service.ApiUserCouponService;
import com.kmall.api.service.mk.*;
import com.kmall.api.util.ApiBaseAction;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.*;
import com.qiniu.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 门店优惠券活动Controller
 *
 * @author emato
 * @email admin@qhdswl.com
 * @date 2019-05-07 16:06:28
 */
@RestController
@RequestMapping("/api/mkstoreticketdiscount")
public class ApiStoreTicketDiscountController  extends ApiBaseAction {
    @Autowired
    private ApiMkStoreTicketDiscountService apiMkStoreTicketDiscountService;
    @Autowired
    private ApiUserCouponService apiUserCouponService;
    @Autowired
    private ApiCartService apiCartService;
    @Autowired
    private ApiMkStoreTopicStatService apiMkStoreTopicStatService;

    /**
     * 查看列表
     */
    @GetMapping("list")
    public Object list(Integer storeId,@LoginUser UserVo loginUser) {
        //查询列表数据
        Map<String, Object> params = new HashMap<>();
        params.put("storeId", storeId);
        params.put("userId", getUserId());
        params.put("isPast", "0");//未过期
        List<MkStoreTicketDiscountVo> mkStoreTicketDiscountList = apiMkStoreTicketDiscountService.getDiscountByStoreIdList(params);
        for (MkStoreTicketDiscountVo discountEntity : mkStoreTicketDiscountList) {
            discountEntity.setInValidTime(setInvalidTime(discountEntity));
            //是否领取 1：是 0：否
            discountEntity.setIsReceive(getReceive(discountEntity,loginUser));
        }

        return toResponsSuccess(mkStoreTicketDiscountList);
    }

    /**
     * 查看信息
     */
    @GetMapping("detail")
    public Object info(Integer couponId, Long storeId, Integer discId,@LoginUser UserVo loginUser) {
        MkStoreTicketDiscountVo mkStoreTicketDiscount = null;
        if(couponId != null){
            mkStoreTicketDiscount = apiMkStoreTicketDiscountService.queryTickObjectByIdAndStoreIdAndUserId(couponId, storeId, loginUser.getId());
        }

        if(discId != null){
            mkStoreTicketDiscount = apiMkStoreTicketDiscountService.queryDiscObjectByUserId(discId, loginUser.getId());
        }
        if(mkStoreTicketDiscount != null){
            String inValidDate = "";
            if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_00.getItem())){
                String startDate = DateUtils.format(mkStoreTicketDiscount.getFixBegTime(), DateUtils.PATTERN_YYYY_MM_DD_HH_MM);
                String endDate = DateUtils.format(mkStoreTicketDiscount.getFixEndTime(), DateUtils.PATTERN_YYYY_MM_DD_HH_MM);
                inValidDate = startDate + " 至 " + endDate;
            }
            if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_01.getItem())){
                if(mkStoreTicketDiscount.getAddTime() == null){
                    String postponeNum = com.kmall.common.utils.StringUtils.isNotEmpty(mkStoreTicketDiscount.getPostponeNum()) ? mkStoreTicketDiscount.getPostponeNum() : "0";
                    String validDayNum = com.kmall.common.utils.StringUtils.isNotEmpty(mkStoreTicketDiscount.getValidDayNum()) ? mkStoreTicketDiscount.getValidDayNum() : "0";
                    inValidDate = "领取" + postponeNum + "天后 " + validDayNum + "天内有效";
                }else {
                    String startDate = DateUtils.format(mkStoreTicketDiscount.getAddTime(), DateUtils.PATTERN_YYYY_MM_DD_HH_MM);
                    String endDate = DateUtils.format(mkStoreTicketDiscount.getEndTime(), DateUtils.PATTERN_YYYY_MM_DD_HH_MM);
                    inValidDate = startDate + " 至 " + endDate;
                }
            }
            mkStoreTicketDiscount.setInValidTime(inValidDate);
            mkStoreTicketDiscount.setIsReceive(getReceive(mkStoreTicketDiscount,loginUser));

            Integer storeTopicId = mkStoreTicketDiscount.getStoreTopicId();
            //记录活动营销统计访客量数据
            apiMkStoreTopicStatService.saveStoreTopicStatByVisitData(storeTopicId, storeId, getUserId());
        }
        return toResponsSuccess(mkStoreTicketDiscount);
    }

    /**
     * 详情页查询该商品可支持的优惠券
     */
    @GetMapping("getDiscountByGoodsIdList")
    public Object getDiscountByGoodsIdList(@LoginUser UserVo loginUser, Integer storeId, Integer goodsId,
                                           @RequestParam(value = "page", defaultValue = "1") Integer page,
                                           @RequestParam(value = "size", defaultValue = "10") Integer size) {
        List<MkStoreTicketDiscountVo> discountVoList = apiMkStoreTicketDiscountService.queryStoreDiscountByGoodsId(storeId,getUserId(),goodsId);
        List<MkStoreTicketDiscountVo> resultDiscountVoList = new ArrayList<>();
        if(size <= discountVoList.size()) {
            for (int i = 0; i < size; i++) {
                MkStoreTicketDiscountVo discountEntity = discountVoList.get(i);
                //优惠券是否可操作 1：不可操作 0：可操作
                discountEntity.setIsReceive(getReceive(discountEntity,loginUser));
                discountEntity.setInValidTime(setInvalidTime(discountEntity));
                resultDiscountVoList.add(discountEntity);
            }
        }
        if(size > discountVoList.size()) {
            for (MkStoreTicketDiscountVo discountEntity: discountVoList) {
                //优惠券是否可操作 1：不可操作 0：可操作
                discountEntity.setIsReceive(getReceive(discountEntity,loginUser));
                discountEntity.setInValidTime(setInvalidTime(discountEntity));
                resultDiscountVoList.add(discountEntity);
            }
        }
        return toResponsSuccess(resultDiscountVoList);
    }

    /**
     * 优惠券是否可操作 1：不可操作 0：可操作
     * @param discountEntity
     * @param loginUser
     * @return
     */
    private Integer getReceive(MkStoreTicketDiscountVo discountEntity, UserVo loginUser){
        Integer isReceive;
        if(discountEntity.getTicketNum() == 0){
            isReceive = 1;//库存为0则不可领取了
        }else{
            //获取优惠券每人可领取张数，与已领取数比较
            if(discountEntity.getLimitNum() == discountEntity.getReceiveCount()){
                isReceive = 1;//每人限领张数与已领取数相等则不可领取了
            }else{
                isReceive = 0;
            }
        }

        return isReceive;
    }

    /**
     * 查看当前用户已领取的且订单商品所支持的优惠券列表
     */
    @GetMapping("getDiscountByCheckCartList")
    public Object getDiscountByCheckCartList(@LoginUser UserVo loginUser, Integer storeId, String checkCart,String bizType, Long goodsId, Integer number) {
        CheckOutDto checkOutDto = new CheckOutDto();
        checkOutDto.setCheckCart(checkCart);
        //商品id不为空，则提交订单是从商品详情页立即购买过来的
        if(goodsId != null){
            checkOutDto.setGoodsId(goodsId);
            checkOutDto.setNumber(number);
        }
        checkOutDto.setLoginUser(loginUser);
        //获取要购买的商品
        Map<String, Object> cartData = apiCartService.getCartMoney(loginUser, checkOutDto, Long.valueOf(storeId));

        List<CartVo> checkedGoodsList = new ArrayList();
        List<CartVo> cartGoodsList = (List<CartVo>) cartData.get("cartList");
        for (CartVo cartEntity : cartGoodsList) {
            if (cartEntity.getChecked() == 1) {
                if(bizType.equalsIgnoreCase(cartEntity.getGoodsBizType())) {
                    checkedGoodsList.add(cartEntity);
                }
            }
        }
        //计算订单的费用 商品总价
        BigDecimal goodsTotalPrice = (BigDecimal) ((HashMap) cartData.get("cartTotal")).get("checkedGoodsAmount");
        BigDecimal goodsTotalPrice00 = (BigDecimal) ((HashMap) cartData.get("cartTotal")).get("checkedGoodsAmount00");
        BigDecimal goodsTotalPrice02 = (BigDecimal) ((HashMap) cartData.get("cartTotal")).get("checkedGoodsAmount02");
        BigDecimal goodsTotalPrice10 = (BigDecimal) ((HashMap) cartData.get("cartTotal")).get("checkedGoodsAmount10");
        BigDecimal goodsTotalPrice11 = (BigDecimal) ((HashMap) cartData.get("cartTotal")).get("checkedGoodsAmount11");
        if(bizType.equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
            goodsTotalPrice = goodsTotalPrice00;
        }else if(bizType.equalsIgnoreCase(Dict.orderBizType.item_02.getItem())){
            goodsTotalPrice = goodsTotalPrice02;
        }else if(bizType.equalsIgnoreCase(Dict.orderBizType.item_10.getItem())){
            goodsTotalPrice = goodsTotalPrice10;
        }else if(bizType.equalsIgnoreCase(Dict.orderBizType.item_11.getItem())){
            goodsTotalPrice = goodsTotalPrice11;
        }
        //获取可用的优惠券信息 抵用券
        UserCouponDto userCouponDto = new UserCouponDto();
        userCouponDto.setUserId(loginUser.getId());
        userCouponDto.setStoreId(getStoreId());
        userCouponDto.setGoodsTotalPrice(goodsTotalPrice);
        userCouponDto.setCartGoodsList(checkedGoodsList);
        userCouponDto.setBizType(bizType);
        List<UserCouponVo> enableCouponList = apiUserCouponService.matchUserCouponList(userCouponDto);
        return toResponsSuccess(enableCouponList);
    }
}
