package com.kmall.admin.service.impl.mk.store;

import com.kmall.admin.dao.AdDao;
import com.kmall.admin.dao.OrderDao;
import com.kmall.admin.dao.StoreDao;
import com.kmall.admin.dao.UserCouponDao;
import com.kmall.admin.dao.mk.store.MkStoreTicketDiscountDao;
import com.kmall.admin.dao.mk.store.MkStoreTicketDiscountGoodsDao;
import com.kmall.admin.dao.mk.store.MkStoreTicketGoodsTempDao;
import com.kmall.admin.dao.mk.store.StoreTopicDao;
import com.kmall.admin.entity.AdEntity;
import com.kmall.admin.entity.OrderEntity;
import com.kmall.admin.entity.StoreEntity;
import com.kmall.admin.entity.UserCouponEntity;
import com.kmall.admin.entity.mk.store.MkStoreTicketDiscountEntity;
import com.kmall.admin.entity.mk.store.MkStoreTicketDiscountGoodsEntity;
import com.kmall.admin.entity.mk.store.MkStoreTicketGoodsTempEntity;
import com.kmall.admin.entity.mk.store.StoreTopicEntity;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.admin.service.mk.store.MkStoreTicketDiscountService;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.api.entity.UserCouponVo;
import com.kmall.api.service.wxGlobal.ApiWxGlobalPayService;
import com.kmall.common.constant.Dict;
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 org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 门店优惠券活动Service实现类
 *
 * @author emato
 * @email admin@qhdswl.com
 * @date 2019-05-07 16:06:28
 */
@Service("mkStoreTicketDiscountService")
public class MkStoreTicketDiscountServiceImpl implements MkStoreTicketDiscountService {
    @Autowired
    private MkStoreTicketDiscountDao mkStoreTicketDiscountDao;
    @Autowired
    private StoreTopicDao storeTopicDao;
    @Autowired
    private MkStoreTicketGoodsTempDao mkStoreTicketGoodsTempDao;
    @Autowired
    private MkStoreTicketDiscountGoodsDao mkStoreTicketDiscountGoodsDao;
    @Autowired
    private StoreDao storeDao;
    @Autowired
    private AdDao adDao;
    @Autowired
    private UserCouponDao userCouponDao;
    @Autowired
    private OrderDao orderDao;

    @Override
    public MkStoreTicketDiscountEntity queryObject(Integer tickDiscId) {
        return mkStoreTicketDiscountDao.queryObject(tickDiscId);
    }

    @Override
    public List<MkStoreTicketDiscountEntity> queryList(Map<String, Object> map) {
        return mkStoreTicketDiscountDao.queryList(map);
    }

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

