package com.iamberry.wechat.service;

import com.iamberry.wechat.core.entity.activity.ActivityDate;
import com.iamberry.wechat.core.entity.admin.FullReduction;
import com.iamberry.wechat.core.entity.cart.CartDto;
import com.iamberry.wechat.core.entity.eo.*;
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.eo.SettlementGiftService;
import com.iamberry.wechat.face.member.MemberService;
import org.apache.poi.ss.formula.functions.T;
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.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 上朵活动类
 */
@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 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(236).getRuleDesc();
        String end = systemService.selectOneShopRuleByIdDynamic(237).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();
    }

    /**
     * 获取所有优惠信息
     * @return 期限内true；
     */
    public void preferential(List<CartDto> cartDtoList){
        if(!isActivity()){
            return ;
        }
        Promotions promotions = promotionsService.getPromotionsListByTime();
        this.giftCartPriv(cartDtoList,promotions);
        this.getColorSpikePriv(cartDtoList,promotions);
    }

    /**
     * 赠送赠品
     * @param cartDtoList
     */
    public void giftCart(List<CartDto> cartDtoList){
        if(!isActivity()){
            return;
        }
        Promotions promotions = promotionsService.getPromotionsListByTime();
        this.giftCartPriv(cartDtoList,promotions);
    }

    /**
     * 查询秒杀
     * @param colorId
     */
    public Spike getColorSpike(Integer colorId){
        Spike spk = new Spike();
        if(!isActivity()){
            return null;
        }
        Promotions promotions = promotionsService.getPromotionsListByTime();
        return this.getColorSpikePriv(colorId,promotions);
    }
    /**
     * 查询秒杀
     * @param list
     */
    public void getColorSpike(List list){
        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);
                        cartDto.setProductIsSpell(1);
                        cartDto.setColorSpellAmount(0);

                        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);

                        giftPool.setGiftPoolStock(giftPool.getGiftPoolStock()-num);

                        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(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.setProductIntroduceImg(product.getColorImg());
					carD.setProductRemark(product.getColorPresent());
					carD.setProductColor(product.getColorName());
					carD.setColorImg(product.getColorImg());
					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 null;
        }
        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;
        }
    }

    /**
     * 查询用户是否满赠优惠
     * @return true/false；
     */
    public boolean getFullReduction(String openid){
        if(openid == null || openid.equals("")){
            return false;
        }
        FullReduction fullReduction = memberService.getFullReduction(openid);
        if(fullReduction == null){
            return false;
        }else{
            return true;
        }
    }
}
