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

import com.google.common.collect.ImmutableBiMap;
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.MkStoreCampMinusDao;
import com.kmall.admin.dao.mk.store.MkStoreCampMinusLevelDao;
import com.kmall.admin.dao.mk.store.MkStoreTicketGoodsTempDao;
import com.kmall.admin.dao.mk.store.StoreTopicDao;
import com.kmall.admin.dto.*;
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.MkStoreCampMinusEntity;
import com.kmall.admin.entity.mk.store.MkStoreCampMinusLevelEntity;
import com.kmall.admin.entity.mk.store.StoreTopicEntity;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.admin.service.mk.store.MkStoreCampMinusService;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.api.entity.mk.MkStoreCampMinusLevelVo;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 门店满减活动Service实现类
 *
 * @author emato
 * @email admin@qhdswl.com
 * @date 2019-05-29 14:43:28
 */
@Service("mkStoreCampMinusService")
public class MkStoreCampMinusServiceImpl implements MkStoreCampMinusService {
    @Autowired
    private MkStoreCampMinusDao mkStoreCampMinusDao;
    @Autowired
    private MkStoreCampMinusLevelDao mkStoreCampMinusLevelDao;
    @Autowired
    private StoreTopicDao storeTopicDao;
    @Autowired
    private AdDao adDao;
    @Autowired
    private StoreDao storeDao;
    @Autowired
    private UserCouponDao userCouponDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private MkStoreTicketGoodsTempDao mkStoreTicketGoodsTempDao;

