package com.iamberry.wechat.service;

import com.iamberry.wechat.core.entity.activity.ActivityDate;
import com.iamberry.wechat.core.entity.cart.CartDto;
import com.iamberry.wechat.core.entity.eo.*;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.eo.PromotionsService;
import com.iamberry.wechat.face.member.MemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 上朵活动类
 */
@Component
public class ActivityUtil {

    Logger logger = LoggerFactory.getLogger(ActivityUtil.class);

    @Autowired
    private SystemService systemService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private PromotionsService promotionsService;
    @Autowired
    private ProductInfoService productInfoService;

    private final static SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取日期
     * @return
     */
    private ActivityDate initDate(){
        ActivityDate activityDate  = new ActivityDate();
        activityDate.setStatus(false);
        String begin = systemService.selectOneShopRuleByIdDynamic(256).getRuleDesc();
        String end = systemService.selectOneShopRuleByIdDynamic(257).getRuleDesc();
        try {
            activityDate.setBeginDate(sd.parse(begin));
            activityDate.setEndDate(sd.parse(end));
        } catch (ParseException e) {
            logger.info("活动日期转换错误！");
            e.printStackTrace();
            activityDate.setStatus(false);
            return activityDate;
        }
        Date date = new Date();
        if (activityDate.getBeginDate().before(date) && date.before(activityDate.getEndDate())){  //beginDate 比 date 早? true ：false
            activityDate.setStatus(true);
        }
        return activityDate;
    }

    /**
     * 判断是否在注销时间内
     * @return 期限内true；
     */
    public boolean isActivity(){
        ActivityDate activityDate = initDate();
        return activityDate.isStatus();
    }

    /**
     * 判断是否在注销时间内
     * @return 期限内true；
     */
    public ActivityDate getActivityDate(){
        ActivityDate activityDate = initDate();
        if(!activityDate.isStatus()){
            return activityDate;
        }
        Promotions promotions = getAllPromotions();
        activityDate.setPromotions(promotions);
        return activityDate;
    }

    /**
     * 获取所有优惠信息
     * @return 期限内true；
     */
    public Promotions getAllPromotions(){
        if(!isActivity()){
            return null;
        }
        return promotionsService.getPromotionsListByTime();
    }

    /**
     * 订单结算满足优惠
     * @param cartDtoList
     */
    public void giftCart(List<CartDto> cartDtoList){
        if(!isActivity()){
            return;
        }
        Promotions promotions = promotionsService.getPromotionsListByTime();
        this.giftCartPriv(cartDtoList,promotions);
    }

    /**
     * 赠送赠品+秒杀减价
     * @param cartDtoList
     */
    public void preferential(List<CartDto> cartDtoList){
        if(!isActivity()){
            return;
        }
        Promotions promotions = promotionsService.getPromotionsListByTime();
        this.getColorSpikePriv(cartDtoList,promotions); //必须要先执行秒杀，否则秒杀与赠品想冲突
        this.giftCartPriv(cartDtoList,promotions);
    }

    /**
     * 查询秒杀
     * @param colorId
     */
    public Spike getColorSpike(Integer colorId){
        Spike spk = new Spike();
        if(!isActivity()){
            return null;
        }
        Promotions promotions = promotionsService.getPromotionsListByTime();
        return getColorSpikePriv(colorId,promotions);
    }

    /**
     * 查询秒杀
     * @param list
     */
    public void getColorSpike(List list){
        Spike spk = new Spike();
        if(!isActivity()){
            return;
        }
        Promotions promotions = promotionsService.getPromotionsListByTime();
        this.getColorSpikePriv(list,promotions);
    }