    @Transactional
    @Override
    public int save(MkStoreTicketDiscountEntity mkStoreTicketDiscount) {
        if(!StringUtils.isNotEmpty(String.valueOf(mkStoreTicketDiscount.getLimitNum()))){
            mkStoreTicketDiscount.setLimitNum(1);
        }
        StoreEntity storeEntity = storeDao.queryObject(mkStoreTicketDiscount.getStoreId());
        if(storeEntity == null){
            throw new RRException("门店信息不存在");
        }else{
            mkStoreTicketDiscount.setStoreName(storeEntity.getStoreName());
        }
        SysUserEntity user = ShiroUtils.getUserEntity();
        List<MkStoreTicketGoodsTempEntity> tempEntityList = new ArrayList<>();
        if(!mkStoreTicketDiscount.getApplyType().equalsIgnoreCase(Dict.applyType.item_00.getItem())){
            //根据唯一id、门店id、试用商品类型、是否有效查询临时表是否有数据，没有数据则提示“指定商品参与商品数据为空，请选择”“指定商品不参与商品数据为空，请选择”
            MkStoreTicketGoodsTempEntity entity = new MkStoreTicketGoodsTempEntity();
            entity.setStoreId(mkStoreTicketDiscount.getStoreId());
//            entity.setApplyType(mkStoreTicketDiscount.getApplyType());
            entity.setGuid(mkStoreTicketDiscount.getGuid());
            entity.setIsValid(Dict.isValid.item_0.getItem());
            entity.setIsButtonCannel(Dict.isValid.item_0.getItem());
            tempEntityList = mkStoreTicketGoodsTempDao.queryGoodsTempByIsValid(entity);
            if(tempEntityList.size() == 0){
                if(Dict.applyType.item_01.getItem().equalsIgnoreCase(mkStoreTicketDiscount.getApplyType())) {
                    throw new RRException("指定商品参与商品数据为空，请选择");
                }
                if(Dict.applyType.item_02.getItem().equalsIgnoreCase(mkStoreTicketDiscount.getApplyType())) {
                    throw new RRException("指定商品不参与商品数据为空，请选择");
                }
            }
        }
        StoreTopicEntity storeTopicEntity = saveStoreTopic(mkStoreTicketDiscount, user);
        if(storeTopicEntity != null) {
            mkStoreTicketDiscount.setCreateTime(new Date());
            mkStoreTicketDiscount.setCreaterSn(user.getUsername());
            mkStoreTicketDiscount.setModTime(new Date());
            mkStoreTicketDiscount.setModerSn(user.getUsername());
            mkStoreTicketDiscount.setStoreTopicId(storeTopicEntity.getId());
            mkStoreTicketDiscount.setIsPast(Dict.isPast.item_0.getItem());//未过期
            /*//开始时间大于当前时间，则结束状态为未开始
            if(mkStoreTicketDiscount.getFixBegTime().getTime() > new Date().getTime()){
                mkStoreTicketDiscount.setIsPast(Dict.isPast.item_2.getItem());
            }
            //开始时间小于当前时间，则结束状态为进行中
            if(mkStoreTicketDiscount.getFixBegTime().getTime() < new Date().getTime()){
                mkStoreTicketDiscount.setIsPast(Dict.isPast.item_0.getItem());
            }*/
            mkStoreTicketDiscountDao.save(mkStoreTicketDiscount);
            if(tempEntityList.size() > 0){
                for(MkStoreTicketGoodsTempEntity tempEntity: tempEntityList) {
                    MkStoreTicketDiscountGoodsEntity discountGoodsEntity = new MkStoreTicketDiscountGoodsEntity();
                    discountGoodsEntity.setTickDiscId(mkStoreTicketDiscount.getTickDiscId());
                    discountGoodsEntity.setStoreRelaId(tempEntity.getStoreRelaId());
                    discountGoodsEntity.setApplyType(mkStoreTicketDiscount.getApplyType());
                    discountGoodsEntity.setIsValid(Dict.isValid.item_0.getItem());
                    discountGoodsEntity.setCreaterSn(user.getUsername());
                    discountGoodsEntity.setCreateTime(new Date());
                    discountGoodsEntity.setModerSn(user.getUsername());
                    discountGoodsEntity.setModTime(new Date());
                    mkStoreTicketDiscountGoodsDao.save(discountGoodsEntity);

                    MkStoreTicketGoodsTempEntity entity = new MkStoreTicketGoodsTempEntity();
                    entity.setDiscGoodTempId(tempEntity.getDiscGoodTempId());
                    entity.setApplyType(mkStoreTicketDiscount.getApplyType());
                    mkStoreTicketGoodsTempDao.update(entity);
                }
            }
//            是否展示在小程序门店首页广告栏，为1则新增广告信息广告位
            if(mkStoreTicketDiscount.getIsStoreShow().equalsIgnoreCase("1")) {
                AdEntity adEntity = new AdEntity();
                adEntity.setStoreId(mkStoreTicketDiscount.getStoreId());
                adEntity.setContent(mkStoreTicketDiscount.getName());
                adEntity.setMerchSn(storeEntity.getMerchSn());
                adEntity.setImageUrl(mkStoreTicketDiscount.getStoreLogoUrl());
                adEntity.setName(mkStoreTicketDiscount.getName());
                adEntity.setLink("/pages/ucenter/couponDetail/couponDetail?discId=" + mkStoreTicketDiscount.getTickDiscId() + "&&storeId=" + mkStoreTicketDiscount.getStoreId() + "&&isShare==0");
                adEntity.setEnabled(1);
                adEntity.setAdPositionId(1);
                adEntity.setMediaType(1);
                adEntity.setTickDiscId(mkStoreTicketDiscount.getTickDiscId());
                adDao.save(adEntity);
            }
            return 1;
        }else {
            return 0;
        }
    }

