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

import com.kmall.admin.dao.mk.store.MkStoreTicketGoodsTempDao;
import com.kmall.admin.dto.CheckGoodsDto;
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.fromcomm.entity.SysUserEntity;
import com.kmall.admin.service.mk.store.MkStoreTicketDiscountGoodsService;
import com.kmall.admin.service.mk.store.MkStoreTicketDiscountService;
import com.kmall.admin.service.mk.store.MkStoreTicketGoodsTempService;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.RRException;
import com.kmall.common.utils.StringUtils;
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-09 17:33:29
 */
@Service("mkStoreTicketGoodsTempService")
public class MkStoreTicketGoodsTempServiceImpl implements MkStoreTicketGoodsTempService {
    @Autowired
    private MkStoreTicketGoodsTempDao mkStoreTicketGoodsTempDao;
    @Autowired
    private MkStoreTicketDiscountGoodsService mkStoreTicketDiscountGoodsService;
    @Autowired
    private MkStoreTicketDiscountService mkStoreTicketDiscountService;

    @Override
    public MkStoreTicketGoodsTempEntity queryObject(Integer discGoodTempId) {
        return mkStoreTicketGoodsTempDao.queryObject(discGoodTempId);
    }

    @Override
    public MkStoreTicketGoodsTempEntity queryGoodsTempByRealId(Integer discGoodTempId, String guid) {
        return mkStoreTicketGoodsTempDao.queryGoodsTempByRealId(discGoodTempId, guid);
    }

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

    @Override
    public List<MkStoreTicketGoodsTempEntity> queryAllDiscountByStoreId(Map<String, Object> map) {
        return mkStoreTicketGoodsTempDao.queryAllDiscountByStoreId(map);
    }

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

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

    @Override
    public int save(MkStoreTicketGoodsTempEntity mkStoreTicketGoodsTemp) {
        return mkStoreTicketGoodsTempDao.save(mkStoreTicketGoodsTemp);
    }

    @Override
    public int update(MkStoreTicketGoodsTempEntity mkStoreTicketGoodsTemp) {
        return mkStoreTicketGoodsTempDao.update(mkStoreTicketGoodsTemp);
    }

    @Override
    public int delete(Integer discGoodTempId) {
        return mkStoreTicketGoodsTempDao.delete(discGoodTempId);
    }

    @Override
    public int deleteBatch(Integer[]discGoodTempIds) {
        return mkStoreTicketGoodsTempDao.deleteBatch(discGoodTempIds);
    }