    /**
     * 赠送赠品 - 私有
     * @param cartDtoList
     */
    public void giftCartPriv(List<CartDto> cartDtoList,Promotions promotions){
        if(promotions == null){
            return;
        }
        List<CartDto> giftList = new ArrayList<>();
        for (SettlementGift settlementGift:promotions.getSettlementGiftList()) {
            boolean isHaveColor = false;
            for (CartDto cd:cartDtoList) {
                Integer cdNum = 0;
                for (GiftCondition giftCondition:settlementGift.getGiftConditionList()) {
                    if(cd.getCartColorId() == giftCondition.getGiftConditionFillColorId()){//添加赠送产品
                        isHaveColor = true;
                        cdNum = cd.getCartNum();
                    }
                }
                if(isHaveColor){
                    String giftPoolRelationDesc = "";
                    for (GiftPool giftPool:settlementGift.getGiftPoolList()) {
                        CartDto cartDto = new CartDto();

                        Integer num = giftPool.getGiftPoolNum();
                        if(giftPool.getGiftPoolNum() < 1){	//判断赠送数量，大于0就用该数量
                            num = cdNum;
                        }
                        if(num > giftPool.getGiftPoolStock()){
                            continue;
                        }

                        if(!"".equals(giftPoolRelationDesc)){
                            if(1 == giftPool.getGiftPoolRelation() || !giftPoolRelationDesc.equals(giftPool.getGiftPoolRelationDesc())){
                                continue;
                            }
                        }
                        cartDto.setCartColorId(giftPool.getGiftPoolColorId());
                        cartDto.setCartNum(num);
                        cartDto.setProductDiscount(giftPool.getGiftPoolPrice());
                        cartDto.setProductPrice(giftPool.getGiftPoolPrice());
                        cartDto.setTotal(giftPool.getGiftPoolPrice()*num);

                        List<ItemGift> itemGiftList = new ArrayList<>();
                        ItemGift itemGift = new ItemGift();
                        itemGift.setGiftPoolId(giftPool.getGiftPoolId());
                        itemGift.setItemGiftNum(num);
                        itemGiftList.add(itemGift);
                        cartDto.setItemGiftList(itemGiftList);

                        giftList.add(cartDto);

                        if( 1 == giftPool.getGiftPoolRelation()){
                            break;
                        }else{
                            giftPoolRelationDesc = giftPool.getGiftPoolRelationDesc();
                        }
                    }
                }
            }
        }

        List<CartDto> newGiftList = new ArrayList<>();
        if(giftList != null && giftList.size() > 0){
            for (CartDto carD:giftList) {
                boolean fl = false;
                for(CartDto newCarD:newGiftList) {
                    if(Objects.equals(newCarD.getCartColorId(), carD.getCartColorId())){	//赠品相同，合并
                        fl = true;
                        newCarD.setCartNum(newCarD.getCartNum() + carD.getCartNum());
                        newCarD.setProductDiscount(newCarD.getProductDiscount() +  carD.getProductDiscount());
                        newCarD.setProductPrice( newCarD.getProductPrice() + carD.getProductPrice());
                        newCarD.setTotal(newCarD.getTotal() + carD.getTotal());
                        if(carD.getItemGiftList() != null && carD.getItemGiftList().size() > 0){
                            if(newCarD.getItemGiftList() != null && newCarD.getItemGiftList().size() > 0){
                                List<ItemGift> itemIG = new ArrayList<>();
                                for (ItemGift carDIG:carD.getItemGiftList()) {
                                    for (ItemGift newCarDIG:newCarD.getItemGiftList()) {
                                        if(carDIG.getGiftPoolId() == newCarDIG.getGiftPoolId()){
                                            newCarDIG.setItemGiftNum(newCarDIG.getItemGiftNum()+carDIG.getItemGiftNum());
                                        }
                                    }
                                }
                            }else{
                                newCarD.setItemGiftList(carD.getItemGiftList());
                            }
                        }
                    }
                }
                if(!fl){
                    Product product = productInfoService.selectProductByColorId(carD.getCartColorId());
                    carD.setCartId(1);
                    carD.setCartProductId(product.getProductId());
                    carD.setProductName("【赠品】"+product.getProductName());
                    carD.setProductType(product.getProductTypeId());
                    carD.setProductStatus(1);
                    carD.setColorStatus(1);
                    carD.setProductIntroduceImg(product.getColorProductPic());
                    carD.setProductRemark(product.getColorPresent());
                    carD.setProductColor(product.getColorName());
                    carD.setProductIntroduceImg(product.getColorProductPic());	//productIntroduceImg
                    carD.setProductChildType(product.getProductChildTypeId());	//productChildType
                    carD.setCartIsSource(1);
                    carD.setColorType(1);
                    CartDto newCartDto = new CartDto();
                    BeanUtils.copyProperties(carD,newCartDto);
                    newGiftList.add(newCartDto);
                }
            }
        }
        if(newGiftList != null && newGiftList.size() > 0){
            cartDtoList.addAll(newGiftList);
        }
    }

    /**
     * 查询秒杀
     * @param colorId
     */
    public Spike getColorSpikePriv(Integer colorId,Promotions promotions){
        Spike spk = new Spike();
        if(promotions == null){
            return spk;
        }
        for (Spike spike:promotions.getSpikeList()) {
            if(colorId == spike.getSpikeColorId()){
                spk = spike;
            }
        }
        return spk;
    }

    /**
     * 查询秒杀
     */
    public void getColorSpikePriv(List list,Promotions promotions){
        if(promotions == null){
            return;
        }
        if(list==null || list.size()<1){
            return;
        }
        String nowClass = list.get(0).getClass().getName();
        switch (nowClass){
            case ("com.iamberry.wechat.core.entity.product.ProductColor"):
                for (Object obj:list) {
                    for (Spike spike:promotions.getSpikeList()) {
                        ProductColor productColor = (ProductColor) obj;
                        if(spike.getSpikeColorId() == productColor.getColorId()){
                            productColor.setColorPrice(spike.getSpikePrice());
                            productColor.setColorDiscount(spike.getSpikeDiscount());
                        }
                    }
                }
                break;
            case "com.iamberry.wechat.core.entity.cart.CartDto":
                for (Object obj:list) {
                    for (Spike spike:promotions.getSpikeList()) {
                        CartDto cd = (CartDto) obj;
                        if(spike.getSpikeColorId() == cd.getCartColorId()){
                            cd.setProductPrice(spike.getSpikePrice());
                            cd.setProductDiscount(spike.getSpikeDiscount());
                        }
                    }
                }
                break;
                default:break;
        }
    }


//    /**
//     * 添加一个免费滤芯
//     * @param cartDtoList
//     * @param openId
//     * @return  true 表示有赠送
//     * @return  false 表示未赠送
//     */
//    public boolean setVipPreFerential(List<CartDto> cartDtoList,String openId){
//        Member member = memberService.getMemberByUserOpenId(openId);
//        if(member.getUserVipPreferential() == 2 ){   //1.未兑换 2.已兑换
//            return false;
//        }
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(member.getUserVipDate());
//        calendar.add(Calendar.MONTH,3); //增加三个月   
//        if(!new Date().before(calendar.getTime())){
//            return false;
//        }
//        CartDto addCd = new CartDto();
//        boolean flag = false;
//        for (CartDto cd:cartDtoList) {
//            if(cd.getColorType() == 3){
//                 BeanUtils.copyProperties(cd,addCd);
//                 flag = true;
//                 break;
//            }
//        }
//        if(flag){
//            addCd.setProductDiscount(0);
//            addCd.setCartNum(1);
//            addCd.setProductName("【VIP赠送】"+addCd.getProductName());
//            cartDtoList.add(addCd);
//            return true;
//        }
//        return false;
//    }

}