    @Transactional
    @Override
    public int update(MkStoreTicketDiscountEntity mkStoreTicketDiscount) {
        MkStoreTicketDiscountEntity discountEntity = queryObject(mkStoreTicketDiscount.getTickDiscId());
        if(discountEntity == null){
            throw new RRException("优惠券信息不存在");
        }
        if(mkStoreTicketDiscount.getFixEndTime()!= null){
            if(mkStoreTicketDiscount.getFixEndTime().getTime() < discountEntity.getFixEndTime().getTime()){
                throw new RRException("不可缩短优惠券有效期");
            }
        }
        if(!StringUtils.isNotEmpty(String.valueOf(mkStoreTicketDiscount.getLimitNum()))){
            mkStoreTicketDiscount.setLimitNum(1);
        }
        StoreEntity storeEntity = storeDao.queryObject(mkStoreTicketDiscount.getStoreId());
        if(storeEntity == null){
            throw new RRException("门店信息不存在");
        }else{
            mkStoreTicketDiscount.setStoreName(storeEntity.getStoreName());
        }

        SysUserEntity user = ShiroUtils.getUserEntity();
        List<MkStoreTicketGoodsTempEntity> tempEntityList = new ArrayList<>();
        if(!mkStoreTicketDiscount.getApplyType().equalsIgnoreCase(Dict.applyType.item_00.getItem())){
            //根据唯一id、门店id、试用商品类型、是否有效查询临时表是否有数据，没有数据则提示“指定商品参与商品数据为空，请选择”“指定商品不参与商品数据为空，请选择”
            MkStoreTicketGoodsTempEntity entity = new MkStoreTicketGoodsTempEntity();
            entity.setStoreId(mkStoreTicketDiscount.getStoreId());
//            entity.setApplyType(mkStoreTicketDiscount.getApplyType());
            entity.setIsValid(Dict.isValid.item_0.getItem());
            entity.setIsButtonCannel(Dict.isValid.item_0.getItem());
            entity.setGuid(mkStoreTicketDiscount.getGuid());
            tempEntityList = mkStoreTicketGoodsTempDao.queryGoodsTempByIsValid(entity);
            if(tempEntityList.size() == 0){
                if(Dict.applyType.item_02.getItem().equalsIgnoreCase(mkStoreTicketDiscount.getApplyType())) {
                    throw new RRException("指定商品不参与商品数据为空，请选择");
                }
                if(Dict.applyType.item_01.getItem().equalsIgnoreCase(mkStoreTicketDiscount.getApplyType())) {
                    throw new RRException("指定商品参与商品数据为空，请选择");
                }
            }
        }
        deleteTemp(mkStoreTicketDiscount);
        StoreTopicEntity storeTopicEntity = storeTopicDao.queryObject(mkStoreTicketDiscount.getStoreTopicId());
        if(storeTopicEntity != null) {
            storeTopicEntity.setTitle(mkStoreTicketDiscount.getName());
            storeTopicDao.update(storeTopicEntity);

            mkStoreTicketDiscount.setCreateTime(new Date());
            mkStoreTicketDiscount.setCreaterSn(user.getUsername());
            mkStoreTicketDiscount.setModTime(new Date());
            mkStoreTicketDiscount.setModerSn(user.getUsername());
            /*//开始时间大于当前时间，则结束状态为未开始
            if(mkStoreTicketDiscount.getFixBegTime().getTime() > new Date().getTime()){
                mkStoreTicketDiscount.setIsPast(Dict.isPast.item_2.getItem());
            }
            //开始时间小于当前时间，则结束状态为进行中
            if(mkStoreTicketDiscount.getFixBegTime().getTime() < new Date().getTime()){
                mkStoreTicketDiscount.setIsPast(Dict.isPast.item_0.getItem());
            }*/
            mkStoreTicketDiscountDao.update(mkStoreTicketDiscount);
            if(tempEntityList.size() > 0){
                mkStoreTicketDiscountGoodsDao.deleteByTickDistId(mkStoreTicketDiscount.getTickDiscId());

                for (MkStoreTicketGoodsTempEntity tempEntity : tempEntityList) {
                           /* MkStoreTicketDiscountGoodsEntity ticketDiscountEntity = new MkStoreTicketDiscountGoodsEntity();
                            ticketDiscountEntity.setTickDiscId(mkStoreTicketDiscount.getTickDiscId());
                            ticketDiscountEntity.setApplyType(mkStoreTicketDiscount.getApplyType());
                            ticketDiscountEntity.setStoreRelaId(tempEntity.getStoreRelaId());
                            MkStoreTicketDiscountGoodsEntity ticketDiscountGoodsEntity = mkStoreTicketDiscountGoodsDao.queryObjectByStoreReal(ticketDiscountEntity);*/
                    MkStoreTicketDiscountGoodsEntity discountGoodsEntity = new MkStoreTicketDiscountGoodsEntity();
                    discountGoodsEntity.setStoreRelaId(tempEntity.getStoreRelaId());
                    discountGoodsEntity.setApplyType(mkStoreTicketDiscount.getApplyType());
                    discountGoodsEntity.setCreaterSn(user.getUsername());
                    discountGoodsEntity.setCreateTime(new Date());
                    discountGoodsEntity.setModerSn(user.getUsername());
                    discountGoodsEntity.setModTime(new Date());
                    discountGoodsEntity.setTickDiscId(mkStoreTicketDiscount.getTickDiscId());
                    discountGoodsEntity.setIsValid(Dict.isValid.item_0.getItem());
                    mkStoreTicketDiscountGoodsDao.save(discountGoodsEntity);

                    MkStoreTicketGoodsTempEntity entity = new MkStoreTicketGoodsTempEntity();
                    entity.setDiscGoodTempId(tempEntity.getDiscGoodTempId());
                    entity.setApplyType(mkStoreTicketDiscount.getApplyType());
                    mkStoreTicketGoodsTempDao.update(entity);
                }
            }
            AdEntity ad = adDao.queryAdByTickDiscId(mkStoreTicketDiscount.getTickDiscId());
//            是否展示在小程序门店首页广告栏，为1则新增广告信息广告位
            if(mkStoreTicketDiscount.getIsStoreShow().equalsIgnoreCase("1")) {
                AdEntity adEntity = new AdEntity();
                adEntity.setContent(mkStoreTicketDiscount.getName());
                adEntity.setImageUrl(mkStoreTicketDiscount.getStoreLogoUrl());
                adEntity.setName(mkStoreTicketDiscount.getName());
                adEntity.setLink("/pages/ucenter/couponDetail/couponDetail?discId=" + mkStoreTicketDiscount.getTickDiscId() + "&&storeId=" + mkStoreTicketDiscount.getStoreId() + "&&isShare==0");
                adEntity.setEnabled(1);
                if(ad != null){
                    adEntity.setId(ad.getId());
                    adDao.update(adEntity);
                }else{
                    adEntity.setStoreId(mkStoreTicketDiscount.getStoreId());
                    adEntity.setMerchSn(storeEntity.getMerchSn());
                    adEntity.setAdPositionId(1);
                    adEntity.setMediaType(1);
                    adEntity.setTickDiscId(mkStoreTicketDiscount.getTickDiscId());
                    adDao.save(adEntity);
                }
            }
//            为0则将已有的广告位隐藏
            if(mkStoreTicketDiscount.getIsStoreShow().equalsIgnoreCase("0")) {
                if(ad != null) {
                    AdEntity adEntity = new AdEntity();
                    adEntity.setEnabled(0);
                    adEntity.setId(ad.getId());
                    adDao.update(adEntity);
                }
            }
            return 1;
        }else {
            return 0;
        }
    }