    @Override
    public MkStoreCampMinusEntity queryObject(Integer campMinusId) {
        MkStoreCampMinusEntity mkStoreCampMinus = mkStoreCampMinusDao.queryObject(campMinusId);
        if(mkStoreCampMinus == null){
            throw new RRException("满减满折活动信息不存在");
        }
        StoreEntity storeEntity = storeDao.queryObject(mkStoreCampMinus.getStoreId());
        if(storeEntity == null){
            throw new RRException("门店信息不存在");
        }
        mkStoreCampMinus.setStoreName(storeEntity.getStoreName());
        String invalidTime = DateUtils.format(mkStoreCampMinus.getCampBegTime(),DateUtils.DATE_TIME_PATTERN) +
                " - " + DateUtils.format(mkStoreCampMinus.getCampEndTime(),DateUtils.DATE_TIME_PATTERN);
        mkStoreCampMinus.setInValidTime(invalidTime);
        List<MinusTypeUnitAttrDto> minusTypeUnitAttrList = new ArrayList<>();
        List<MinusTypeUnitModeDto> minusTypeUnitMode10List = new ArrayList<>();
        List<MinusTypePieceAttrDto> minusTypePieceAttrList = new ArrayList<>();
        List<MinusTypePieceModeDto> minusTypePieceMode10List = new ArrayList<>();
        List<MinusTypeDiscUnitAttrDto> minusTypeDiscUnitAttrList = new ArrayList<>();
        List<MinusTypeDiscPieceAttrDto> minusTypeDiscPieceAttrList = new ArrayList<>();

        List<MkStoreCampMinusLevelEntity> levelEntityList = mkStoreCampMinusLevelDao.queryLevelByCampMinusId(campMinusId);
        for(MkStoreCampMinusLevelEntity levelEntity: levelEntityList) {
            //满元满减
            if (levelEntity.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_00.getItem())
                    && levelEntity.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_00.getItem())) {
                MinusTypeUnitAttrDto minusTypeUnitAttrDto = new MinusTypeUnitAttrDto();
                minusTypeUnitAttrDto.setYuanMinusCond(String.valueOf(levelEntity.getYuanMinusCond()).replace(".00",""));
                minusTypeUnitAttrDto.setYuanMinusPref(String.valueOf(levelEntity.getYuanMinusPref()).replace(".00",""));
                minusTypeUnitAttrDto.setIsDelete(0);
                minusTypeUnitAttrList.add(minusTypeUnitAttrDto);
            }
            //满元满减，且减免类型为每满一次减一次
            if (levelEntity.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_00.getItem())
                    && levelEntity.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_10.getItem())) {
                MinusTypeUnitModeDto unitModeDto = new MinusTypeUnitModeDto();
                unitModeDto.setYuanMinusCond(String.valueOf(levelEntity.getYuanMinusCond()).replace(".00",""));
                unitModeDto.setYuanMinusPref(String.valueOf(levelEntity.getYuanMinusPref()).replace(".00",""));
                unitModeDto.setPieceMinusEachDisc(String.valueOf(levelEntity.getPieceMinusEachDisc()).replace(".00",""));
                unitModeDto.setIsDelete(0);
                minusTypeUnitMode10List.add(unitModeDto);
            }
            //满件满减
            if (levelEntity.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_01.getItem())
                    && levelEntity.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_00.getItem())) {
                MinusTypePieceAttrDto pieceAttrDto = new MinusTypePieceAttrDto();
                pieceAttrDto.setPieceMinusConf(levelEntity.getPieceMinusConf());
                pieceAttrDto.setPieceMinusPref(String.valueOf(levelEntity.getPieceMinusPref()).replace(".00",""));
                pieceAttrDto.setIsDelete(0);
                minusTypePieceAttrList.add(pieceAttrDto);
            }
            //满件满减，且减免类型为每满一次减一次
            if (levelEntity.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_01.getItem())
                    && levelEntity.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_10.getItem())) {
                MinusTypePieceModeDto pieceModeDto = new MinusTypePieceModeDto();
                pieceModeDto.setPieceMinusConf(levelEntity.getPieceMinusConf());
                pieceModeDto.setPieceMinusPref(String.valueOf(levelEntity.getPieceMinusPref()).replace(".00",""));
                pieceModeDto.setPieceMinusEachDisc(String.valueOf(levelEntity.getPieceMinusEachDisc()).replace(".00",""));
                pieceModeDto.setIsDelete(0);
                minusTypePieceMode10List.add(pieceModeDto);
            }
            //满元满折
            if (levelEntity.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_10.getItem())) {
                MinusTypeDiscUnitAttrDto discUnitAttrDto = new MinusTypeDiscUnitAttrDto();
                discUnitAttrDto.setYuanDiscCond(String.valueOf(levelEntity.getYuanDiscCond()).replace(".00",""));
                discUnitAttrDto.setYuanDiscPref(String.valueOf(levelEntity.getYuanDiscPref()).replace(".00",""));
                discUnitAttrDto.setIsDelete(0);
                minusTypeDiscUnitAttrList.add(discUnitAttrDto);
            }
            //满件满折
            if (levelEntity.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_11.getItem())) {
                MinusTypeDiscPieceAttrDto discPieceAttrDto = new MinusTypeDiscPieceAttrDto();
                discPieceAttrDto.setPieceDiscConf(levelEntity.getPieceDiscConf());
                discPieceAttrDto.setPieceDiscPref(String.valueOf(levelEntity.getPieceDiscPref()).replace(".00",""));
                discPieceAttrDto.setIsDelete(0);
                minusTypeDiscPieceAttrList.add(discPieceAttrDto);
            }
        }
        mkStoreCampMinus.setMinusTypeUnitAttrList(minusTypeUnitAttrList);
        mkStoreCampMinus.setMinusTypeUnitMode10List(minusTypeUnitMode10List);
        mkStoreCampMinus.setMinusTypePieceAttrList(minusTypePieceAttrList);
        mkStoreCampMinus.setMinusTypePieceMode10List(minusTypePieceMode10List);
        mkStoreCampMinus.setMinusTypeDiscUnitAttrList(minusTypeDiscUnitAttrList);
        mkStoreCampMinus.setMinusTypeDiscPieceAttrList(minusTypeDiscPieceAttrList);
        return mkStoreCampMinus;
    }

    @Override
    public List<MkStoreCampMinusEntity> queryList(Map<String, Object> map) {
        List<MkStoreCampMinusEntity> mkStoreCampMinusEntities = mkStoreCampMinusDao.queryList(map);
        for (MkStoreCampMinusEntity campMinusEntity: mkStoreCampMinusEntities) {
            String browseNum = StringUtils.isNotEmpty(String.valueOf(campMinusEntity.getBrowseNum())) ? String.valueOf(campMinusEntity.getBrowseNum()) : "0";
            String submitNum = StringUtils.isNotEmpty(String.valueOf(campMinusEntity.getSubmitNum())) ? String.valueOf(campMinusEntity.getSubmitNum()) : "0";
            String actMoney = StringUtils.isNotEmpty(String.valueOf(campMinusEntity.getActMoney())) ? String.valueOf(campMinusEntity.getActMoney()) : "0";
            String invalidTime = DateUtils.format(campMinusEntity.getCampBegTime(),DateUtils.DATE_TIME_PATTERN) +
                    " - " + DateUtils.format(campMinusEntity.getCampEndTime(),DateUtils.DATE_TIME_PATTERN);
            String minusStat = "商品浏览量：" + browseNum + "\n下单单数：" + submitNum + "\n实收金额：" + actMoney;

            campMinusEntity.setInValidTime(invalidTime);
            campMinusEntity.setMinusStat(minusStat);
        }
        return mkStoreCampMinusEntities;
    }

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

    /**
     * 校验优惠内容活动层级信息
     * @param mkStoreCampMinus
     */
    private void checkMkStoreCampMinusData(MkStoreCampMinusEntity mkStoreCampMinus){
        //满元满减
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_00.getItem())
                && mkStoreCampMinus.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_00.getItem())) {
            List<MinusTypeUnitAttrDto> minusTypeUnitAttrList = mkStoreCampMinus.getMinusTypeUnitAttrList();
            if(minusTypeUnitAttrList == null && minusTypeUnitAttrList.size() == 0){
                throw new RRException("优惠内容活动层级不能为空");
            }else{
                List<MinusTypeUnitAttrDto> checkMinusTypeList = minusTypeUnitAttrList;
                for (int i=0; i < minusTypeUnitAttrList.size(); i++) {
                    MinusTypeUnitAttrDto item = minusTypeUnitAttrList.get(i);
                    Map<String, Object> valideDate = MapBeanUtil.fromObject(item);
                    ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
                    builder.put("yuanMinusCond", "满元减条件");
                    builder.put("yuanMinusPref", "满元减优惠");
                    R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
                    if (Integer.valueOf(r.get("code").toString()) != 0) {
                        throw new RRException(r.get("msg").toString());
                    }
                    if(!StringUtils.checkNumberByTwoDecimal(String.valueOf(item.getYuanMinusCond()))){
                        throw new RRException("满元减条件格式错误，最多只保留小数点后2位的正数");
                    }
                    if(!StringUtils.checkNumberByTwoDecimal(String.valueOf(item.getYuanMinusPref()))){
                        throw new RRException("满元减优惠格式错误，最多只保留小数点后2位的正数");
                    }
                    if(Double.valueOf(item.getYuanMinusPref()) <= 0){
                        throw new RRException("满元减优惠不能小于等于0");
                    }
                    //校验当前满元减条件与下一级条件比较，层级必须递增且不可相同
                    String yuanMinusCond = "";
                    if((i+1) < minusTypeUnitAttrList.size()){
                        yuanMinusCond = minusTypeUnitAttrList.get(i+1).getYuanMinusCond();
                    }
                    if(!"".equalsIgnoreCase(yuanMinusCond)) {
                        if (Double.valueOf(item.getYuanMinusCond()) >= Double.valueOf(yuanMinusCond)) {
                            throw new RRException("满元减条件格式错误，层级必须递增且不可相同");
                        }
                    }
                }
            }
        }
        //满元满减，且减免类型为每满一次减一次
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_00.getItem())
                && mkStoreCampMinus.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_10.getItem())) {
            List<MinusTypeUnitModeDto> minusTypeUnitMode10List = mkStoreCampMinus.getMinusTypeUnitMode10List();
            if(minusTypeUnitMode10List == null && minusTypeUnitMode10List.size() == 0){
                throw new RRException("优惠内容活动层级不能为空");
            }else{
                for (MinusTypeUnitModeDto item : minusTypeUnitMode10List) {
                    Map<String, Object> valideDate = MapBeanUtil.fromObject(item);
                    ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
                    builder.put("yuanMinusCond", "满元减条件");
                    builder.put("yuanMinusPref", "满元减优惠");
                    builder.put("pieceMinusEachDisc", "满减件每人优惠");
                    R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
                    if (Integer.valueOf(r.get("code").toString()) != 0) {
                        throw new RRException(r.get("msg").toString());
                    }
                    if(!StringUtils.checkNumberByTwoDecimal(String.valueOf(item.getYuanMinusCond()))){
                        throw new RRException("满元减条件格式错误，最多只保留小数点后2位的正数");
                    }
                    if(Double.valueOf(item.getYuanMinusCond()) <= 0){
                        throw new RRException("满元减条件不能小于等于0");
                    }
                    if(!StringUtils.checkNumberByTwoDecimal(String.valueOf(item.getYuanMinusPref()))){
                        throw new RRException("满元减优惠格式错误，最多只保留小数点后2位的正数");
                    }
                    if(Double.valueOf(item.getYuanMinusPref()) <= 0){
                        throw new RRException("满元减优惠不能小于等于0");
                    }
                    if(!StringUtils.checkNumberByTwoDecimal(String.valueOf(item.getPieceMinusEachDisc()))){
                        throw new RRException("满减件每人优惠格式错误，最多只保留小数点后2位的正数");
                    }
                    if(Double.valueOf(item.getPieceMinusEachDisc()) < 0){
                        throw new RRException("满减件每人优惠不能小于0");
                    }
                }
            }
        }
        //满件满减
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_01.getItem())
                && mkStoreCampMinus.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_00.getItem())) {
            List<MinusTypePieceAttrDto> minusTypePieceAttrList = mkStoreCampMinus.getMinusTypePieceAttrList();
            if(minusTypePieceAttrList == null && minusTypePieceAttrList.size() == 0){
                throw new RRException("优惠内容活动层级不能为空");
            }else{
                for (int i=0; i<minusTypePieceAttrList.size(); i++) {
                    MinusTypePieceAttrDto item = minusTypePieceAttrList.get(i);
                    Map<String, Object> valideDate = MapBeanUtil.fromObject(item);
                    ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
                    builder.put("pieceMinusConf", "满件减条件");
                    builder.put("pieceMinusPref", "满件减优惠");
                    R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
                    if (Integer.valueOf(r.get("code").toString()) != 0) {
                        throw new RRException(r.get("msg").toString());
                    }
                    if(!StringUtils.checkNumberByInteger(String.valueOf(item.getPieceMinusConf()))){
                        throw new RRException("满件减条件格式错误，只允许输入大于等于0的整数");
                    }
                    if(item.getPieceMinusConf().doubleValue() < 0){
                        throw new RRException("满件减条件格式错误，只允许输入大于等于0的整数");
                    }
                    if(!StringUtils.checkNumberByTwoDecimal(String.valueOf(item.getPieceMinusPref()))){
                        throw new RRException("满件减优惠格式错误，最多只保留小数点后2位的正数");
                    }
                    if(Double.valueOf(item.getPieceMinusPref()) <= 0){
                        throw new RRException("满件减优惠不能小于等于0");
                    }
                    //校验当前满件折条件与下一级条件比较，层级必须递增且不可相同
                    Integer pieceMinusConf = null;
                    if((i+1) < minusTypePieceAttrList.size()){
                        pieceMinusConf = minusTypePieceAttrList.get(i+1).getPieceMinusConf();
                    }
                    if(pieceMinusConf != null) {
                        if (item.getPieceMinusConf() >= pieceMinusConf) {
                            throw new RRException("满件减条件格式错误，层级必须递增且不可相同");
                        }
                    }
                }
            }
        }
        //满件满减，且减免类型为每满一次减一次
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_01.getItem())
                && mkStoreCampMinus.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_10.getItem())) {
            List<MinusTypePieceModeDto> minusTypePieceMode10List = mkStoreCampMinus.getMinusTypePieceMode10List();
            if(minusTypePieceMode10List == null && minusTypePieceMode10List.size() == 0){
                throw new RRException("优惠内容活动层级不能为空");
            }else{
                for (MinusTypePieceModeDto item : minusTypePieceMode10List) {
                    Map<String, Object> valideDate = MapBeanUtil.fromObject(item);
                    ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
                    builder.put("pieceMinusConf", "满件减条件");
                    builder.put("pieceMinusPref", "满件减优惠");
                    builder.put("pieceMinusEachDisc", "满减件每人优惠");
                    R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
                    if (Integer.valueOf(r.get("code").toString()) != 0) {
                        throw new RRException(r.get("msg").toString());
                    }
                    if(!StringUtils.checkNumberByInteger(String.valueOf(item.getPieceMinusConf()))){
                        throw new RRException("满件减条件格式错误，只允许输入大于0的整数");
                    }
                    if(item.getPieceMinusConf().doubleValue() <= 0){
                        throw new RRException("满件减条件格式错误，只允许输入大于0的整数");
                    }

                    if(!StringUtils.checkNumberByTwoDecimal(String.valueOf(item.getPieceMinusPref()))){
                        throw new RRException("满件减优惠格式错误，最多只保留小数点后2位的正数");
                    }
                    if(Double.valueOf(item.getPieceMinusPref()) <= 0){
                        throw new RRException("满件减优惠不能小于等于0");
                    }

                    if(!StringUtils.checkNumberByTwoDecimal(String.valueOf(item.getPieceMinusEachDisc()))){
                        throw new RRException("满减件每人优惠格式错误，最多只保留小数点后2位的正数");
                    }
                    if(Double.valueOf(item.getPieceMinusPref()) < 0){
                        throw new RRException("满减件每人优惠不能小于0");
                    }
                }
            }
        }
        //满元满折
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_10.getItem())) {
            List<MinusTypeDiscUnitAttrDto> minusTypeDiscUnitAttrList = mkStoreCampMinus.getMinusTypeDiscUnitAttrList();
            if(minusTypeDiscUnitAttrList == null && minusTypeDiscUnitAttrList.size() == 0){
                throw new RRException("优惠内容活动层级不能为空");
            }else{
                for (int i=0; i<minusTypeDiscUnitAttrList.size(); i++) {
                    MinusTypeDiscUnitAttrDto item = minusTypeDiscUnitAttrList.get(i);
                    Map<String, Object> valideDate = MapBeanUtil.fromObject(item);
                    ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
                    builder.put("yuanDiscCond", "满元折条件");
                    builder.put("yuanDiscPref", "满元折优惠");
                    R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
                    if (Integer.valueOf(r.get("code").toString()) != 0) {
                        throw new RRException(r.get("msg").toString());
                    }

                    if(!StringUtils.checkNumberByTwoDecimal(String.valueOf(item.getYuanDiscCond()))){
                        throw new RRException("满元折条件格式错误，最多只保留小数点后2位的正数");
                    }
                    if(Double.valueOf(item.getYuanDiscCond()) < 0){
                        throw new RRException("满元折条件不能小于0");
                    }

                    if (!StringUtils.checkNumberByOneDecimal(String.valueOf(item.getYuanDiscPref()))){
                        throw new RRException("满元折优惠格式错误，最多只保留小数点后1位的正数");
                    }
                    if(Double.valueOf(item.getYuanDiscPref()) > 10){
                        throw new RRException("请输入不大于10的满元折优惠数值");
                    }
                    if(Double.valueOf(item.getYuanDiscPref()) <= 0){
                        throw new RRException("满元折优惠数值不能小于等于0");
                    }
                    //校验当前满元减条件与下一级条件比较，层级必须递增且不可相同
                    String yuanDiscCond = "";
                    if((i+1) < minusTypeDiscUnitAttrList.size()){
                        yuanDiscCond = minusTypeDiscUnitAttrList.get(i+1).getYuanDiscCond();
                    }
                    if(!"".equalsIgnoreCase(yuanDiscCond)) {
                        if (Double.valueOf(item.getYuanDiscCond()) >= Double.valueOf(yuanDiscCond)) {
                            throw new RRException("满元折条件格式错误，层级必须递增且不可相同");
                        }
                    }
                }
            }
        }
        //满件满折
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_11.getItem())) {
            List<MinusTypeDiscPieceAttrDto> minusTypeDiscPieceAttrList = mkStoreCampMinus.getMinusTypeDiscPieceAttrList();
            if(minusTypeDiscPieceAttrList == null && minusTypeDiscPieceAttrList.size() == 0){
                throw new RRException("优惠内容活动层级不能为空");
            }else{
                for (int i=0; i < minusTypeDiscPieceAttrList.size(); i++) {
                    MinusTypeDiscPieceAttrDto item = minusTypeDiscPieceAttrList.get(i);
                    Map<String, Object> valideDate = MapBeanUtil.fromObject(item);
                    ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
                    builder.put("pieceDiscConf", "满件折条件");
                    builder.put("pieceDiscPref", "满件折优惠");
                    R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
                    if (Integer.valueOf(r.get("code").toString()) != 0) {
                        throw new RRException(r.get("msg").toString());
                    }
                    if(!StringUtils.checkNumberByInteger(String.valueOf(item.getPieceDiscConf()))){
                        throw new RRException("满件折条件格式错误，只允许输入大于等于0的整数");
                    }
                    if(item.getPieceDiscConf().doubleValue() < 0){
                        throw new RRException("满件折条件格式错误，只允许输入大于等于0的整数");
                    }

                    if (!StringUtils.checkNumberByOneDecimal(String.valueOf(item.getPieceDiscPref()))){
                        throw new RRException("满元折优惠格式错误，最多只保留小数点后1位的正数");
                    }
                    if(Double.valueOf(item.getPieceDiscPref()) > 10){
                        throw new RRException("请输入不大于10的满元折优惠数值");
                    }
                    if(Double.valueOf(item.getPieceDiscPref()) <= 0){
                        throw new RRException("满元折优惠数值不能小于等于0");
                    }
                    //校验当前满件折条件与下一级条件比较，层级必须递增且不可相同
                    Integer pieceDiscConf = null;
                    if((i+1) < minusTypeDiscPieceAttrList.size()){
                        pieceDiscConf = minusTypeDiscPieceAttrList.get(i+1).getPieceDiscConf();
                    }
                    if(pieceDiscConf != null) {
                        if (item.getPieceDiscConf() >= pieceDiscConf) {
                            throw new RRException("满件折条件格式错误，层级必须递增且不可相同");
                        }
                    }
                }
            }
        }
    }

    @Transactional
    @Override
    public int save(MkStoreCampMinusEntity mkStoreCampMinus) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        StoreEntity storeEntity = storeDao.queryObject(mkStoreCampMinus.getStoreId());
        if(storeEntity == null){
            throw new RRException("门店信息不存在");
        }
        if(!DateUtils.compareDate(mkStoreCampMinus.getCampBegTime(), mkStoreCampMinus.getCampBegTime())){
            throw new RRException("结束时间不能超过开始时间");
        }
        if(mkStoreCampMinus.getCampBegTime().getTime() == mkStoreCampMinus.getCampEndTime().getTime()){
            throw new RRException("结束时间不能与开始时间相同");
        }
        //校验优惠内容活动层级信息
        checkMkStoreCampMinusData(mkStoreCampMinus);

        StoreTopicEntity storeTopicEntity = saveStoreTopic(mkStoreCampMinus, user);
        if(storeTopicEntity != null) {
            //新增满减信息
            mkStoreCampMinus.setCreaterSn(user.getUsername());
            mkStoreCampMinus.setCreateTime(new Date());
            mkStoreCampMinus.setModerSn(user.getUsername());
            mkStoreCampMinus.setModTime(new Date());
            mkStoreCampMinus.setIsPast("0");
            mkStoreCampMinus.setStoreTopicId(storeTopicEntity.getId());
            //开始时间大于当前时间，则结束状态为未开始
            if(mkStoreCampMinus.getCampBegTime().getTime() > new Date().getTime()){
                mkStoreCampMinus.setIsPast(Dict.isPast.item_2.getItem());
            }
            //开始时间小于当前时间，则结束状态为进行中
            if(mkStoreCampMinus.getCampBegTime().getTime() < new Date().getTime()){
                mkStoreCampMinus.setIsPast(Dict.isPast.item_0.getItem());
            }
            mkStoreCampMinusDao.save(mkStoreCampMinus);
        }
        //保存或更新满减满折活动层级数据
        saveOrUpdateCampMinusLevel(mkStoreCampMinus);

        //是否展示在小程序门店首页广告栏，为1则新增广告信息广告位
        if(mkStoreCampMinus.getIsStoreShow().equalsIgnoreCase("1")) {
            AdEntity adEntity = new AdEntity();
            adEntity.setStoreId(mkStoreCampMinus.getStoreId());
            adEntity.setContent(mkStoreCampMinus.getCampName());
            adEntity.setMerchSn(storeEntity.getMerchSn());
            adEntity.setImageUrl(mkStoreCampMinus.getAdvImgUrl());
            adEntity.setName(mkStoreCampMinus.getCampName());
            adEntity.setLink("/pages/ucenter/campMinusDetail/campMinusDetail?campMinusId=" + mkStoreCampMinus.getCampMinusId() +
                    "&&storeId=" + mkStoreCampMinus.getStoreId() + "&&isShare==0");
            adEntity.setEnabled(1);
            adEntity.setAdPositionId(1);
            adEntity.setMediaType(1);
            adEntity.setStoreTopicId(mkStoreCampMinus.getStoreTopicId());
            adDao.save(adEntity);
        }
        return 1;
    }

    @Transactional
    @Override
    public int update(MkStoreCampMinusEntity mkStoreCampMinus) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        MkStoreCampMinusEntity storeCampMinusEntity = queryObject(mkStoreCampMinus.getCampMinusId());
        if(storeCampMinusEntity == null){
            throw new RRException("满减满折活动信息不存在");
        }
        StoreEntity storeEntity = storeDao.queryObject(mkStoreCampMinus.getStoreId());
        if(storeEntity == null){
            throw new RRException("门店信息不存在");
        }
        if(!DateUtils.compareDate(mkStoreCampMinus.getCampBegTime(), mkStoreCampMinus.getCampBegTime())){
            throw new RRException("结束时间不能超过开始时间");
        }
        if(mkStoreCampMinus.getCampBegTime().getTime() == mkStoreCampMinus.getCampEndTime().getTime()){
            throw new RRException("结束时间不能与开始时间相同");
        }
        if(mkStoreCampMinus.getCampEndTime()!= null){
            if(mkStoreCampMinus.getCampEndTime().getTime() < storeCampMinusEntity.getCampEndTime().getTime()){
                throw new RRException("不可缩短满减满折活动有效期");
            }
        }
        //校验优惠内容活动层级信息
        checkMkStoreCampMinusData(mkStoreCampMinus);
        StoreTopicEntity storeTopicEntity = storeTopicDao.queryObject(storeCampMinusEntity.getStoreTopicId());
        if(storeTopicEntity != null) {
            storeTopicEntity.setTitle(mkStoreCampMinus.getCampName());
            storeTopicDao.update(storeTopicEntity);
            //更新满减信息
            mkStoreCampMinus.setModerSn(user.getUsername());
            mkStoreCampMinus.setModTime(new Date());
            mkStoreCampMinus.setIsPast("0");
            mkStoreCampMinus.setStoreTopicId(storeTopicEntity.getId());
            //开始时间大于当前时间，则结束状态为未开始
            if(mkStoreCampMinus.getCampBegTime().getTime() > new Date().getTime()){
                mkStoreCampMinus.setIsPast(Dict.isPast.item_2.getItem());
            }
            //开始时间小于当前时间，则结束状态为进行中
            if(mkStoreCampMinus.getCampBegTime().getTime() < new Date().getTime()){
                mkStoreCampMinus.setIsPast(Dict.isPast.item_0.getItem());
            }
            mkStoreCampMinusDao.update(mkStoreCampMinus);

            //保存或更新满减满折活动层级数据
            saveOrUpdateCampMinusLevel(mkStoreCampMinus);

            AdEntity ad = adDao.queryAdByStoreTopicId(storeCampMinusEntity.getStoreTopicId());
            //是否展示在小程序门店首页广告栏，为1则新增广告信息广告位
            if(mkStoreCampMinus.getIsStoreShow().equalsIgnoreCase("1")) {
                AdEntity adEntity = new AdEntity();
                adEntity.setContent(mkStoreCampMinus.getCampName());
                adEntity.setImageUrl(mkStoreCampMinus.getAdvImgUrl());
                adEntity.setName(mkStoreCampMinus.getCampName());
                adEntity.setLink("/pages/ucenter/campMinusDetail/campMinusDetail?campMinusId=" + storeCampMinusEntity.getCampMinusId() +
                        "&&storeId=" + storeCampMinusEntity.getStoreId() + "&&isShare==0");
                adEntity.setEnabled(1);
                if(ad != null){
                    adEntity.setId(ad.getId());
                    adDao.update(adEntity);
                }else{
                    adEntity.setStoreId(storeCampMinusEntity.getStoreId());
                    adEntity.setMerchSn(storeEntity.getMerchSn());
                    adEntity.setAdPositionId(1);
                    adEntity.setMediaType(1);
                    adEntity.setStoreTopicId(storeCampMinusEntity.getStoreTopicId());
                    adDao.save(adEntity);
                }
            }
//            为0则将已有的广告位隐藏
            if(storeCampMinusEntity.getIsStoreShow().equalsIgnoreCase("0")) {
                if(ad != null) {
                    AdEntity adEntity = new AdEntity();
                    adEntity.setEnabled(0);
                    adEntity.setId(ad.getId());
                    adDao.update(adEntity);
                }
            }
        }
        return 1;
    }

    /**
     * 保存或更新满减满折活动层级数据
     * @param mkStoreCampMinus 已保存的满减满折活动信息
     */
    private void saveOrUpdateCampMinusLevel(MkStoreCampMinusEntity mkStoreCampMinus){
        Integer campMinusId = mkStoreCampMinus.getCampMinusId();
        List<MkStoreCampMinusLevelEntity> minusLevelEntityList = mkStoreCampMinusLevelDao.queryLevelByCampMinusId(campMinusId);
        List<MkStoreCampMinusLevelEntity> saveMinusLevelList = new ArrayList<>();
        if(minusLevelEntityList != null && minusLevelEntityList.size() > 0) {
            //删除该满减满折活动原有的层级活动信息
            mkStoreCampMinusLevelDao.deleteByCampMinusId(campMinusId);
        }

        //满元满减
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_00.getItem())
                && mkStoreCampMinus.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_00.getItem())) {
            List<MinusTypeUnitAttrDto> minusTypeUnitAttrList = mkStoreCampMinus.getMinusTypeUnitAttrList();
            if(minusTypeUnitAttrList != null && minusTypeUnitAttrList.size() > 0) {
                for (MinusTypeUnitAttrDto unitAttrDto : minusTypeUnitAttrList) {
                    if (unitAttrDto.getIsDelete() == 0) {
                        MkStoreCampMinusLevelEntity levelVo = new MkStoreCampMinusLevelEntity();
                        levelVo.setCampMinusId(campMinusId);
                        levelVo.setCampMinusType(mkStoreCampMinus.getCampMinusType());
                        levelVo.setMinusMode(mkStoreCampMinus.getMinusMode());
                        levelVo.setYuanMinusCond(BigDecimal.valueOf(Double.parseDouble(unitAttrDto.getYuanMinusCond())));
                        levelVo.setYuanMinusPref(BigDecimal.valueOf(Double.parseDouble(unitAttrDto.getYuanMinusPref())));
                        levelVo.setIsValid(Dict.isValid.item_0.getItem());
                        levelVo.setCreaterSn(mkStoreCampMinus.getCreaterSn());
                        levelVo.setCreateTime(new Date());
                        levelVo.setModerSn(mkStoreCampMinus.getModerSn());
                        levelVo.setModTime(new Date());
                        saveMinusLevelList.add(levelVo);
                    }
                }
            }
        }
        //满元满减，且减免类型为每满一次减一次
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_00.getItem())
                && mkStoreCampMinus.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_10.getItem())) {
            List<MinusTypeUnitModeDto> minusTypeUnitMode10List = mkStoreCampMinus.getMinusTypeUnitMode10List();
            if(minusTypeUnitMode10List != null && minusTypeUnitMode10List.size() > 0) {
                for (MinusTypeUnitModeDto unitModeDto : minusTypeUnitMode10List) {
                    if (unitModeDto.getIsDelete() == 0) {
                        MkStoreCampMinusLevelEntity levelVo = new MkStoreCampMinusLevelEntity();
                        levelVo.setCampMinusId(campMinusId);
                        levelVo.setCampMinusType(mkStoreCampMinus.getCampMinusType());
                        levelVo.setMinusMode(mkStoreCampMinus.getMinusMode());
                        levelVo.setYuanMinusCond(BigDecimal.valueOf(Double.parseDouble(unitModeDto.getYuanMinusCond())));
                        levelVo.setYuanMinusPref(BigDecimal.valueOf(Double.parseDouble(unitModeDto.getYuanMinusPref())));
                        levelVo.setPieceMinusEachDisc(BigDecimal.valueOf(Double.parseDouble(unitModeDto.getPieceMinusEachDisc())));
                        levelVo.setIsValid(Dict.isValid.item_0.getItem());
                        levelVo.setCreaterSn(mkStoreCampMinus.getCreaterSn());
                        levelVo.setCreateTime(new Date());
                        levelVo.setModerSn(mkStoreCampMinus.getModerSn());
                        levelVo.setModTime(new Date());
                        saveMinusLevelList.add(levelVo);
                    }
                }
            }
        }
        //满件满减
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_01.getItem())
                && mkStoreCampMinus.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_00.getItem())) {
            List<MinusTypePieceAttrDto> minusTypePieceAttrList = mkStoreCampMinus.getMinusTypePieceAttrList();
            if(minusTypePieceAttrList != null && minusTypePieceAttrList.size() > 0) {
                for (MinusTypePieceAttrDto pieceAttrDto : minusTypePieceAttrList) {
                    if (pieceAttrDto.getIsDelete() == 0) {
                        MkStoreCampMinusLevelEntity levelVo = new MkStoreCampMinusLevelEntity();
                        levelVo.setCampMinusId(campMinusId);
                        levelVo.setCampMinusType(mkStoreCampMinus.getCampMinusType());
                        levelVo.setMinusMode(mkStoreCampMinus.getMinusMode());
                        levelVo.setPieceMinusConf(pieceAttrDto.getPieceMinusConf());
                        levelVo.setPieceMinusPref(BigDecimal.valueOf(Double.parseDouble(pieceAttrDto.getPieceMinusPref())));
                        levelVo.setIsValid(Dict.isValid.item_0.getItem());
                        levelVo.setCreaterSn(mkStoreCampMinus.getCreaterSn());
                        levelVo.setCreateTime(new Date());
                        levelVo.setModerSn(mkStoreCampMinus.getModerSn());
                        levelVo.setModTime(new Date());
                        saveMinusLevelList.add(levelVo);
                    }
                }
            }
        }
        //满件满减，且减免类型为每满一次减一次
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_01.getItem())
                && mkStoreCampMinus.getMinusMode().equalsIgnoreCase(Dict.minusMode.item_10.getItem())) {
            List<MinusTypePieceModeDto> minusTypePieceMode10List = mkStoreCampMinus.getMinusTypePieceMode10List();
            if(minusTypePieceMode10List != null && minusTypePieceMode10List.size() > 0) {
                for (MinusTypePieceModeDto pieceModeDto : minusTypePieceMode10List) {
                    if (pieceModeDto.getIsDelete() == 0) {
                        MkStoreCampMinusLevelEntity levelVo = new MkStoreCampMinusLevelEntity();
                        levelVo.setCampMinusId(campMinusId);
                        levelVo.setCampMinusType(mkStoreCampMinus.getCampMinusType());
                        levelVo.setMinusMode(mkStoreCampMinus.getMinusMode());
                        levelVo.setPieceMinusConf(pieceModeDto.getPieceMinusConf());
                        levelVo.setPieceMinusPref(BigDecimal.valueOf(Double.parseDouble(pieceModeDto.getPieceMinusPref())));
                        levelVo.setPieceMinusEachDisc(BigDecimal.valueOf(Double.parseDouble(pieceModeDto.getPieceMinusEachDisc())));
                        levelVo.setIsValid(Dict.isValid.item_0.getItem());
                        levelVo.setCreaterSn(mkStoreCampMinus.getCreaterSn());
                        levelVo.setCreateTime(new Date());
                        levelVo.setModerSn(mkStoreCampMinus.getModerSn());
                        levelVo.setModTime(new Date());
                        saveMinusLevelList.add(levelVo);
                    }
                }
            }
        }
        //满元满折
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_10.getItem())) {
            List<MinusTypeDiscUnitAttrDto> minusTypeDiscUnitAttrList = mkStoreCampMinus.getMinusTypeDiscUnitAttrList();
            if(minusTypeDiscUnitAttrList != null && minusTypeDiscUnitAttrList.size() > 0) {
                for (MinusTypeDiscUnitAttrDto discUnitAttrDto : minusTypeDiscUnitAttrList) {
                    if (discUnitAttrDto.getIsDelete() == 0) {
                        MkStoreCampMinusLevelEntity levelVo = new MkStoreCampMinusLevelEntity();
                        levelVo.setCampMinusId(campMinusId);
                        levelVo.setCampMinusType(mkStoreCampMinus.getCampMinusType());
                        levelVo.setMinusMode(mkStoreCampMinus.getMinusMode());
                        levelVo.setYuanDiscCond(BigDecimal.valueOf(Double.parseDouble(discUnitAttrDto.getYuanDiscCond())));
                        levelVo.setYuanDiscPref(BigDecimal.valueOf(Double.parseDouble(discUnitAttrDto.getYuanDiscPref())));
                        levelVo.setIsValid(Dict.isValid.item_0.getItem());
                        levelVo.setCreaterSn(mkStoreCampMinus.getCreaterSn());
                        levelVo.setCreateTime(new Date());
                        levelVo.setModerSn(mkStoreCampMinus.getModerSn());
                        levelVo.setModTime(new Date());
                        saveMinusLevelList.add(levelVo);
                    }
                }
            }
        }
        //满件满折
        if (mkStoreCampMinus.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_11.getItem())) {
            List<MinusTypeDiscPieceAttrDto> minusTypeDiscPieceAttrList = mkStoreCampMinus.getMinusTypeDiscPieceAttrList();
            if(minusTypeDiscPieceAttrList != null && minusTypeDiscPieceAttrList.size() > 0) {
                for (MinusTypeDiscPieceAttrDto discPieceAttrDto : minusTypeDiscPieceAttrList) {
                    if (discPieceAttrDto.getIsDelete() == 0) {
                        MkStoreCampMinusLevelEntity levelVo = new MkStoreCampMinusLevelEntity();
                        levelVo.setCampMinusId(campMinusId);
                        levelVo.setCampMinusType(mkStoreCampMinus.getCampMinusType());
                        levelVo.setMinusMode(mkStoreCampMinus.getMinusMode());
                        levelVo.setPieceDiscConf(discPieceAttrDto.getPieceDiscConf());
                        levelVo.setPieceDiscPref(BigDecimal.valueOf(Double.parseDouble(discPieceAttrDto.getPieceDiscPref())));
                        levelVo.setIsValid(Dict.isValid.item_0.getItem());
                        levelVo.setCreaterSn(mkStoreCampMinus.getCreaterSn());
                        levelVo.setCreateTime(new Date());
                        levelVo.setModerSn(mkStoreCampMinus.getModerSn());
                        levelVo.setModTime(new Date());
                        saveMinusLevelList.add(levelVo);
                    }
                }
            }
        }
        //层级信息不为空
        if(saveMinusLevelList != null && saveMinusLevelList.size() > 0) {
            mkStoreCampMinusLevelDao.saveBatch(saveMinusLevelList);
        }
    }

    /**
     * 新增门店活动
     * @param mkStoreCampMinus
     * @param user
     * @return
     */
    private StoreTopicEntity saveStoreTopic(MkStoreCampMinusEntity mkStoreCampMinus, SysUserEntity user){
        StoreTopicEntity storeTopicEntity = new StoreTopicEntity();
        storeTopicEntity.setTitle(mkStoreCampMinus.getCampName());
        storeTopicEntity.setContent(mkStoreCampMinus.getAdvDesc());
        storeTopicEntity.setSubtitle(mkStoreCampMinus.getCampName());
        storeTopicEntity.setStoreId(mkStoreCampMinus.getStoreId());
        storeTopicEntity.setThirdMerchSn(mkStoreCampMinus.getThirdMerchSn());
        storeTopicEntity.setIsValid("0");
        storeTopicEntity.setCreateTime(new Date());
        storeTopicEntity.setCreaterSn(user.getUsername());
        storeTopicEntity.setModTime(new Date());
        storeTopicEntity.setModerSn(user.getUsername());
        storeTopicEntity.setPromTypeId(7);
        storeTopicDao.save(storeTopicEntity);
        return storeTopicEntity;
    }

    @Override
    public int delete(Integer campMinusId) {
        return mkStoreCampMinusDao.delete(campMinusId);
    }

    @Transactional
    @Override
    public int deleteBatch(Integer[]campMinusIds) {
        if(campMinusIds != null && campMinusIds.length > 0) {
            Integer[] storeTopicIds = new Integer[campMinusIds.length];
            for (int i = 0; i < campMinusIds.length; i++) {
                MkStoreCampMinusEntity campMinusEntity = mkStoreCampMinusDao.queryObject(campMinusIds[i]);
                if (campMinusEntity != null) {
                    storeTopicIds[i] = campMinusEntity.getStoreTopicId();
                    List<UserCouponEntity> userCouponEntityList = userCouponDao.queryByStoreTopicId(campMinusEntity.getStoreTopicId());
                    if (userCouponEntityList != null && userCouponEntityList.size() > 0){
                        if(userCouponEntityList.size() > 0){
                            throw new RRException("该优惠券【"+campMinusEntity.getCampName()+"】已有"+userCouponEntityList.size()+"个用户领取，不能删除");
                        }
                    }
                    List<OrderEntity> orderEntityList = orderDao.queryObjectByActivityId(campMinusEntity.getStoreTopicId());
                    if (orderEntityList != null && orderEntityList.size() > 0){
                        if(orderEntityList.size() > 0){
                            throw new RRException("该优惠券【"+campMinusEntity.getCampName()+"】已生成"+orderEntityList.size()+"条订单信息，不能删除");
                        }
                    }
                    mkStoreCampMinusLevelDao.deleteByCampMinusId(campMinusIds[i]);

                    mkStoreTicketGoodsTempDao.deleteByStoreTopicId(campMinusEntity.getStoreTopicId());

                    //修改为无效活动
                    StoreTopicEntity storeTopicEntity = new StoreTopicEntity();
                    storeTopicEntity.setId(campMinusEntity.getStoreTopicId());
                    storeTopicEntity.setIsValid(Dict.isValid.item_1.getItem());
                    storeTopicDao.update(storeTopicEntity);
                }
            }
//            storeTopicDao.deleteBatch(storeTopicIds);
        }
        return mkStoreCampMinusDao.deleteBatch(campMinusIds);
    }

    @Override
    public int updatePastById(MkStoreCampMinusEntity mkStoreCampMinus){
        return mkStoreCampMinusDao.update(mkStoreCampMinus);
    }
}