    /**
     * 触发优惠券选择商品页面分页按钮时保存数据
     * @param mkStoreTicketDiscountGoods
     */
    @Transactional
    @Override
    public void batchSaveDiscountGoods(MkStoreTicketGoodsTempEntity mkStoreTicketDiscountGoods){
        SysUserEntity user = ShiroUtils.getUserEntity();
        List<CheckGoodsDto> list = mkStoreTicketDiscountGoods.getCheckGoodsList();
        if(list.size() > 0){
            //如前端获取选中数组为空，则查询出无效字段进行删除
            MkStoreTicketGoodsTempEntity entity = new MkStoreTicketGoodsTempEntity();
            entity.setStoreId(mkStoreTicketDiscountGoods.getStoreId());
            entity.setApplyType(mkStoreTicketDiscountGoods.getApplyType());
            entity.setGuid(mkStoreTicketDiscountGoods.getGuid());
            entity.setIsValid(Dict.isValid.item_1.getItem());
            List<MkStoreTicketGoodsTempEntity> tempEntityList = mkStoreTicketGoodsTempDao.queryGoodsTempByIsValid(entity);
            if(tempEntityList.size() > 0){
                deleteBatchTemp(tempEntityList);
            }
            for(int i=0; i < list.size(); i++){
                CheckGoodsDto checkGoodsDto = list.get(i);
                MkStoreTicketGoodsTempEntity ticketGoodsTempEntity = mkStoreTicketGoodsTempDao.queryGoodsTempByRealId(checkGoodsDto.getStoreRealId(),checkGoodsDto.getGuid());
                mkStoreTicketDiscountGoods.setCreateTime(new Date());
                mkStoreTicketDiscountGoods.setModTime(new Date());
                mkStoreTicketDiscountGoods.setCreaterSn(user.getUsername());
                mkStoreTicketDiscountGoods.setModerSn(user.getUsername());
                mkStoreTicketDiscountGoods.setGuid(checkGoodsDto.getGuid());
                mkStoreTicketDiscountGoods.setApplyType(checkGoodsDto.getApplyType());
                mkStoreTicketDiscountGoods.setStoreRelaId(checkGoodsDto.getStoreRealId());
                mkStoreTicketDiscountGoods.setIsButtonCannel("0");
                if(ticketGoodsTempEntity == null) {
                    mkStoreTicketDiscountGoods.setIsValid(Dict.isValid.item_0.getItem());
                    mkStoreTicketDiscountGoods.setIsSubmit(mkStoreTicketDiscountGoods.getIsSubmit());
                    mkStoreTicketGoodsTempDao.save(mkStoreTicketDiscountGoods);
                }else{
                    mkStoreTicketDiscountGoods.setIsValid(Dict.isValid.item_0.getItem());
                    mkStoreTicketDiscountGoods.setIsSubmit(Dict.isSubmit.item_0.getItem());
                    mkStoreTicketDiscountGoods.setDiscGoodTempId(ticketGoodsTempEntity.getDiscGoodTempId());
                    mkStoreTicketGoodsTempDao.update(mkStoreTicketDiscountGoods);
                }
            }
        }else{
            mkStoreTicketDiscountGoods.setStoreId(mkStoreTicketDiscountGoods.getStoreId());
            mkStoreTicketDiscountGoods.setApplyType(mkStoreTicketDiscountGoods.getApplyType());
            mkStoreTicketDiscountGoods.setGuid(mkStoreTicketDiscountGoods.getGuid());
            if(mkStoreTicketDiscountGoods.getIsSubmit().equalsIgnoreCase(Dict.isSubmit.item_0.getItem())){//确定按钮
                //如前端获取选中数组为空，则查询出无效字段进行删除
                mkStoreTicketDiscountGoods.setIsValid(Dict.isValid.item_1.getItem());
                List<MkStoreTicketGoodsTempEntity> tempEntityList = mkStoreTicketGoodsTempDao.queryGoodsTempByIsValid(mkStoreTicketDiscountGoods);
                deleteBatchTemp(tempEntityList);
            }else{//取消按钮
                mkStoreTicketDiscountGoods.setIsSubmit(Dict.isSubmit.item_1.getItem());//取消按钮
                List<MkStoreTicketGoodsTempEntity> tempEntityList = mkStoreTicketGoodsTempDao.queryGoodsTempByGuidAndIsSubmit(mkStoreTicketDiscountGoods);
                //删除定为弹框取消按钮触发选中的商品
                deleteBatchTemp(tempEntityList);

                //点击取消按钮，查询无效商品恢复为有效商品
                mkStoreTicketDiscountGoods.setIsValid(Dict.isValid.item_1.getItem());
                List<MkStoreTicketGoodsTempEntity> tempByIsValidList = mkStoreTicketGoodsTempDao.queryGoodsTempByIsValid(mkStoreTicketDiscountGoods);
                for(int i=0; i < tempByIsValidList.size(); i++){
                    //修改为有效
                    MkStoreTicketGoodsTempEntity tempEntity = new MkStoreTicketGoodsTempEntity();
                    tempEntity.setIsValid(Dict.isValid.item_0.getItem());
                    tempEntity.setDiscGoodTempId(tempByIsValidList.get(i).getDiscGoodTempId());
                    mkStoreTicketGoodsTempDao.update(tempEntity);
                }
            }
        }
    }

    private void deleteBatchTemp(List<MkStoreTicketGoodsTempEntity> tempEntityList){
        if(tempEntityList.size() > 0) {
            Integer[] ids = new Integer[tempEntityList.size()];
            for (int i = 0; i < tempEntityList.size(); i++) {
                ids[i] = tempEntityList.get(i).getDiscGoodTempId();
            }
            mkStoreTicketGoodsTempDao.deleteBatch(ids);
        }
    }

    @Override
    public List<MkStoreTicketGoodsTempEntity> queryGoodsTempIdBy(MkStoreTicketGoodsTempEntity entity) {
        return mkStoreTicketGoodsTempDao.queryGoodsTempIdBy(entity);
    }

