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.SsmPromotionDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.PromotionListRequest;
import com.ssm.manage.query.RepayListRequest;
import com.ssm.manage.query.StoreRequest;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.math.BigInteger;
import java.util.*;

@Service
@Slf4j
public class SsmPromotionServiceImpl extends BaseServiceImpl<PromotionList> implements SsmPromotionService {
    @Autowired
    private SsmPromotionMemberService ssmPromotionMemberSevice;

    @Autowired
    private SsmPromotionProjectService ssmPromotionProjectService;

    @Autowired
    private SsmPromotionUnitServiceImpl ssmPromotionUnitService;

    @Autowired
    private SsmPromotionStoreServiceImpl ssmPromotionStoreService;


    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmPromotionDao dao;

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

    @Override
    public PageInfo<PromotionListRequest> selectPage(PromotionListRequest promotionListRequest) {
        return dao.selectPage(promotionListRequest);
    }

    @Override
    public List<Map<String,Object>> selectList(PromotionListRequest promotionListRequest) {
        return dao.selectList(promotionListRequest);
    }

    @Override
    public PageInfo<PromotionList> selectPages(PromotionListRequest promotionListRequest) {
        Long storeId = promotionListRequest.getStoreId();
        ArrayList<PromotionList> objects = new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(promotionListRequest.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                promotionListRequest.setStoreId(pagesorganization.getId());
                break;
            }
        }
        List<PromotionList> promotionLists = dao.selectPages(promotionListRequest);
        for (PromotionList promotionList : promotionLists) {
            if(promotionList.getSuitableStore()==0){
                objects.add(promotionList);
            }else if(promotionList.getSuitableStore()==1){
                PromotionStore promotionStore = new PromotionStore();
                promotionStore.setPromotionId(promotionList.getId());
                List<PromotionStore> promotionStores = ssmPromotionStoreService.selectList(promotionStore);
                for (PromotionStore store : promotionStores) {
                    if(store.getPromotionId() == storeId || storeId.equals(store.getPromotionId())){
                        objects.add(promotionList);
                    }
                }
            }
        }
        PageInfo<PromotionList> pageInfo = new PageInfo<>(objects);
        return pageInfo;
    }

    @Override
    public PageInfo<PromotionList> selectPagenew(PromotionListRequest promotionListRequest) {
        PromotionUnit promotionUnit = new PromotionUnit();
        promotionUnit.setStoreId(promotionListRequest.getStoreId());
        List<Long> bigIntegers = ssmPromotionUnitService.selectallId(promotionUnit);
        promotionListRequest.setPromotionunitId(bigIntegers);
        return dao.selectPagenew(promotionListRequest);
    }

    //    @Override