    private void deleteTemp(MkStoreTicketDiscountEntity mkStoreTicketDiscount){
        MkStoreTicketGoodsTempEntity entity = new MkStoreTicketGoodsTempEntity();
        entity.setStoreId(mkStoreTicketDiscount.getStoreId());
        entity.setApplyType(mkStoreTicketDiscount.getApplyType());
        entity.setIsButtonCannel(Dict.isValid.item_1.getItem());
        entity.setGuid(mkStoreTicketDiscount.getGuid());
        List<MkStoreTicketGoodsTempEntity> tempEntityList = mkStoreTicketGoodsTempDao.queryGoodsTempByIsValid(entity);
        Integer[] tempIds = new Integer[tempEntityList.size()];
        for (int i=0; i<tempEntityList.size(); i++) {
            tempIds[i] = tempEntityList.get(i).getDiscGoodTempId();
        }
        if(tempIds.length > 0){
            mkStoreTicketGoodsTempDao.deleteBatch(tempIds);
        }
    }

    private StoreTopicEntity saveStoreTopic(MkStoreTicketDiscountEntity mkStoreTicketDiscount, SysUserEntity user){
        StoreTopicEntity storeTopicEntity = new StoreTopicEntity();
        storeTopicEntity.setTitle(mkStoreTicketDiscount.getName());
        storeTopicEntity.setContent(mkStoreTicketDiscount.getUseNoti());
        storeTopicEntity.setSubtitle(mkStoreTicketDiscount.getTickDiscSubTitle());
        storeTopicEntity.setStoreId(mkStoreTicketDiscount.getStoreId());
        storeTopicEntity.setThirdMerchSn(mkStoreTicketDiscount.getThirdMerchSn());
        storeTopicEntity.setIsValid("0");
        storeTopicEntity.setCreateTime(new Date());
        storeTopicEntity.setCreaterSn(user.getUsername());
        storeTopicEntity.setModTime(new Date());
        storeTopicEntity.setModerSn(user.getUsername());
        storeTopicEntity.setPromTypeId(6);
        storeTopicDao.save(storeTopicEntity);
        return storeTopicEntity;
    }