    /**
     * 触发优惠券选择商品页面取消按钮时，将返回失效的商品还原为有效
     * @param mkStoreTicketGoodsTemp
     */
    @Transactional
    @Override
    public void resetDiscTicketIsValidByTemp(MkStoreTicketGoodsTempEntity mkStoreTicketGoodsTemp){
        if(StringUtils.isNotEmpty(mkStoreTicketGoodsTemp.getGuid())){
            mkStoreTicketGoodsTempDao.deleteByGuid(mkStoreTicketGoodsTemp.getGuid());//删除
        }
        if(mkStoreTicketGoodsTemp.getTickDiscId() != null){
            MkStoreTicketDiscountEntity mkStoreTicketDiscountEntity = mkStoreTicketDiscountService.queryObject(mkStoreTicketGoodsTemp.getTickDiscId());
            if(mkStoreTicketDiscountEntity == null){
                throw new RRException("优惠券信息不存在");
            }
            //点击取消按钮，则恢复被删除的无效商品为有效商品
            mkStoreTicketGoodsTemp.setStoreId(mkStoreTicketDiscountEntity.getStoreId());
            mkStoreTicketGoodsTemp.setApplyType(mkStoreTicketDiscountEntity.getApplyType());
            mkStoreTicketGoodsTemp.setGuid(mkStoreTicketDiscountEntity.getGuid());
            mkStoreTicketGoodsTemp.setIsButtonCannel("1");//点击页面取消按钮设置为无效的商品
            //查询页面无效商品
            List<MkStoreTicketGoodsTempEntity> tempByIsValidList = mkStoreTicketGoodsTempDao.queryGoodsTempByIsValid(mkStoreTicketGoodsTemp);
            for(int i=0; i < tempByIsValidList.size(); i++){
                MkStoreTicketGoodsTempEntity tempEntity = new MkStoreTicketGoodsTempEntity();
                tempEntity.setDiscGoodTempId(tempByIsValidList.get(i).getDiscGoodTempId());
                tempEntity.setIsButtonCannel("0");//点击页面取消按钮设置为有效的商品
                mkStoreTicketGoodsTempDao.update(tempEntity);//修改为有效
            }
            /**
             * 当在修改优惠券商品页选择了其他商品后，触发页面返回按钮，则将该商品在临时表中删除
             */
            mkStoreTicketGoodsTemp.setIsValid("0");
            mkStoreTicketGoodsTemp.setIsButtonCannel("0");
            //根据适用商品类型、优惠券id查询优惠券商品
            Map goodsMap = new HashMap();
            goodsMap.put("tickDiscId", mkStoreTicketDiscountEntity.getTickDiscId());
            goodsMap.put("applyType", mkStoreTicketDiscountEntity.getApplyType());
            List<MkStoreTicketDiscountGoodsEntity> discountGoodsList = mkStoreTicketDiscountGoodsService.queryList(goodsMap);
            List<Integer> storeRelaIdList = null;
            if(discountGoodsList.size() > 0) {
                storeRelaIdList = new ArrayList<>();
                for (MkStoreTicketDiscountGoodsEntity entity : discountGoodsList) {
                    storeRelaIdList.add(entity.getStoreRelaId());
                }
            }
            mkStoreTicketGoodsTemp.setStoreRelaIdList(storeRelaIdList);
            //查询排除掉优惠券商品表中已存在的（storeRelaIdList）优惠券商品临时数据
            List<MkStoreTicketGoodsTempEntity> tempIdList = mkStoreTicketGoodsTempDao.queryGoodsTempIdBy(mkStoreTicketGoodsTemp);
            Integer[] ids = new Integer[tempIdList.size()];
            if(tempIdList.size() > 0) {
                for (int i = 0; i < tempIdList.size(); i++) {
                    ids[i] = tempIdList.get(i).getDiscGoodTempId();
                }
                if (ids.length > 0) {
                    mkStoreTicketGoodsTempDao.deleteBatch(ids);//删除
                }
            }
        }
    }