//    public PageInfo<PromotionListResponse> selectPage(PromotionListRequest promotionListRequest) {
//        PageInfo<PromotionList> pageInfo = dao.selectPage(promotionListRequest);
//        List<PromotionListResponse> responseList = new ArrayList<>();
//        for (PromotionList promotionList : pageInfo.getList()) {
//            PromotionListResponse response = new PromotionListResponse();
//            BeanUtils.copyProperties(promotionList, response);
//            //指定会员
//            if (response.getSuitableObject() == 2){
//                //设置会员列表
//
//            }
//            //设置项目列表
//
//            responseList.add(response);
//        }
//        PageInfo<PromotionListResponse> p = new PageInfo<>(responseList);
//        return p;
//    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addPromotion(PromotionListRequest promotionListRequest) throws SmsException {
        int i = 0;
        //基础信息赋值
        PromotionList promotionList = new PromotionList();
        BeanUtils.copyProperties(promotionListRequest, promotionList);
        Long promotionId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        promotionList.setId(promotionId);
        promotionList.setPromotionNum(this.getNum(promotionListRequest));
        //设置录单人信息
        if (redisClient.hasKey(getKey(promotionListRequest.getStaffPhone()))) {
            promotionList.setCreatedId(redisClient.get(getKey(promotionListRequest.getStaffPhone())).getId());
            promotionList.setCreatedBy(redisClient.get(getKey(promotionListRequest.getStaffPhone())).getStaffName());
            promotionList.setCreatedDate(new Date());
        }
        //设置状态
        promotionList.setState(0);
        //适用对象是指定会员时将指定会员插入促销会员记录表
        if (promotionList.getSuitableObject() == 2){

            List<PromotionMember> memberList = promotionListRequest.getPromotionMemberLists();
            if(memberList==null || memberList.size()==0){
                throw new SmsException("50099","会员不能为空");
            }
            ssmPromotionMemberSevice.addPromotionMember(memberList, promotionList);
        }

        //添加促销项目
        List<PromotionProject> projectList = promotionListRequest.getPromotionProjectLists();
        /*for (PromotionProject promotionProject : projectList) {
            promotionProject.setValidTime(promotionListRequest.getValidTime());
            promotionProject.setUseEndDate(promotionListRequest.getUseEndDate());
        }*/
        ssmPromotionProjectService.addPromotionProject(projectList, promotionList);

        try {
            i = dao.saveNotNull(promotionList);
            //设置使用门店
            if (promotionList.getSuitableStore() == 1){
                List<PromotionStore> promotionStores = promotionListRequest.getPromotionStores();
                for (PromotionStore promotionStore : promotionStores) {
                    promotionStore.setId(new SnowflakeUtil(new Random().nextInt(1021)).nextId());
                    promotionStore.setPromotionId(promotionList.getId());
                    promotionStore.setPromotionNum(promotionList.getPromotionNum());
                    promotionStore.setPromotionName(promotionList.getPromotionName());
                }
                ssmPromotionStoreService.saveBatchPromotionStore(promotionStores);
            }
        }catch (Exception e){
            log.error("SsmPromotionServiceImpl.addPromotion",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }

    @Autowired
    private PromotionRechargeListService promotionRechargeListService;
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addCourseGitRechargePromotion(PromotionListRequest promotionListRequest) throws SmsException {
        int i = 0;
        //基础信息赋值
        PromotionList promotionList = new PromotionList();
        BeanUtils.copyProperties(promotionListRequest, promotionList);
        Long promotionId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        promotionList.setId(promotionId);
        promotionList.setPromotionNum(this.getNum(promotionListRequest));
        //设置录单人信息
        if (redisClient.hasKey(getKey(promotionListRequest.getStaffPhone()))) {
            promotionList.setCreatedId(redisClient.get(getKey(promotionListRequest.getStaffPhone())).getId());
            promotionList.setCreatedBy(redisClient.get(getKey(promotionListRequest.getStaffPhone())).getStaffName());
            promotionList.setCreatedDate(new Date());
        }
        //设置状态
        promotionList.setState(0);
        //适用对象是指定会员时将指定会员插入促销会员记录表
        if (promotionList.getSuitableObject() == 2){

            List<PromotionMember> memberList = promotionListRequest.getPromotionMemberLists();
            if(memberList==null || memberList.size()==0){
                throw new SmsException("50099","会员不能为空");
            }
            ssmPromotionMemberSevice.addPromotionMember(memberList, promotionList);
        }

        //添加促销项目
        List<PromotionProject> projectList = promotionListRequest.getPromotionProjectLists();
        /*for (PromotionProject promotionProject : projectList) {
            promotionProject.setValidTime(promotionListRequest.getValidTime());
            promotionProject.setUseEndDate(promotionListRequest.getUseEndDate());
        }*/
        ssmPromotionProjectService.addPromotionProject(projectList, promotionList);

        //添加充值卡
        if(promotionListRequest.getType()==1 && promotionListRequest.getPromotionRechargeLists()!=null && promotionListRequest.getPromotionRechargeLists().size()>0){
            for (PromotionRechargeList promotionRechargeList : promotionListRequest.getPromotionRechargeLists()) {
                promotionRechargeList.setPromotionId(promotionId);
                promotionRechargeList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            }
            promotionRechargeListService.addPromotionRechargeList(promotionListRequest.getPromotionRechargeLists());
        }

        try {
            i = dao.saveNotNull(promotionList);
            //设置使用门店
            if (promotionList.getSuitableStore() == 1){
                List<PromotionStore> promotionStores = promotionListRequest.getPromotionStores();
                for (PromotionStore promotionStore : promotionStores) {
                    promotionStore.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    promotionStore.setPromotionId(promotionList.getId());
                    promotionStore.setPromotionNum(promotionList.getPromotionNum());
                    promotionStore.setPromotionName(promotionList.getPromotionName());
                }
                ssmPromotionStoreService.saveBatchPromotionStore(promotionStores);
            }
        }catch (Exception e){
            log.error("SsmPromotionServiceImpl.addPromotion",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }

    @Override
    @Transactional
    public int updatePromotionRechargeList(PromotionListRequest promotionListRequest) throws SmsException {
        int i = 0;
        //基础信息赋值
        PromotionList promotionList = new PromotionList();
        BeanUtils.copyProperties(promotionListRequest, promotionList);

        //设置修改人信息
        if (redisClient.hasKey(getKey(promotionListRequest.getStaffPhone()))) {
            promotionList.setUpdatedId(redisClient.get(getKey(promotionListRequest.getStaffPhone())).getId());
            promotionList.setUpdatedBy(redisClient.get(getKey(promotionListRequest.getStaffPhone())).getStaffName());
            promotionList.setUpdateDate(new Date());
        }
        //设置状态
        promotionList.setState(1);
        //适用对象是指定会员时将指定会员插入促销会员记录表
        if (promotionList.getSuitableObject() == 2){
            List<PromotionMember> memberList = promotionListRequest.getPromotionMemberLists();
            ssmPromotionMemberSevice.updatePromotionMember(memberList, promotionList);
        }
        //添加促销项目
        List<PromotionProject> projectList = promotionListRequest.getPromotionProjectLists();
        ssmPromotionProjectService.updatePromotionProject(projectList, promotionList);

        //设置使用门店
        if (promotionList.getSuitableStore() == 1){
            //先删除
            PromotionStore promotionStores = new PromotionStore();
            promotionStores.setPromotionId(promotionList.getId());
            ssmPromotionStoreService.delete(promotionStores);

            List<PromotionStore> memberList = promotionListRequest.getPromotionStores();
            for (PromotionStore promotionStore : memberList) {
                promotionStore.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                promotionStore.setPromotionId(promotionList.getId());
                promotionStore.setPromotionNum(promotionList.getPromotionNum());
                promotionStore.setPromotionName(promotionList.getPromotionName());
                ssmPromotionStoreService.saveNotNull(promotionStore);
            }
        }
        if(promotionListRequest.getType()==1 && promotionListRequest.getPromotionRechargeLists()!=null && promotionListRequest.getPromotionRechargeLists().size()>0){
            //先删除再新增
            PromotionRechargeList rechargeList = new PromotionRechargeList();
            rechargeList.setPromotionId(promotionList.getId());
            promotionRechargeListService.delete(rechargeList);
            for (PromotionRechargeList promotionRechargeList : promotionListRequest.getPromotionRechargeLists()) {
                promotionRechargeList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                promotionRechargeList.setPromotionId(promotionList.getId());
            }
            promotionRechargeListService.addPromotionRechargeList(promotionListRequest.getPromotionRechargeLists());
        }





        try {
            i = dao.updateByPrimaryKeySelective(promotionList);
        }catch (Exception e){
            log.error("SsmPromotionServiceImpl.updatePromotion",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }

    @Override
    public List<PromotionList> selectPromotionType(PromotionListRequest promotionListRequest) {

        return dao.selectPromotionType(promotionListRequest);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int updatePromotion(PromotionListRequest promotionListRequest) throws SmsException {
        int i = 0;
        //基础信息赋值
        PromotionList promotionList = new PromotionList();
        BeanUtils.copyProperties(promotionListRequest, promotionList);

        //设置修改人信息
        if (redisClient.hasKey(getKey(promotionListRequest.getStaffPhone()))) {
            promotionList.setUpdatedId(redisClient.get(getKey(promotionListRequest.getStaffPhone())).getId());
            promotionList.setUpdatedBy(redisClient.get(getKey(promotionListRequest.getStaffPhone())).getStaffName());
            promotionList.setUpdateDate(new Date());
        }
        //设置状态
        promotionList.setState(1);
        //适用对象是指定会员时将指定会员插入促销会员记录表
        if (promotionList.getSuitableObject() == 2){
            List<PromotionMember> memberList = promotionListRequest.getPromotionMemberLists();
            ssmPromotionMemberSevice.updatePromotionMember(memberList, promotionList);
        }
        //添加促销项目
        List<PromotionProject> projectList = promotionListRequest.getPromotionProjectLists();
        ssmPromotionProjectService.updatePromotionProject(projectList, promotionList);

        //设置使用门店
        if (promotionList.getSuitableStore() == 1){
            //先删除
            PromotionStore promotionStores = new PromotionStore();
            promotionStores.setPromotionId(promotionList.getId());
            ssmPromotionStoreService.delete(promotionStores);

            List<PromotionStore> memberList = promotionListRequest.getPromotionStores();
            for (PromotionStore promotionStore : memberList) {
                promotionStore.setId(new SnowflakeUtil(new Random().nextInt(1021)).nextId());
                promotionStore.setPromotionId(promotionList.getId());
                promotionStore.setPromotionNum(promotionList.getPromotionNum());
                promotionStore.setPromotionName(promotionList.getPromotionName());
            }
            ssmPromotionStoreService.saveBatchPromotionStore(memberList);
        }





        try {
            i = dao.updateByPrimaryKeySelective(promotionList);
        }catch (Exception e){
            log.error("SsmPromotionServiceImpl.updatePromotion",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }



    @Override
    public int sendAudit(PromotionListRequest promotionListRequest) throws SmsException {
        int i = 0;
        PromotionList promotionList = new PromotionList();
        promotionList.setState(2);
        if (promotionListRequest.getState() == 3 || promotionListRequest.getState() == 4 ){
            throw new SmsException(ResponseCode.NOT_ALLOW_UPDATE_STATE, "送审");
        }
        promotionList.setId(promotionListRequest.getId());
        i = dao.updateByPrimaryKeySelective(promotionList);
        return i;
    }


    @Override
    public int revokeAudit(PromotionListRequest promotionListRequest) throws SmsException {
        int i = 0;
        PromotionList promotionList = new PromotionList();
        promotionList.setState(3);
        if (promotionListRequest.getState() != 2) {
            throw new SmsException(ResponseCode.NOT_ALLOW_UPDATE_STATE, "回收");
        }
        promotionList.setId(promotionListRequest.getId());
        i = dao.updateByPrimaryKeySelective(promotionList);
        return i;
    }

    @Override
    public int audit(PromotionListRequest promotionListRequest) {
        int i = 0;
        PromotionList promotionList = new PromotionList();
        promotionList.setState(4);
        //设置审核人信息
        if (redisClient.hasKey(getKey(promotionListRequest.getStaffPhone()))) {
            promotionList.setAuditId(redisClient.get(getKey(promotionListRequest.getStaffPhone())).getId());
            promotionList.setAuditBy(redisClient.get(getKey(promotionListRequest.getStaffPhone())).getStaffName());

        }
        Set<String> keys = redisClient.keys(getKey(promotionListRequest.getStaffPhone()) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            promotionList.setAuditId(staffResponse.getId());
            promotionList.setAuditBy(staffResponse.getStaffName());
        }
        promotionList.setAuditDate(new Date());
        promotionList.setId(promotionListRequest.getId());
        i = dao.updateByPrimaryKeySelective(promotionList);
        return i;
    }


    @Override
    public int unAudit(PromotionListRequest promotionListRequest) {
        int i = 0;
        PromotionList promotionList = new PromotionList();
        promotionList.setState(5);
        promotionList.setAuditId(null);
        promotionList.setAuditBy(null);
        promotionList.setAuditDate(null);
        promotionList.setId(promotionListRequest.getId());
        i = dao.updateByPrimaryKeySelective(promotionList);
        return i;
    }

    @Override
    public int shutDown(PromotionListRequest promotionListRequest) throws SmsException {
        int i = 0;
        PromotionList promotionList = new PromotionList();
        if (promotionListRequest.getPushState() != 1) {
            throw new SmsException(ResponseCode.NOT_ALLOW_UPDATE_STATE, "关闭");
        }
        promotionList.setState(6);
        promotionList.setId(promotionListRequest.getId());
        i = dao.updateByPrimaryKeySelective(promotionList);
        return i;
    }

    @Override
    public int push(PromotionListRequest promotionListRequest) {
        int i = 0;
        //向微信会员推送信息

        //更新状态 次数
        PromotionList promotionList = new PromotionList();
        promotionList.setId(promotionListRequest.getId());
        promotionList.setPushState(1);
        promotionList.setPushCount(promotionListRequest.getPushCount() + 1);
        i = dao.updateByPrimaryKeySelective(promotionList);
        return i;
    }

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

    public String getNum(PromotionListRequest promotionListRequest){
        //查询数据库促销方案编码最新的一个
        String ymdDate = DateUtils.YMDFormat(new Date());
        Example example = new Example(PromotionList.class);
        Example.Criteria criteria = example.createCriteria();
        //按门店编码降序排列
        example.setOrderByClause("promotion_num desc");
        String promotionNum="";
        if(promotionListRequest.getType()==0){
            promotionNum = "DBJ";

        }
        if(promotionListRequest.getType()==1 || promotionListRequest.getType()==3){
            promotionNum = "MJS";

        }
        if(promotionListRequest.getType()==2){
            promotionNum = "SXP";

        }
        //通过时间模糊查询
        criteria.andLike("promotionNum",promotionNum+ymdDate + "%");
        criteria.andEqualTo("storeId", promotionListRequest.getStoreId());
        List<PromotionList> promotionLists = dao.selectByExample(example);
        String num;
        int mm = 0;
        if (promotionLists != null && promotionLists.size() > 0) {
            PromotionList promotionList = promotionLists.get(0);
            mm = Integer.parseInt(promotionList.getPromotionNum().substring(11)) + 1;
            if (mm < 10){
                num = "000" + mm;
            }else if (mm < 100){
                num = "00" + mm;
            }else if (mm < 1000){
                num = "0" + mm;
            }else {
                num = String.valueOf(mm);
            }
            promotionNum+= ymdDate + num;

        }else {
            num = "0001" ;
            promotionNum += ymdDate + num;
        }
        return promotionNum;
    }

}