    @Override
    public int delete(Integer tickDiscId) {
        return mkStoreTicketDiscountDao.delete(tickDiscId);
    }

    @Transactional
    @Override
    public int deleteBatch(Integer[]tickDiscIds) {
        if(tickDiscIds != null && tickDiscIds.length > 0) {
            Integer[] storeTopicIds = new Integer[tickDiscIds.length];
            for (int i = 0; i < tickDiscIds.length; i++) {
                MkStoreTicketDiscountEntity discountEntity = mkStoreTicketDiscountDao.queryObject(tickDiscIds[i]);
                if (discountEntity != null) {
                    storeTopicIds[i] = discountEntity.getStoreTopicId();
                    List<UserCouponEntity> userCouponEntityList = userCouponDao.queryByStoreTopicId(discountEntity.getStoreTopicId());
                    if (userCouponEntityList != null && userCouponEntityList.size() > 0){
                        if(userCouponEntityList.size() > 0){
                            throw new RRException("该优惠券【"+discountEntity.getName()+"】已有"+userCouponEntityList.size()+"个用户领取，不能删除");
                        }
                    }
                    List<OrderEntity> orderEntityList = orderDao.queryObjectByActivityId(discountEntity.getStoreTopicId());
                    if (orderEntityList != null && orderEntityList.size() > 0){
                        if(orderEntityList.size() > 0){
                            throw new RRException("该优惠券【"+discountEntity.getName()+"】已生成"+orderEntityList.size()+"条订单信息，不能删除");
                        }
                    }
                    StoreTopicEntity storeTopicEntity = new StoreTopicEntity();
                    storeTopicEntity.setId(discountEntity.getStoreTopicId());
                    storeTopicEntity.setIsValid(Dict.isValid.item_1.getItem());
                    storeTopicDao.update(storeTopicEntity);
                }
            }
//            storeTopicDao.deleteBatch(storeTopicIds);
        }
        return mkStoreTicketDiscountDao.deleteBatch(tickDiscIds);
    }
}