    /**
     * 触发门店活动选择商品页面分页按钮时保存数据
     * @param mkStoreTicketDiscountGoods
     */
    @Transactional
    @Override
    public void batchSaveStoreTopicGoods(MkStoreTicketGoodsTempEntity mkStoreTicketDiscountGoods){
        SysUserEntity user = ShiroUtils.getUserEntity();
        List<CheckGoodsDto> list = mkStoreTicketDiscountGoods.getCheckGoodsList();
        if(list.size() > 0){
            //如前端获取选中数组为空，则查询出无效字段进行删除
            MkStoreTicketGoodsTempEntity entity = new MkStoreTicketGoodsTempEntity();
            entity.setStoreId(mkStoreTicketDiscountGoods.getStoreId());
            entity.setApplyType(mkStoreTicketDiscountGoods.getApplyType());
            // TODO: 2019/6/5 门店活动
            entity.setStoreTopicId(mkStoreTicketDiscountGoods.getStoreTopicId());
            entity.setIsValid(Dict.isValid.item_1.getItem());
            List<MkStoreTicketGoodsTempEntity> tempEntityList = mkStoreTicketGoodsTempDao.queryGoodsTempByIsValid(entity);
            if(tempEntityList.size() > 0){
                deleteBatchTemp(tempEntityList);
            }
            for(int i=0; i < list.size(); i++){
                CheckGoodsDto checkGoodsDto = list.get(i);
                MkStoreTicketGoodsTempEntity ticketGoodsTempEntity = mkStoreTicketGoodsTempDao.queryGoodsTempByRealIdAndTopicId(checkGoodsDto.getStoreRealId(),
                        mkStoreTicketDiscountGoods.getStoreTopicId());
                mkStoreTicketDiscountGoods.setCreateTime(new Date());
                mkStoreTicketDiscountGoods.setModTime(new Date());
                mkStoreTicketDiscountGoods.setCreaterSn(user.getUsername());
                mkStoreTicketDiscountGoods.setModerSn(user.getUsername());
                mkStoreTicketDiscountGoods.setApplyType(checkGoodsDto.getApplyType());
                mkStoreTicketDiscountGoods.setStoreRelaId(checkGoodsDto.getStoreRealId());
                mkStoreTicketDiscountGoods.setIsButtonCannel("0");
                mkStoreTicketDiscountGoods.setStoreTopicId(mkStoreTicketDiscountGoods.getStoreTopicId());
                if(ticketGoodsTempEntity == null) {
                    mkStoreTicketDiscountGoods.setIsSubmit(mkStoreTicketDiscountGoods.getIsSubmit());
                    mkStoreTicketDiscountGoods.setIsValid(Dict.isValid.item_0.getItem());
                    mkStoreTicketGoodsTempDao.save(mkStoreTicketDiscountGoods);
                }else{
                    mkStoreTicketDiscountGoods.setIsValid(Dict.isValid.item_0.getItem());
                    mkStoreTicketDiscountGoods.setIsSubmit(Dict.isSubmit.item_0.getItem());
                    mkStoreTicketDiscountGoods.setDiscGoodTempId(ticketGoodsTempEntity.getDiscGoodTempId());
                    mkStoreTicketGoodsTempDao.update(mkStoreTicketDiscountGoods);
                }
            }
        }else{
            mkStoreTicketDiscountGoods.setStoreId(mkStoreTicketDiscountGoods.getStoreId());
            mkStoreTicketDiscountGoods.setApplyType(mkStoreTicketDiscountGoods.getApplyType());
            // TODO: 2019/6/5 门店活动
            mkStoreTicketDiscountGoods.setStoreTopicId(mkStoreTicketDiscountGoods.getStoreTopicId());
            if(mkStoreTicketDiscountGoods.getIsSubmit().equalsIgnoreCase(Dict.isSubmit.item_0.getItem())){//确定按钮
                //如前端获取选中数组为空，则查询出无效字段进行删除
                mkStoreTicketDiscountGoods.setIsValid(Dict.isValid.item_1.getItem());
                List<MkStoreTicketGoodsTempEntity> tempEntityList = mkStoreTicketGoodsTempDao.queryGoodsTempByIsValid(mkStoreTicketDiscountGoods);
                deleteBatchTemp(tempEntityList);
            }else{//取消按钮
                mkStoreTicketDiscountGoods.setIsSubmit(Dict.isSubmit.item_1.getItem());//取消按钮
                List<MkStoreTicketGoodsTempEntity> tempEntityList = mkStoreTicketGoodsTempDao.queryGoodsTempByGuidAndIsSubmit(mkStoreTicketDiscountGoods);
                //删除定为弹框取消按钮触发选中的商品
                deleteBatchTemp(tempEntityList);

                //点击取消按钮，查询无效商品恢复为有效商品
                mkStoreTicketDiscountGoods.setIsValid(Dict.isValid.item_1.getItem());
                List<MkStoreTicketGoodsTempEntity> tempByIsValidList = mkStoreTicketGoodsTempDao.queryGoodsTempByIsValid(mkStoreTicketDiscountGoods);
                for(int i=0; i < tempByIsValidList.size(); i++){
                    //修改为有效
                    MkStoreTicketGoodsTempEntity tempEntity = new MkStoreTicketGoodsTempEntity();
                    tempEntity.setDiscGoodTempId(tempByIsValidList.get(i).getDiscGoodTempId());
                    tempEntity.setIsValid(Dict.isValid.item_0.getItem());
                    mkStoreTicketGoodsTempDao.update(tempEntity);
                }
            }
        }
    }

    @Override
    public MkStoreTicketGoodsTempEntity queryGoodsTempByRealIdAndTopicId(Integer discGoodTempId, Integer storeTopicId) {
        return mkStoreTicketGoodsTempDao.queryGoodsTempByRealIdAndTopicId(discGoodTempId, storeTopicId);
    }
}
