package com.ssm.manage.service.impl;

import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmRechargeTypeDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.AccountTradeRecordRequest;
import com.ssm.manage.query.RechargeTypeRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SsmRechargeTypeServiceImpl extends BaseServiceImpl<RechargeType> implements SsmRechargeTypeSevice {
    @Autowired
    private RedisClient<List<RechargeType>> redisClient;

    @Autowired
    private RedisClient<StaffResponse> templateRedisClient;

    @Autowired
    private SsmRechargeTypeDao dao;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmRechargeTypeStoreImp ssmRechargeTypeStoreImp;

    @Autowired
    private SsmRechargeTypeStoreService ssmRechargeTypeStoreService;

    @Autowired
    private SsmPromotionProjectService ssmPromotionProjectService;


    @Override
    public SsmRechargeTypeDao getDao() {
        return dao;
    }

    private static String key = "rechargeTypeList";

    @Override
    public PageInfo<RechargeType> selectPage(RechargeTypeRequest rechargeRequest) {
        return dao.selectPage(rechargeRequest);
    }

    @Override
    public PageInfo<RechargeType> selectPagess(RechargeTypeRequest rechargeRequest) {
        return dao.selectPagess(rechargeRequest);
    }

    @Override
    public PageInfo<RechargeType> selectnewPage(RechargeTypeRequest rechargeRequest) {
        return dao.selectnewPage(rechargeRequest);
    }

    @Override
    public PageInfo<RechargeType> selectnewPages(RechargeTypeRequest rechargeRequest) {
        return dao.selectnewPages(rechargeRequest);
    }
    @Override
    public PageInfo<RechargeType> selectpromotionPage(RechargeTypeRequest rechargeRequest) {
        return dao.selectnewPage(rechargeRequest);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addRecharge(RechargeTypeRequest rechargeRequest, String phone) throws SmsException {
        checkNum(rechargeRequest.getRechargeTypeNum(), rechargeRequest.getRechargeTypeName(), rechargeRequest.getStoreId());
        RechargeType recharge = new RechargeType();
        recharge.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        recharge.setRechargeTypeNum(rechargeRequest.getRechargeTypeNum());
        recharge.setRechargeTypeName(rechargeRequest.getRechargeTypeName());
        recharge.setDiscount(rechargeRequest.getDiscount());
        recharge.setStoreId(rechargeRequest.getStoreId());
        recharge.setStoreName(rechargeRequest.getStoreName());
        recharge.setState(1);
        recharge.setTypeRatio(rechargeRequest.getTypeRatio());
        recharge.setType(rechargeRequest.getType());
        if(rechargeRequest.getType()==2){//促销类型
            recharge.setGiveType(rechargeRequest.getGiveType());//仅门店使用
        }
        recharge.setRechargeMoney(rechargeRequest.getRechargeMoney());
        recharge.setGiftMoney(rechargeRequest.getGiftMoney());
        recharge.setValidTime(rechargeRequest.getValidTime());
        recharge.setDiscountFreeAmount(rechargeRequest.getDiscountFreeAmount());
        recharge.setFirstAmount(rechargeRequest.getFirstAmount());
        recharge.setCardType(0);
        recharge.setLiftCardId(rechargeRequest.getLiftCardId());
        recharge.setUnifiedDue(rechargeRequest.getUnifiedDue());
        recharge.setDonateType(rechargeRequest.getDonateType());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if(null!=rechargeRequest.getStartDates()) {
                recharge.setStartDates(simpleDateFormat.parse(rechargeRequest.getStartDates()));
            }
            if(null!=rechargeRequest.getStopDates()){
                recharge.setStopDates(simpleDateFormat.parse(rechargeRequest.getStopDates()));
            }


        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (templateRedisClient.hasKey(getKey(phone))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(phone));
            recharge.setFounderStaff(staffResponse.getStaffName());
            recharge.setFounderDatetime(new Date());
        }
        if(rechargeRequest.getType()==2&&rechargeRequest.getStoreType()==1){//指定门店使用
            recharge.setStoreType(rechargeRequest.getStoreType());
            ssmRechargeTypeStoreService.insert(rechargeRequest.getRechargeTypeStoreList(),recharge);
        }
        int i = dao.saveNotNull(recharge);

        redisClient.delete(getKey(rechargeRequest.getStoreId(),key));
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addPromotionCourse(RechargeTypeRequest rechargeRequest, String phone) throws SmsException {
        checkNum(rechargeRequest.getRechargeTypeNum(), rechargeRequest.getRechargeTypeName(), rechargeRequest.getStoreId());
        RechargeType recharge = new RechargeType();
        recharge.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        recharge.setRechargeTypeNum(rechargeRequest.getRechargeTypeNum());
        recharge.setRechargeTypeName(rechargeRequest.getRechargeTypeName());
        recharge.setDiscount(rechargeRequest.getDiscount());
        recharge.setStoreId(rechargeRequest.getStoreId());
        recharge.setStoreName(rechargeRequest.getStoreName());
        recharge.setState(1);
        recharge.setTypeRatio(rechargeRequest.getTypeRatio());
        recharge.setType(rechargeRequest.getType());
        if(rechargeRequest.getType()==2){//促销类型
            recharge.setGiveType(rechargeRequest.getGiveType());//仅门店使用
        }
        recharge.setRechargeMoney(rechargeRequest.getRechargeMoney());
        recharge.setGiftMoney(rechargeRequest.getGiftMoney());
        recharge.setValidTime(rechargeRequest.getValidTime());
        recharge.setDiscountFreeAmount(rechargeRequest.getDiscountFreeAmount());
        recharge.setFirstAmount(rechargeRequest.getFirstAmount());
        recharge.setCardType(0);
        recharge.setLiftCardId(rechargeRequest.getLiftCardId());
        recharge.setUnifiedDue(rechargeRequest.getUnifiedDue());
        recharge.setDonateType(rechargeRequest.getDonateType());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if(null!=rechargeRequest.getStartDates()) {
                recharge.setStartDates(simpleDateFormat.parse(rechargeRequest.getStartDates()));
            }
            if(null!=rechargeRequest.getStopDates()){
                recharge.setStopDates(simpleDateFormat.parse(rechargeRequest.getStopDates()));
            }


        } catch (ParseException e) {
            e.printStackTrace();
        }
        //添加赠送的疗程项目
        if(rechargeRequest.getType()==2 && rechargeRequest.getPromotionProjectList()!=null && rechargeRequest.getPromotionProjectList().size()>0){

            List<PromotionProject> promotionProjectList = rechargeRequest.getPromotionProjectList();
            for (PromotionProject promotionProject : promotionProjectList) {
                //插入项目id
                promotionProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                promotionProject.setPromotionId(recharge.getId());
                promotionProject.setPromotionNum(recharge.getRechargeTypeNum());
                promotionProject.setPromotionName(recharge.getRechargeTypeName());
                promotionProject.setStoreId(recharge.getStoreId());
                promotionProject.setStoreName(recharge.getStoreName());
                promotionProject.setType(1);
                //设置项目的价格
                promotionProject.setStandardMoney(BigDecimalUtils.multiply(promotionProject.getPriceMember(),BigDecimalUtils.bigDecimal(promotionProject.getTimes().toString())));
                ssmPromotionProjectService.saveNotNull(promotionProject);
            }
            //保存充值送疗程

        }
        if (templateRedisClient.hasKey(getKey(phone))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(phone));
            recharge.setFounderStaff(staffResponse.getStaffName());
            recharge.setFounderDatetime(new Date());
        }
        if(rechargeRequest.getType()==2&&rechargeRequest.getStoreType()==1){//指定门店使用
            recharge.setStoreType(rechargeRequest.getStoreType());
            ssmRechargeTypeStoreService.insert(rechargeRequest.getRechargeTypeStoreList(),recharge);
        }
        int i = dao.saveNotNull(recharge);

        redisClient.delete(getKey(rechargeRequest.getStoreId(),key));
        return i;
    }

    @Override
    public int addRecharges(List<RechargeTypeRequest> rechargeRequest, String phone) throws SmsException {
        Boolean status=true;
        for (RechargeTypeRequest rechargeTypeRequest : rechargeRequest) {
            checkNum(rechargeTypeRequest.getRechargeTypeNum(), rechargeTypeRequest.getRechargeTypeName(), rechargeTypeRequest.getStoreId());
            RechargeType recharge = new RechargeType();
            recharge.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            recharge.setRechargeTypeNum(rechargeTypeRequest.getRechargeTypeNum());
            recharge.setRechargeTypeName(rechargeTypeRequest.getRechargeTypeName());
            recharge.setDiscount(rechargeTypeRequest.getDiscount());
            recharge.setStoreId(rechargeTypeRequest.getStoreId());
            recharge.setStoreName(rechargeTypeRequest.getStoreName());
            recharge.setState(1);
            recharge.setTypeRatio(rechargeTypeRequest.getTypeRatio());
            recharge.setType(rechargeTypeRequest.getType());
            recharge.setRechargeMoney(rechargeTypeRequest.getRechargeMoney());
            recharge.setGiftMoney(rechargeTypeRequest.getGiftMoney());
            recharge.setValidTime(rechargeTypeRequest.getValidTime());
            recharge.setDiscountFreeAmount(rechargeTypeRequest.getDiscountFreeAmount());
            recharge.setFirstAmount(rechargeTypeRequest.getFirstAmount());
            recharge.setCardType(0);
            recharge.setLiftCardId(rechargeTypeRequest.getLiftCardId());
            recharge.setDonateType(rechargeTypeRequest.getDonateType());
            if (templateRedisClient.hasKey(getKey(phone))){
                StaffResponse staffResponse = templateRedisClient.get(getKey(phone));
                recharge.setFounderStaff(staffResponse.getStaffName());
                recharge.setFounderDatetime(new Date());
            }
            int i = dao.saveNotNull(recharge);
            if(i>0){

            }else{
                status=false;
            }

        }
        if(status){
            redisClient.delete(getKey(rechargeRequest.get(0).getStoreId(),key));
            return 1;
        }else{
            throw new RuntimeException("拷贝其他门店充值类型出错");
        }


    }

    @Override
    public int updateRecharge(RechargeTypeRequest rechargeRequest, String phone) throws SmsException {
        checkNumUpdate(null, rechargeRequest.getRechargeTypeName(), rechargeRequest.getStoreId(),rechargeRequest.getId());
        RechargeType recharge = new RechargeType();
        recharge.setId(rechargeRequest.getId());
        recharge.setRechargeTypeName(rechargeRequest.getRechargeTypeName());
        recharge.setDiscount(rechargeRequest.getDiscount());
        recharge.setTypeRatio(rechargeRequest.getTypeRatio());
        recharge.setType(rechargeRequest.getType());
        recharge.setRechargeMoney(rechargeRequest.getRechargeMoney());
        recharge.setGiftMoney(rechargeRequest.getGiftMoney());
        recharge.setValidTime(rechargeRequest.getValidTime());
        recharge.setDiscountFreeAmount(rechargeRequest.getDiscountFreeAmount());
        recharge.setFirstAmount(rechargeRequest.getFirstAmount());
        recharge.setUnifiedDue(rechargeRequest.getUnifiedDue());
        recharge.setDonateType(rechargeRequest.getDonateType());
        recharge.setStoreType(rechargeRequest.getStoreType());
        recharge.setGiveType(rechargeRequest.getGiveType());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
        if(rechargeRequest.getType()==2){
            try {
                Date date = simpleDateFormat.parse(rechargeRequest.getStartDates());
                Date date1 = simpleDateFormat.parse(rechargeRequest.getStopDates());
                recharge.setStartDates(date);
                recharge.setStopDates(date1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        recharge.setCardType(0);
        if (templateRedisClient.hasKey(getKey(phone))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(phone));
            recharge.setModifyBy(staffResponse.getStaffName());
            recharge.setModifyDatetime(new Date());
        }
        if(rechargeRequest.getStoreType()==1){
            RechargeTypeStore rechargeTypeStore=new RechargeTypeStore();
            rechargeTypeStore.setRechargeId(recharge.getId());
            ssmRechargeTypeStoreService.delete(rechargeTypeStore);//删除之前的
            recharge.setRechargeTypeNum(rechargeRequest.getRechargeTypeNum());
            ssmRechargeTypeStoreService.insert(rechargeRequest.getRechargeTypeStoreList(),recharge);//插入新的
        }
        int i = dao.updateByPrimaryKeySelective(recharge);
        if(i>0){
            RechargeType recharges = new RechargeType();
            recharges.setRawCardId(recharge.getId());
            List<RechargeType> select = dao.select(recharges);
            for (RechargeType rechargeType : select) {
                rechargeType.setRechargeTypeName(rechargeRequest.getRechargeTypeName());
                rechargeType.setDiscount(rechargeRequest.getDiscount());
                rechargeType.setTypeRatio(rechargeRequest.getTypeRatio());
                rechargeType.setType(rechargeRequest.getType());
                rechargeType.setGiftMoney(rechargeRequest.getGiftMoney());
                rechargeType.setValidTime(rechargeRequest.getValidTime());
                rechargeType.setDiscountFreeAmount(rechargeRequest.getDiscountFreeAmount());
                rechargeType.setDonateType(rechargeRequest.getDonateType());
                if (templateRedisClient.hasKey(getKey(phone))){
                    StaffResponse staffResponse = templateRedisClient.get(getKey(phone));
                    rechargeType.setModifyBy(staffResponse.getStaffName());
                    rechargeType.setModifyDatetime(new Date());
                }
                rechargeType.setUnifiedDue(recharge.getUnifiedDue());
                dao.updateByPrimaryKeySelective(rechargeType);
            }
        }
        redisClient.delete(getKey(rechargeRequest.getStoreId(),key));
        return i;
    }

    @Override
    public int updatePromotionRecharge(RechargeTypeRequest rechargeRequest, String phone) throws SmsException {
        checkNumUpdate(null, rechargeRequest.getRechargeTypeName(), rechargeRequest.getStoreId(),rechargeRequest.getId());
        RechargeType recharge = new RechargeType();
        recharge.setId(rechargeRequest.getId());
        recharge.setRechargeTypeName(rechargeRequest.getRechargeTypeName());
        recharge.setDiscount(rechargeRequest.getDiscount());
        recharge.setTypeRatio(rechargeRequest.getTypeRatio());
        recharge.setType(rechargeRequest.getType());
        recharge.setRechargeMoney(rechargeRequest.getRechargeMoney());
        recharge.setGiftMoney(rechargeRequest.getGiftMoney());
        recharge.setValidTime(rechargeRequest.getValidTime());
        recharge.setDiscountFreeAmount(rechargeRequest.getDiscountFreeAmount());
        recharge.setFirstAmount(rechargeRequest.getFirstAmount());
        recharge.setUnifiedDue(rechargeRequest.getUnifiedDue());
        recharge.setDonateType(rechargeRequest.getDonateType());
        recharge.setStoreType(rechargeRequest.getStoreType());
        recharge.setGiveType(rechargeRequest.getGiveType());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
        if(rechargeRequest.getType()==2){
            try {
                Date date = simpleDateFormat.parse(rechargeRequest.getStartDates());
                Date date1 = simpleDateFormat.parse(rechargeRequest.getStopDates());
                recharge.setStartDates(date);
                recharge.setStopDates(date1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        recharge.setCardType(0);
        if (templateRedisClient.hasKey(getKey(phone))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(phone));
            recharge.setModifyBy(staffResponse.getStaffName());
            recharge.setModifyDatetime(new Date());
        }
        if(rechargeRequest.getStoreType()==1){
            RechargeTypeStore rechargeTypeStore=new RechargeTypeStore();
            rechargeTypeStore.setRechargeId(recharge.getId());
            ssmRechargeTypeStoreService.delete(rechargeTypeStore);//删除之前的
            recharge.setRechargeTypeNum(rechargeRequest.getRechargeTypeNum());
            ssmRechargeTypeStoreService.insert(rechargeRequest.getRechargeTypeStoreList(),recharge);//插入新的
        }
        int i = dao.updateByPrimaryKeySelective(recharge);


        //添加赠送的疗程项目
        if(rechargeRequest.getType()==2 && rechargeRequest.getPromotionProjectList()!=null && rechargeRequest.getPromotionProjectList().size()>0){

            List<PromotionProject> promotionProjectList = rechargeRequest.getPromotionProjectList();
            //删除之前保存的
            ssmPromotionProjectService.deleteByPromotionId(recharge.getId());
//            ssmPromotionProjectService.delete(null);
            //重新插入
            for (PromotionProject promotionProject : promotionProjectList) {
                //插入项目id
                promotionProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                promotionProject.setPromotionId(recharge.getId());
                promotionProject.setPromotionNum(recharge.getRechargeTypeNum());
                promotionProject.setPromotionName(recharge.getRechargeTypeName());
                promotionProject.setStoreId(recharge.getStoreId());
                promotionProject.setStoreName(recharge.getStoreName());
                //设置项目的价格
                promotionProject.setStandardMoney(BigDecimalUtils.multiply(promotionProject.getPriceMember(),BigDecimalUtils.bigDecimal(promotionProject.getTimes().toString())));
                //保存充值送疗程
                ssmPromotionProjectService.save(promotionProject);
            }
        }

        if(i>0){
            RechargeType recharges = new RechargeType();
            recharges.setRawCardId(recharge.getId());
            List<RechargeType> select = dao.select(recharges);
            for (RechargeType rechargeType : select) {
                rechargeType.setRechargeTypeName(rechargeRequest.getRechargeTypeName());
                rechargeType.setDiscount(rechargeRequest.getDiscount());
                rechargeType.setTypeRatio(rechargeRequest.getTypeRatio());
                rechargeType.setType(rechargeRequest.getType());
                rechargeType.setGiftMoney(rechargeRequest.getGiftMoney());
                rechargeType.setValidTime(rechargeRequest.getValidTime());
                rechargeType.setDiscountFreeAmount(rechargeRequest.getDiscountFreeAmount());
                rechargeType.setDonateType(rechargeRequest.getDonateType());
                if (templateRedisClient.hasKey(getKey(phone))){
                    StaffResponse staffResponse = templateRedisClient.get(getKey(phone));
                    rechargeType.setModifyBy(staffResponse.getStaffName());
                    rechargeType.setModifyDatetime(new Date());
                }
                rechargeType.setUnifiedDue(recharge.getUnifiedDue());
                dao.updateByPrimaryKeySelective(rechargeType);
            }
        }
        redisClient.delete(getKey(rechargeRequest.getStoreId(),key));
        return i;
    }
    @Override
    public int deleteRecharge(RechargeTypeRequest rechargeRequest) {
        RechargeType recharge = new RechargeType();
        recharge.setId(rechargeRequest.getId());
        int i = dao.deleteByPrimaryKey(recharge);
        redisClient.delete(getKey(rechargeRequest.getStoreId(),key));
        return i;
    }

    @Override
    public int updateStates(RechargeTypeRequest rechargeRequest) {
        RechargeType recharge = new RechargeType();
        recharge.setId(rechargeRequest.getId());
        recharge.setState(rechargeRequest.getState());
        int i = dao.updateByPrimaryKeySelective(recharge);
        redisClient.delete(getKey(rechargeRequest.getStoreId(),key));
        return i;
    }

    @Override
    public List<RechargeType> selectList(RechargeTypeRequest rechargeTypeRequest,Long storeId)throws SmsException {
        List<RechargeType> list = new ArrayList<>();
        List<RechargeType> lists = new ArrayList<>();
        RechargeType rechargeType = new RechargeType();
        rechargeType.setStoreId(rechargeTypeRequest.getStoreId());
        rechargeType.setState(1);
        rechargeType.setCardType(0);
        if(null != rechargeTypeRequest.getType()){
            rechargeType.setType(rechargeTypeRequest.getType());
        }
        if(null != rechargeTypeRequest.getRechargeTypeId()){
            RechargeType rechargeType1=dao.selectByPrimaryKey(rechargeTypeRequest.getRechargeTypeId());
            if(rechargeType1.getGiveType()==1)
                rechargeType.setGiveType(1);
        }

        list = dao.select(rechargeType);
        for (RechargeType type : list) {
            Date unifiedDue = null;
            try {
                if(type.getUnifiedDue()!=null) {
                    unifiedDue = DateUtils.ymdhmsString2DateTime(type.getUnifiedDue());
                }
            }catch (ParseException e){
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if(null != type.getType()){
                if(unifiedDue == null ||  unifiedDue.after(new Date())){
                    if(type.getType()!= 2){
                        lists.add(type);
                    }else{
                        Date stopDates = type.getStopDates();
                        Date date = new Date();
                        if(date.before(stopDates)){
                            if(type.getStoreType()==1){
                                for(RechargeTypeStore rechargeTypeStore:ssmRechargeTypeStoreImp.selectStore(type)){
                                    if(storeId.hashCode()==rechargeTypeStore.getStoreId().hashCode()) {
                                        //判断有没有
                                        PromotionProject promotionProject = new PromotionProject();
                                        promotionProject.setPromotionId(type.getId());
                                        List<PromotionProject> select = ssmPromotionProjectService.select(promotionProject);
                                        type.setPromotionProjectList(select);
                                        lists.add(type);
                                    }
                                }
                            }else{
                                //判断有没有
                                PromotionProject promotionProject = new PromotionProject();
                                promotionProject.setPromotionId(type.getId());
                                List<PromotionProject> select = ssmPromotionProjectService.select(promotionProject);
                                type.setPromotionProjectList(select);
                                lists.add(type);
                            }
                        }
                    }
                }
            }
        }

        return lists;
    }

    @Override
    public List<RechargeType> selectsjianjiList(RechargeTypeRequest rechargeTypeRequest) {
        List<RechargeType> list = dao.selectsjianjiList(rechargeTypeRequest);
        return list;
    }

    @Override
    public List<RechargeType> selectsjianjiLists(RechargeTypeRequest rechargeTypeRequest) {
        List<RechargeType> list = dao.selectsjianjiLists(rechargeTypeRequest);
        return list;
    }

    @Override
    public RechargeType one(RechargeTypeRequest rechargeTypeRequest) {
        RechargeType rechargeType = new RechargeType();
        rechargeType.setId(rechargeTypeRequest.getId());
        RechargeType list = dao.selectOne(rechargeType);
        return list;
    }

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public List<RechargeType> insertBatch(List<RechargeType> list, Long storeId, String storeName, String phone) throws SmsException {
        List<RechargeType> unusualList = this.check(list);
        List<RechargeType> rechargeTypeList = new ArrayList<>();
        if (!unusualList.isEmpty()){
            return unusualList;
        }
        StaffResponse staffResponse = new StaffResponse();
        if (templateRedisClient.hasKey(getKey(phone))){
            staffResponse = templateRedisClient.get(getKey(phone));
        }
        int count =0;
        for (RechargeType rechargeType : list) {
            count ++;
            if(null != rechargeType.getRechargeTypeNum()){
                RechargeType rechargeType1 = new RechargeType();
                rechargeType1.setRechargeTypeNum(rechargeType.getRechargeTypeNum());
                rechargeType1.setStoreId(storeId);
                rechargeType1.setCardType(0);
                RechargeType rechargeType2 = dao.selectOne(rechargeType1);
                if(null != rechargeType2){
                    //存在
                    rechargeType2.setTypeRatio(rechargeType.getTypeRatio());
                    rechargeType2.setFirstAmount(rechargeType.getFirstAmount());
                    rechargeType2.setRechargeMoney(rechargeType.getRechargeMoney());
                    if(rechargeType2.getType()==1){
                        rechargeType2.setDiscount(rechargeType.getDiscount());
                    }else if(rechargeType2.getType()==0){
                        rechargeType2.setGiftMoney(rechargeType.getGiftMoney());
                    }else if(rechargeType2.getType()==2){
                        rechargeType2.setDiscount(rechargeType.getDiscount());
                        rechargeType2.setGiftMoney(rechargeType.getGiftMoney());
                    }
                    rechargeType2.setValidTime(rechargeType.getValidTime());
                    rechargeType2.setUnifiedDue(rechargeType.getUnifiedDue());
                    rechargeType2.setDonateType(rechargeType.getDonateType());
                    rechargeType2.setStartDates(rechargeType.getStartDates());
                    rechargeType2.setStopDates(rechargeType.getStopDates());
                    rechargeType2.setModifyBy(staffResponse.getStaffName());
                    rechargeType2.setModifyDatetime(new Date());
                    int update = dao.updateByPrimaryKeySelective(rechargeType2);
                    if(rechargeType2.getType()!=2){
                        if(update>0){
                            RechargeType rechargeType3 = new RechargeType();
                            rechargeType3.setLiftCardId(rechargeType2.getId());
                            List<RechargeType> select = dao.select(rechargeType3);
                            for (RechargeType type : select) {
                                type.setTypeRatio(rechargeType2.getTypeRatio());
                                type.setFirstAmount(rechargeType2.getFirstAmount());
                                type.setDiscount(rechargeType2.getDiscount());
                                type.setValidTime(rechargeType2.getValidTime());
                                type.setUnifiedDue(rechargeType2.getUnifiedDue());
                                type.setDonateType(rechargeType2.getDonateType());
                                dao.updateByPrimaryKeySelective(type);
                            }
                            rechargeType3.setLiftCardId(null);
                            rechargeType3.setRawCardId(rechargeType2.getId());
                            List<RechargeType> selects = dao.select(rechargeType3);
                            for (RechargeType type : selects) {
                                type.setTypeRatio(rechargeType2.getTypeRatio());
                                type.setFirstAmount(rechargeType2.getFirstAmount());
                                type.setDiscount(rechargeType2.getDiscount());
                                type.setValidTime(rechargeType2.getValidTime());
                                type.setUnifiedDue(rechargeType2.getUnifiedDue());
                                type.setDonateType(rechargeType2.getDonateType());
                                dao.updateByPrimaryKeySelective(type);
                            }
                        }
                    }
                }else{
                    rechargeType.setId(SnowflakeUtil.getId());
                    rechargeType.setStoreId(storeId);
                    rechargeType.setStoreName(storeName);
                    rechargeType.setFounderStaff(staffResponse.getStaffName());
                    rechargeType.setFounderDatetime(new Date());
                    rechargeType.setCardType(0);
                    rechargeTypeList.add(rechargeType);
                }

//            rechargeType.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                //批量上传避免数据量过大时new Random()重复导致生成的ID重复

            }else{
                throw new SmsException(ResponseCode.MSG,"第"+count+"条导入充值类别编码存在为空");
            }

        }
        int i = 0;
        try {
            if(rechargeTypeList.size()>0){
                i = dao.insertBatch(rechargeTypeList);
            }

        }catch (Exception e){
            log.error("SsmRechargeTypeServiceImpl.insertBatch:", e);
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i != rechargeTypeList.size()){
            throw new SmsException(ResponseCode.ENCRYPT_ERROR);
        }else {
            throw new SmsException(ResponseCode.OK);
        }
    }

    public String getKey(Long storeId, String key){
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
        key = baseStore.getStoreNum() + key;
        return key;
    }


    public String getKey(String phone){
        String key = "";
        if (StringUtils.isNotBlank(phone)){
            key = Constant.staffKey + phone;
        }
        return key;
    }


    public void checkNum(String rechargeTypeNum, String rechargeTypeName, Long storeId) throws SmsException {
        if (StringUtils.isNotBlank(rechargeTypeNum) || null != rechargeTypeNum) {
            RechargeType recharge = new RechargeType();
            recharge.setRechargeTypeNum(rechargeTypeNum);
            recharge.setStoreId(storeId);
            recharge.setState(1);
            recharge.setCardType(0);
            List<RechargeType> rechargeTypeList = dao.select(recharge);
            if (rechargeTypeList.size() > 0) {
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "类别编码");
            }
        }
        if (StringUtils.isNotBlank(rechargeTypeName) || null != rechargeTypeName) {
            RechargeType recharge = new RechargeType();
            recharge.setRechargeTypeName(rechargeTypeName);
            recharge.setStoreId(storeId);
            recharge.setState(1);
            recharge.setCardType(0);
            List<RechargeType> rechargeTypeList = dao.select(recharge);
            if (rechargeTypeList.size() > 0) {
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "类别名称");
            }
        }
    }

    public void checkNumUpdate(String rechargeTypeNum, String rechargeTypeName, Long storeId,Long id) throws SmsException {
        if (StringUtils.isNotBlank(rechargeTypeNum) || null != rechargeTypeNum) {
            RechargeType recharge = new RechargeType();
            recharge.setRechargeTypeNum(rechargeTypeNum);
            recharge.setStoreId(storeId);
            recharge.setState(1);
            recharge.setCardType(0);
            List<RechargeType> rechargeTypeList = dao.select(recharge);
            if (rechargeTypeList.size() > 1) {
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "类别编码");
            }else if (rechargeTypeList.size() == 1){
                if(!rechargeTypeList.get(0).getId().equals(id)){
                    throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "类别编码");
                }
            }
        }
        if (StringUtils.isNotBlank(rechargeTypeName) || null != rechargeTypeName) {
            RechargeType recharge = new RechargeType();
            recharge.setRechargeTypeName(rechargeTypeName);
            recharge.setStoreId(storeId);
            recharge.setState(1);
            recharge.setCardType(0);
            List<RechargeType> rechargeTypeList = dao.select(recharge);
            if (rechargeTypeList.size() > 1) {
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "类别名称");
            }else if (rechargeTypeList.size() == 1){
                if(!rechargeTypeList.get(0).getId().equals(id)){
                    throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "类别名称");
                }
            }
        }
    }

    public void checkNums(String rechargeTypeNum, String rechargeTypeName, Long storeId,Long liftCardId) throws SmsException {
        if (StringUtils.isNotBlank(rechargeTypeNum) || null != rechargeTypeNum) {
            RechargeType recharge = new RechargeType();
            recharge.setRechargeTypeNum(rechargeTypeNum);
            recharge.setStoreId(storeId);
            recharge.setState(1);
            recharge.setCardType(1);
            recharge.setLiftCardId(liftCardId);
            List<RechargeType> rechargeTypeList = dao.select(recharge);
            if (rechargeTypeList.size() > 0) {
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "升降级关系");
            }
        }
        if (StringUtils.isNotBlank(rechargeTypeName) || null != rechargeTypeName) {
            RechargeType recharge = new RechargeType();
            recharge.setRechargeTypeName(rechargeTypeName);
            recharge.setStoreId(storeId);
            recharge.setState(1);
            recharge.setCardType(1);
            recharge.setLiftCardId(liftCardId);
            List<RechargeType> rechargeTypeList = dao.select(recharge);
            if (rechargeTypeList.size() > 0) {
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "升降级关系");
            }
        }
    }

    public void checkNumUpdates(String rechargeTypeNum, String rechargeTypeName, Long storeId,Long id,Long liftCardId) throws SmsException {
        if (StringUtils.isNotBlank(rechargeTypeNum) || null != rechargeTypeNum) {
            RechargeType recharge = new RechargeType();
            recharge.setRechargeTypeNum(rechargeTypeNum);
            recharge.setStoreId(storeId);
            recharge.setState(1);
            recharge.setCardType(1);
            recharge.setLiftCardId(liftCardId);
            List<RechargeType> rechargeTypeList = dao.select(recharge);
            if (rechargeTypeList.size() > 1) {
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "类别编码");
            }else if (rechargeTypeList.size() == 1){
                if(!rechargeTypeList.get(0).getId().equals(id)){
                    throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "类别编码");
                }
            }
        }
        if (StringUtils.isNotBlank(rechargeTypeName) || null != rechargeTypeName) {
            RechargeType recharge = new RechargeType();
            recharge.setRechargeTypeName(rechargeTypeName);
            recharge.setStoreId(storeId);
            recharge.setState(1);
            recharge.setCardType(1);
            recharge.setLiftCardId(liftCardId);
            List<RechargeType> rechargeTypeList = dao.select(recharge);
            if (rechargeTypeList.size() > 1) {
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "类别名称");
            }else if (rechargeTypeList.size() == 1){
                if(!rechargeTypeList.get(0).getId().equals(id)){
                    throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "类别名称");
                }
            }
        }
    }

    public List<RechargeType> check(List<RechargeType> list){
        List<RechargeType> unusualList = new ArrayList<>();
        //校验启用状态下编码是否重复
        Map<String, List<RechargeType>> map = list.stream().collect(Collectors.groupingBy(rechargeType -> rechargeType.getRechargeTypeNum() + "-" + rechargeType.getState()));
        for (String key : map.keySet()) {
            if (map.get(key).size() > 1){
                unusualList.addAll(map.get(key));
                list.removeAll(map.get(key));
            }
        }
        //校验启用状态下名称是否重复
        Map<String, List<RechargeType>> map1 = list.stream().collect(Collectors.groupingBy(rechargeType -> rechargeType.getRechargeTypeName() + "-" + rechargeType.getState()));
        for (String key : map1.keySet()) {
            if (map1.get(key).size() > 1){
                unusualList.addAll(map1.get(key));
                list.removeAll(map1.get(key));
            }
        }
        return unusualList;
    }


    @Override
    public int addRecharges(RechargeTypeRequest rechargeRequest, String phone) throws SmsException {
        checkNums(rechargeRequest.getRechargeTypeNum(), rechargeRequest.getRechargeTypeName(), rechargeRequest.getStoreId(),rechargeRequest.getLiftCardId());
        RechargeType recharge = new RechargeType();
        recharge.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        recharge.setRechargeTypeNum(rechargeRequest.getRechargeTypeNum());
        recharge.setRechargeTypeName(rechargeRequest.getRechargeTypeName());
        recharge.setDiscount(rechargeRequest.getDiscount());
        recharge.setStoreId(rechargeRequest.getStoreId());
        recharge.setStoreName(rechargeRequest.getStoreName());
        recharge.setState(1);
        recharge.setTypeRatio(rechargeRequest.getTypeRatio());
        recharge.setType(rechargeRequest.getType());
        recharge.setRechargeMoney(rechargeRequest.getRechargeMoney());
        recharge.setGiftMoney(rechargeRequest.getGiftMoney());
        recharge.setValidTime(rechargeRequest.getValidTime());
        recharge.setDiscountFreeAmount(rechargeRequest.getDiscountFreeAmount());
        recharge.setFirstAmount(rechargeRequest.getFirstAmount());
        recharge.setCardType(1);
        recharge.setLiftCardId(rechargeRequest.getLiftCardId());
        recharge.setRawCardId(rechargeRequest.getId());
        recharge.setLiftType(rechargeRequest.getLiftType());
        recharge.setDonateType(rechargeRequest.getDonateType());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if(null!=rechargeRequest.getStartDates()) {
                recharge.setStartDates(simpleDateFormat.parse(rechargeRequest.getStartDates()));
            }
            if(null!=rechargeRequest.getStopDates()){
                recharge.setStopDates(simpleDateFormat.parse(rechargeRequest.getStopDates()));
            }


        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (templateRedisClient.hasKey(getKey(phone))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(phone));
            recharge.setFounderStaff(staffResponse.getStaffName());
            recharge.setFounderDatetime(new Date());
        }
        int i = dao.saveNotNull(recharge);
        redisClient.delete(getKey(rechargeRequest.getStoreId(),key));
        return i;
    }

    @Override
    public int updateRecharges(RechargeTypeRequest rechargeRequest, String phone) throws SmsException {
        checkNumUpdates(null, rechargeRequest.getRechargeTypeName(), rechargeRequest.getStoreId(),rechargeRequest.getId(),rechargeRequest.getLiftCardId());
        RechargeType recharge = new RechargeType();
        recharge.setId(rechargeRequest.getId());
        recharge.setRechargeTypeName(rechargeRequest.getRechargeTypeName());
        recharge.setDiscount(rechargeRequest.getDiscount());
        recharge.setTypeRatio(rechargeRequest.getTypeRatio());
        recharge.setType(rechargeRequest.getType());
        recharge.setRechargeMoney(rechargeRequest.getRechargeMoney());
        recharge.setGiftMoney(rechargeRequest.getGiftMoney());
        recharge.setValidTime(rechargeRequest.getValidTime());
        recharge.setDiscountFreeAmount(rechargeRequest.getDiscountFreeAmount());
        recharge.setFirstAmount(rechargeRequest.getFirstAmount());
        recharge.setCardType(1);
        recharge.setLiftCardId(rechargeRequest.getLiftCardId());
        recharge.setDonateType(rechargeRequest.getDonateType());
        if (templateRedisClient.hasKey(getKey(phone))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(phone));
            recharge.setModifyBy(staffResponse.getStaffName());
            recharge.setModifyDatetime(new Date());
        }
        int i = dao.updateByPrimaryKeySelective(recharge);
        redisClient.delete(getKey(rechargeRequest.getStoreId(),key));
        return i;
    }

    @Override
    public int deleteRecharges(RechargeTypeRequest rechargeRequest) {
        RechargeType recharge = new RechargeType();
        recharge.setId(rechargeRequest.getId());
        int i = dao.deleteByPrimaryKey(recharge);
        redisClient.delete(getKey(rechargeRequest.getStoreId(),key));
        return i;
    }

    @Override
    public List<RechargeType> selectById(List<Long> rechargeTypeId) {
        Example example = new Example(RechargeType.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id",rechargeTypeId);
        return dao.selectByExample(example);
    }
}
