package com.ssm.manage.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmCourseAccountDao;
import com.ssm.manage.dao.SsmStoreConversionDao;
import com.ssm.manage.dao.SsmStoreMemberDao;
import com.ssm.manage.dao.SsmStoreTurnTreatmentDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.mapper.SsmStoreTurnTreatmentMapper;
import com.ssm.manage.query.*;
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.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class SsmStoreTurnTreatmentServiceImpl  extends BaseServiceImpl<StoreTurnTreatment> implements SsmStoreTurnTreatmentService {


    private static String staffKey = "staffKey";

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmStoreMemberDao ssmStoreMemberDao;

    @Autowired
    private SsmCourseAccountDao ssmCourseAccountDao;



    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;

    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private SsmBaseStaffService ssmBaseStaffService;

    @Autowired
    private SsmStoreTurnTreatmentDao dao;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

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

    @Override
    public PageInfo<StoreTurnTreatmentQuery> selectPage(StoreTurnTreatmentQuery storeConversionQuery) throws SmsException{
        List<StoreTurnTreatment> list =new ArrayList<>();
        Example example = new Example(StoreConversion.class);
        Example.Criteria criteria = example.createCriteria();

        Long tota;

        if(storeConversionQuery.getDate()!=null || (storeConversionQuery.getPhone()!=null&&!storeConversionQuery.getPhone().equals(""))){//手机号码查询
            StoreTurnTreatmentQuery storeTurnTreatmentQuery=new StoreTurnTreatmentQuery();
            storeTurnTreatmentQuery.setPageSize(storeConversionQuery.getPageSize());
            storeTurnTreatmentQuery.setPageNum((storeConversionQuery.getPageNum()-1)*storeConversionQuery.getPageSize());

            if(storeConversionQuery.getPhone()!=null&&!storeConversionQuery.getPhone().equals("")){//手机号码查
                String checkp="";
                try {
                    checkp= AESUtils.encrypt(storeConversionQuery.getPhone());
                }catch (Exception e){
                    e.printStackTrace();
                }
                List<StoreMemberList> memberLists=ssmStoreMemberDao.selectPhone("%"+checkp+"%");
                List<Long> mids=new ArrayList<>();
                if(!storeConversionQuery.getPhone().trim().equals("")&&memberLists.size()==0){
                    throw new SmsException(ResponseCode.MSG,"未查到此手机号的相关信息，请输入正确完整的手机号码");
                }
                if(memberLists.size()>0){
                    for(StoreMemberList storeMemberList:memberLists){
                        mids.add(storeMemberList.getId());
                        storeTurnTreatmentQuery.setMids(mids);
                    }
                }
            }

            SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
            if(storeConversionQuery.getDate()!=null){//日期查
                storeTurnTreatmentQuery.setDateone(sf.format(storeConversionQuery.getDate()));
            }
            if(storeConversionQuery.getStartDate()!=null){
                storeTurnTreatmentQuery.setDateStart(sf.format(storeConversionQuery.getDateStart()));
                storeTurnTreatmentQuery.setDateEnd(sf.format(storeConversionQuery.getDateEnd()));
            }
            list=dao.selectPhon(storeTurnTreatmentQuery);
            tota=Long.valueOf(dao.selectPhonCount(storeTurnTreatmentQuery));
            //缓存分页
            if(list.size()==0&&tota>list.size()){
                //计算页数，从最后一页查询
                Integer count=Integer.valueOf(String.valueOf(tota));
                Integer c=count%storeConversionQuery.getPageSize();
                Integer pages=1;
                if(c==0){
                    pages=count/storeConversionQuery.getPageSize();
                }else{
                    pages=count/storeConversionQuery.getPageSize()+pages;
                }
                storeTurnTreatmentQuery.setPageSize(storeConversionQuery.getPageSize());
                storeTurnTreatmentQuery.setPageNum((pages-1)*storeConversionQuery.getPageSize());
                list =dao.selectPhon(storeTurnTreatmentQuery);
            }


        }
        else{

            if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getStoreId()))&& null != storeConversionQuery.getStoreId()){
                criteria.andEqualTo("storeId",storeConversionQuery.getStoreId());
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getStoreNum())&& null != storeConversionQuery.getStoreNum()){
                criteria.andLike("storeNum","%" + storeConversionQuery.getStoreNum() + "%");
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getStoreName())&& null != storeConversionQuery.getStoreName()){
                criteria.andLike("storeName","%" + storeConversionQuery.getStoreName() + "%");
            }
            if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getStoresId()))&& null != storeConversionQuery.getStoresId()){
                criteria.andLike("storesId","%" + storeConversionQuery.getStoresId() + "%");
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getStoresNum())&& null != storeConversionQuery.getStoresNum()){
                criteria.andLike("storesNum","%" + storeConversionQuery.getStoresNum() + "%");
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getStoresName())&& null != storeConversionQuery.getStoresName()){
                criteria.andLike("storesName","%" + storeConversionQuery.getStoresName() + "%");
            }
            if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getStatu()))&& null != storeConversionQuery.getStatu()){
                criteria.andEqualTo("statu",storeConversionQuery.getStatu());
            }
            if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getMemberId()))&& null != storeConversionQuery.getMemberId()){
                criteria.andLike("memberId","%" + storeConversionQuery.getMemberId() + "%");
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getMemberName())&& null != storeConversionQuery.getMemberName()){
                criteria.andLike("memberName","%" + storeConversionQuery.getMemberName() + "%");
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getCourseStoreNum())&& null != storeConversionQuery.getCourseStoreNum()){
                criteria.andLike("courseStoreNum",
                        "%" + storeConversionQuery.getCourseStoreNum()
                                + "%");
            }
            if(storeConversionQuery.getStartTime()!=null && storeConversionQuery.getEndTime()!=null){
                criteria.andBetween("updateDate",storeConversionQuery.getStartTime(),storeConversionQuery.getEndTime());
            }
            storeConversionQuery.setSort("proposerDate");
            PageHelper.startPage(storeConversionQuery.getPageNum(),storeConversionQuery.getPageSize(),storeConversionQuery.getOrderAndSort());
            list = selectByExample(example);
            tota=((Page) list).getTotal();
        }


        List<StoreTurnTreatmentQuery> lists =new ArrayList<>();
        for (StoreTurnTreatment storeTurnTreatment : list) {
            StoreTurnTreatmentQuery storeTurnTreatmentQuery = new StoreTurnTreatmentQuery();
            BeanUtils.copyProperties(storeTurnTreatment,storeTurnTreatmentQuery);
            CourseAccount courseAccount = new CourseAccount();
            courseAccount.setId(storeTurnTreatment.getCourseAccountId());
            courseAccount = ssmCourseAccountService.selectOne(courseAccount);

            storeTurnTreatmentQuery.setCourseRestPrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseRestCount())));
            storeTurnTreatmentQuery.setCourseConsumePrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseConsumeCount())));
            BaseProject baseProject1 = new BaseProject();
            baseProject1.setId(courseAccount.getCourseProjectId());
            BaseProject baseProject = ssmProjectService.selectOne(baseProject1);
            if(null != baseProject){
                storeTurnTreatmentQuery.setCourseProjectNum(baseProject.getProjectNum());
            }
            StoreMemberList memberRequest = new StoreMemberList();
            memberRequest.setId(storeTurnTreatment.getMemberId());
            StoreMemberList storeMemberList = ssmStoreMemberService.selectOne(memberRequest);
            if(null != storeMemberList){
                storeTurnTreatmentQuery.setMemberNum(storeMemberList.getMemberNum());
            }
            if(storeMemberList.getMobilePhone()!=null && storeMemberList.getMobilePhone().length()>0){
                try {
                    storeTurnTreatmentQuery.setPhone(AESUtils.decrypt(storeMemberList.getMobilePhone()).trim().replace("\u0000",""));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            lists.add(storeTurnTreatmentQuery);

        }

        PageInfo<StoreTurnTreatmentQuery> pageInfo = new PageInfo<>(lists);
        pageInfo.setTotal(tota);
        return pageInfo;
    }


    @Override
    public List<StoreTurnTreatmentQuery> exportachis(StoreTurnTreatmentQuery storeConversionQuery) throws SmsException{
        List<StoreTurnTreatment> list =new ArrayList<>();
        Example example = new Example(StoreConversion.class);
        Example.Criteria criteria = example.createCriteria();


        if(storeConversionQuery.getDate()!=null||(storeConversionQuery.getPhone()!=null&&!storeConversionQuery.getPhone().equals(""))){//手机号码查询
            StoreTurnTreatmentQuery storeTurnTreatmentQuery=new StoreTurnTreatmentQuery();
            storeTurnTreatmentQuery.setPageSize(storeConversionQuery.getPageSize());
            storeTurnTreatmentQuery.setPageNum((storeConversionQuery.getPageNum()-1)*storeConversionQuery.getPageSize());

            if(storeConversionQuery.getPhone()!=null&&!storeConversionQuery.getPhone().equals("")){//手机号码查
                String checkp="";
                try {
                    checkp= AESUtils.encrypt(storeConversionQuery.getPhone());
                }catch (Exception e){
                    e.printStackTrace();
                }
                List<StoreMemberList> memberLists=ssmStoreMemberDao.selectPhone("%"+checkp+"%");
                List<Long> mids=new ArrayList<>();
                if(!storeConversionQuery.getPhone().trim().equals("")&&memberLists.size()==0){
                    throw new SmsException(ResponseCode.MSG,"未查到此手机号的相关信息，请输入正确完整的手机号码");
                }
                if(memberLists.size()>0){
                    for(StoreMemberList storeMemberList:memberLists){
                        mids.add(storeMemberList.getId());
                        storeTurnTreatmentQuery.setMids(mids);
                    }
                }
            }
            SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
            if(storeConversionQuery.getDate()!=null){//日期查
                storeTurnTreatmentQuery.setDateone(sf.format(storeConversionQuery.getDate()));
            }
            if(storeConversionQuery.getStartDate()!=null){
                storeTurnTreatmentQuery.setDateStart(sf.format(storeConversionQuery.getDateStart()));
                storeTurnTreatmentQuery.setDateEnd(sf.format(storeConversionQuery.getDateEnd()));
            }
            list=dao.exportachis(storeTurnTreatmentQuery);
            //缓存分页
        }
        else{
            if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getStoreId()))&& null != storeConversionQuery.getStoreId()){
                criteria.andEqualTo("storeId",storeConversionQuery.getStoreId());
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getStoreNum())&& null != storeConversionQuery.getStoreNum()){
                criteria.andLike("storeNum","%" + storeConversionQuery.getStoreNum() + "%");
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getStoreName())&& null != storeConversionQuery.getStoreName()){
                criteria.andLike("storeName","%" + storeConversionQuery.getStoreName() + "%");
            }
            if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getStoresId()))&& null != storeConversionQuery.getStoresId()){
                criteria.andLike("storesId","%" + storeConversionQuery.getStoresId() + "%");
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getStoresNum())&& null != storeConversionQuery.getStoresNum()){
                criteria.andLike("storesNum","%" + storeConversionQuery.getStoresNum() + "%");
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getStoresName())&& null != storeConversionQuery.getStoresName()){
                criteria.andLike("storesName","%" + storeConversionQuery.getStoresName() + "%");
            }
            if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getStatu()))&& null != storeConversionQuery.getStatu()){
                criteria.andEqualTo("statu",storeConversionQuery.getStatu());
            }
            if (StringUtils.isNotBlank(String.valueOf(storeConversionQuery.getMemberId()))&& null != storeConversionQuery.getMemberId()){
                criteria.andLike("memberId","%" + storeConversionQuery.getMemberId() + "%");
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getMemberName())&& null != storeConversionQuery.getMemberName()){
                criteria.andLike("memberName","%" + storeConversionQuery.getMemberName() + "%");
            }
            if (StringUtils.isNotBlank(storeConversionQuery.getCourseStoreNum())&& null != storeConversionQuery.getCourseStoreNum()){
                criteria.andLike("courseStoreNum",
                        "%" + storeConversionQuery.getCourseStoreNum()
                                + "%");
            }
            if(storeConversionQuery.getStartTime()!=null && storeConversionQuery.getEndTime()!=null){
                criteria.andBetween("updateDate",storeConversionQuery.getStartTime(),storeConversionQuery.getEndTime());
            }
            storeConversionQuery.setSort("proposerDate");
            list = selectByExample(example);
        }


        List<StoreTurnTreatmentQuery> lists =new ArrayList<>();
        for (StoreTurnTreatment storeTurnTreatment : list) {
            StoreTurnTreatmentQuery storeTurnTreatmentQuery = new StoreTurnTreatmentQuery();
            BeanUtils.copyProperties(storeTurnTreatment,storeTurnTreatmentQuery);
            CourseAccount courseAccount = new CourseAccount();
            courseAccount.setId(storeTurnTreatment.getCourseAccountId());
            courseAccount = ssmCourseAccountService.selectOne(courseAccount);

            storeTurnTreatmentQuery.setCourseRestPrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseRestCount())));
            storeTurnTreatmentQuery.setCourseConsumePrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseConsumeCount())));
            BaseProject baseProject1 = new BaseProject();
            baseProject1.setId(courseAccount.getCourseProjectId());
            BaseProject baseProject = ssmProjectService.selectOne(baseProject1);
            if(null != baseProject){
                storeTurnTreatmentQuery.setCourseProjectNum(baseProject.getProjectNum());
            }
            StoreMemberList memberRequest = new StoreMemberList();
            memberRequest.setId(storeTurnTreatment.getMemberId());
            StoreMemberList storeMemberList = ssmStoreMemberService.selectOne(memberRequest);
            if(null != storeMemberList){
                storeTurnTreatmentQuery.setMemberNum(storeMemberList.getMemberNum());
            }
            if(storeMemberList.getMobilePhone()!=null && storeMemberList.getMobilePhone().length()>0){
                try {
                    storeTurnTreatmentQuery.setPhone(AESUtils.decrypt(storeMemberList.getMobilePhone()).trim().replace("\u0000",""));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            lists.add(storeTurnTreatmentQuery);

        }

        return lists;
    }


    public String getGiveNum(String s) {
        //查询数据库充值单编码最新的一个
        String ymdDate = DateUtils.YMDFormat(new Date());
        StoreTurnTreatment rechargeAccountGive = new StoreTurnTreatment();
        rechargeAccountGive.setCourseStoreNum(s+ymdDate);
        List<StoreTurnTreatment> ssmRechargeAccountGiveDaoDocNum = dao.getDocNum(rechargeAccountGive);
        String num;
        int mm = 0;
        if (ssmRechargeAccountGiveDaoDocNum != null && ssmRechargeAccountGiveDaoDocNum.size() > 0) {
            StoreTurnTreatment courseList = ssmRechargeAccountGiveDaoDocNum.get(0);
            int a = s.length();
            mm = Integer.parseInt(courseList.getCourseStoreNum().substring(8 + a)) + 1;
            if (mm < 10) {
                num = "00" + mm;
            } else if (mm < 100) {
                num = "0" + mm;
            } else {
                num = String.valueOf(mm);
            }
            s +=  ymdDate + num;

        } else {
            num = "001";
            s += ymdDate + num;
        }
        return s;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int add(List<StoreTurnTreatmentRequesttow> list, String phone)throws  SmsException {

        List<StoreTurnTreatment> storeConversion=new ArrayList<>();
        String memberPhone=list.get(0).getMobilePhone();
        for(StoreTurnTreatmentRequesttow storeTurnTreatmentRequesttow:list){
            StoreTurnTreatment storeTurnTreatment=new StoreTurnTreatment();
            BeanUtils.copyProperties(storeTurnTreatmentRequesttow,storeTurnTreatment);
            storeConversion.add(storeTurnTreatment);
        }

        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        int i=0;
        for (StoreTurnTreatment conversion : storeConversion) {
            conversion.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateNowStr = sdf.format(d);
            String num = this.getNum(dateNowStr,conversion.getStoreId());
            conversion.setOrderCode(num);
            conversion.setProposerName(staffResponse.getStaffName());
            conversion.setProposerId(staffResponse.getId());
            conversion.setProposerDate(new Date());
            conversion.setStatu(0);
            String courseStoreNum = this.getGiveNum("LCZMD");
            conversion.setCourseStoreNum(courseStoreNum);
            int insert = dao.insert(conversion);
            /*if(insert>=1){
                try{
                    AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(conversion,memberPhone);
                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                }catch (Exception e){
                    log.error("SsmStoreTurnTreatmentController.add:", e);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                }
            }*/

            i+=insert;
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int delete(List<StoreTurnTreatmentRequesttow> list, String phone)throws  SmsException {

        List<StoreTurnTreatment> storeConversion=new ArrayList<>();
        String memberPhone=list.get(0).getMobilePhone();
        for(StoreTurnTreatmentRequesttow storeTurnTreatmentRequesttow:list){
            StoreTurnTreatment storeTurnTreatment=new StoreTurnTreatment();
            BeanUtils.copyProperties(storeTurnTreatmentRequesttow,storeTurnTreatment);
            storeConversion.add(storeTurnTreatment);
        }

        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        int i=0;
        for (StoreTurnTreatment conversion : storeConversion) {
            conversion.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateNowStr = sdf.format(d);
            String num = this.getNum(dateNowStr,conversion.getStoreId());
            conversion.setOrderCode(num);
            conversion.setProposerName(staffResponse.getStaffName());
            conversion.setProposerId(staffResponse.getId());
            conversion.setProposerDate(new Date());
            conversion.setStatu(0);
            int insert = dao.insert(conversion);
            /*if(insert>=1){
                try{
                    AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(conversion,memberPhone);
                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                }catch (Exception e){
                    log.error("SsmStoreTurnTreatmentController.add:", e);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                }
            }*/

            i+=insert;
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int updateStatu(StoreTurnTreatmentQuery storeConversion, String phone)throws  SmsException {

        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }

        Example example = new Example(StoreTurnTreatment.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id",storeConversion.getIds());
        List<StoreTurnTreatment> list = dao.selectByExample(example);
        int i =0;
        for (StoreTurnTreatment conversion : list) {
            if(conversion.getStatu()==2){
                throw new SmsException(ResponseCode.MSG,"审核操作失败，已审核过");
            }
//            if(storeConversion.getStatu()==4){
//                i += dao.delete(conversion);
//            }else {


            conversion.setUpdateId(staffResponse.getId());
            conversion.setUpdateName(staffResponse.getStaffName());
            conversion.setUpdateDate(new Date());
            conversion.setStatu(storeConversion.getStatu());
            int update = dao.updateByPrimaryKey(conversion);

            if(update==0){
                throw new RuntimeException("审核失败");
            }else{
                if(storeConversion.getStatu()==2){
                    //添加一条交易记录
                    try{
                        StoreMemberList storeMember=ssmStoreMemberDao.selectByPrimaryKey(conversion.getMemberId());
                        String memberPhone=AESUtils.decrypt(storeMember.getMobilePhone());
                        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(conversion,memberPhone.trim());
                        ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                        AccountTradeRecord accountTradeRecord1 = this.setAccountTradeZCMD(conversion, memberPhone.trim());
                        ssmAccountTradeRecordService.addRecord(accountTradeRecord1);
                    }catch (Exception e){
                        log.error("SsmStoreTurnTreatmentController.add:", e);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                    }


                    CourseAccount courseAccount = new CourseAccount();
                    courseAccount.setId(conversion.getCourseAccountId());
                    CourseAccount courseAccount1 = ssmCourseAccountService.selectOne(courseAccount);
                    courseAccount1.setStoreId(conversion.getStoreId());
                    courseAccount1.setStoreName(conversion.getStoreName());
                    int i1 = ssmCourseAccountService.updateStore(courseAccount1);

                    //ssmAccountTradeRecordService
                    courseAccount1.getCourseNum();


                    if(i1==0){
                        throw new RuntimeException("审核失败");
                    }
                }
                i++;
            }
//          }
        }
        return i;
    }

    @Override
    public List<StoreTurnTreatment> selectFKJ(StoreTurnTreatment storeTurnTreatment) {
        return dao.selectFKJ(storeTurnTreatment);
    }
    @Override
    public List<StoreTurnTreatment> selectFKJOut(StoreTurnTreatment storeTurnTreatment) {
        return dao.selectFKJOut(storeTurnTreatment);
    }

    @Autowired
    private SsmStoreTurnTreatmentMapper mapper;
    @Override
    public List<StoreTurnTreatment> selectFKJByDate(StoreTurnTreatment storeTurnTreatment) {
        return mapper.selectFKJByDate(storeTurnTreatment);
    }
    @Override
    public List<StoreTurnTreatment> selectFKJOutByDate(StoreTurnTreatment storeTurnTreatment) {
        return mapper.selectFKJOutByDate(storeTurnTreatment);
    }


    public String getNum(String date,Long storeId){
        Example example = new Example(StoreTurnTreatment.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("orderCode","%" + date + "%");
        criteria.andEqualTo("storeId",storeId);
        List<StoreTurnTreatment> list = dao.selectByExample(example);
        String num=null;
        if(null != list){
            if(list.size()>0 ){
                if(list.size()>999){
                    num = date+(list.size()+1);
                }else  if(list.size()>99){
                    num = date+"0"+(list.size()+1);
                }else  if(list.size()>9){
                    num = date+"00"+(list.size()+1);
                }else{
                    num = date+"000"+(list.size()+1);
                }
            }else{
                num = date+"0001";
            }
        }else{
            num = date+"0001";
        }
        return num.replace("-","");
    }

    public String getStaffKey(String phone){
        return staffKey + phone;
    }

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


    /*
     * 账户交易记录属性赋值 疗程
     * */
    public AccountTradeRecord setAccountTradeRecord(StoreTurnTreatment storeTurnTreatment,String phone){
        CourseAccount courseAccount=ssmCourseAccountDao.selectByPrimaryKey(storeTurnTreatment.getCourseAccountId());

        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(storeTurnTreatment.getStoreId());
        accountTradeRecord.setStoreName(storeTurnTreatment.getStoreName());
        accountTradeRecord.setMemberId(storeTurnTreatment.getMemberId());
        accountTradeRecord.setMemberName(storeTurnTreatment.getMemberName());

        //accountTradeRecord.setMemberIdentity(courseList.getMemberIdentity());

        accountTradeRecord.setMemberPhone(phone);
        accountTradeRecord.setAccountId(storeTurnTreatment.getCourseAccountId());
        accountTradeRecord.setAccountName(storeTurnTreatment.getCourseProjectName());

        //accountTradeRecord.setAccountInMoney(courseList.getCourseReatmentAmount());
        //accountTradeRecord.setAdditionDate(courseList.getAdditionDate());
        accountTradeRecord.setAccountType(Constant.account_type_project);

        accountTradeRecord.setInputDate(storeTurnTreatment.getUpdateDate());
        accountTradeRecord.setInputBy(storeTurnTreatment.getProposerName());
            //accountTradeRecord.setAccountInCount(courseAccount.getCourseCount());
            //accountTradeRecord.setAccountInMoney(courseAccount.getCourseRestPrice());
       /* else {
            accountTradeRecord.setAccountType(Constant.account_type_project_cancel);
            accountTradeRecord.setInputDate(courseList.getCancelDate());
            accountTradeRecord.setInputBy(courseList.getCancelBy());
            accountTradeRecord.setAccountSpendCount(courseAccount.getCourseCount());
            accountTradeRecord.setAccountSpendMoney(courseAccount.getCourseRestPrice());
        }*/
        accountTradeRecord.setIsAddition(0);
        accountTradeRecord.setDocId(storeTurnTreatment.getCourseAccountId());

        //accountTradeRecord.setDebtMoney(courseList.getDebtMoney());
        //accountTradeRecord.setPrice(courseList.getSalesPrice());

        accountTradeRecord.setDocNum(storeTurnTreatment.getCourseStoreNum());
//        accountTradeRecord.setDocType(Constant.doc_type_card_use+"_store");
        accountTradeRecord.setDocType("LCZRMD");
        accountTradeRecord.setTradeId(storeTurnTreatment.getCourseProjectId());
        accountTradeRecord.setOrderStatu(0);

        accountTradeRecord.setTradeName(storeTurnTreatment.getCourseProjectName());
        accountTradeRecord.setTradeMoney(storeTurnTreatment.getCourseProjectMoney());
        accountTradeRecord.setTradeCount(storeTurnTreatment.getCourseCount());
        accountTradeRecord.setAccountRestCount(storeTurnTreatment.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(storeTurnTreatment.getCourseConsumeCount());
        accountTradeRecord.setAccountRestMoney(storeTurnTreatment.getCourseRestPrice());
        accountTradeRecord.setAccountConsumeMoney(storeTurnTreatment.getCourseConsumePrice());
        //accountTradeRecord.setCardMoney(courseList.getCollectionRechargeAmount());
        //accountTradeRecord.setCashMoney(courseList.getCollectionCashAmount());
        return accountTradeRecord;
    }
public AccountTradeRecord setAccountTradeZCMD(StoreTurnTreatment storeTurnTreatment,String phone){
        CourseAccount courseAccount=ssmCourseAccountDao.selectByPrimaryKey(storeTurnTreatment.getCourseAccountId());

        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(storeTurnTreatment.getStoresId());
        accountTradeRecord.setStoreName(storeTurnTreatment.getStoresName());
        accountTradeRecord.setMemberId(storeTurnTreatment.getMemberId());
        accountTradeRecord.setMemberName(storeTurnTreatment.getMemberName());

        //accountTradeRecord.setMemberIdentity(courseList.getMemberIdentity());

        accountTradeRecord.setMemberPhone(phone);
        accountTradeRecord.setAccountId(storeTurnTreatment.getCourseAccountId());
        accountTradeRecord.setAccountName(storeTurnTreatment.getCourseProjectName());

        //accountTradeRecord.setAccountInMoney(courseList.getCourseReatmentAmount());
        //accountTradeRecord.setAdditionDate(courseList.getAdditionDate());
        accountTradeRecord.setAccountType(Constant.account_type_project);

        accountTradeRecord.setInputDate(storeTurnTreatment.getUpdateDate());
        accountTradeRecord.setInputBy(storeTurnTreatment.getProposerName());
            //accountTradeRecord.setAccountInCount(courseAccount.getCourseCount());
            //accountTradeRecord.setAccountInMoney(courseAccount.getCourseRestPrice());
       /* else {
            accountTradeRecord.setAccountType(Constant.account_type_project_cancel);
            accountTradeRecord.setInputDate(courseList.getCancelDate());
            accountTradeRecord.setInputBy(courseList.getCancelBy());
            accountTradeRecord.setAccountSpendCount(courseAccount.getCourseCount());
            accountTradeRecord.setAccountSpendMoney(courseAccount.getCourseRestPrice());
        }*/
        accountTradeRecord.setIsAddition(0);
        accountTradeRecord.setDocId(storeTurnTreatment.getCourseAccountId());

        //accountTradeRecord.setDebtMoney(courseList.getDebtMoney());
        //accountTradeRecord.setPrice(courseList.getSalesPrice());

        accountTradeRecord.setDocNum(storeTurnTreatment.getCourseStoreNum());
//        accountTradeRecord.setDocType(Constant.doc_type_card_use+"_store");
        accountTradeRecord.setDocType("LCZCMD");
        accountTradeRecord.setTradeId(storeTurnTreatment.getCourseProjectId());
        accountTradeRecord.setOrderStatu(0);

        accountTradeRecord.setTradeName(storeTurnTreatment.getCourseProjectName());
        accountTradeRecord.setTradeMoney(storeTurnTreatment.getCourseProjectMoney());
        accountTradeRecord.setTradeCount(storeTurnTreatment.getCourseCount());
        accountTradeRecord.setAccountRestCount(storeTurnTreatment.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(storeTurnTreatment.getCourseConsumeCount());
        accountTradeRecord.setAccountRestMoney(storeTurnTreatment.getCourseRestPrice());
        accountTradeRecord.setAccountConsumeMoney(storeTurnTreatment.getCourseConsumePrice());
        //accountTradeRecord.setCardMoney(courseList.getCollectionRechargeAmount());
        //accountTradeRecord.setCashMoney(courseList.getCollectionCashAmount());
        return accountTradeRecord;
    }

}
