package com.ssm.manage.service.impl;

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.core.utils.StoreParaUtils;
import com.ssm.manage.dao.SsmMemberInitDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.StaffStatistic;
import com.ssm.manage.mapper.MemberInitMapper;
import com.ssm.manage.mapper.MemberInitStaffMapper;
import com.ssm.manage.query.MemberInitRequest;
import com.ssm.manage.query.MemberRequest;
import com.ssm.manage.query.RechargeTypeRequest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.MemberInitResponse;
import com.ssm.manage.response.MemberResponse;
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 tk.mybatis.mapper.entity.Example;

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

@Service
@Slf4j
public class SsmMemberInitServiceImpl extends BaseServiceImpl<MemberInit> implements SsmMemberInitService {
    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private MemberInitStaffMapper memberInitStaffMapper;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @Autowired
    private SsmRechargeAccountGiveService ssmRechargeAccountGiveService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmDebtService ssmDebtService;

    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;

    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private SsmRechargeTypeSevice ssmRechargeTypeSevice;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmMemberInitDao dao;

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

    @Override
    public PageInfo<MemberInit> selectPage(MemberInitRequest memberInitRequest) {
        return dao.selectPage(memberInitRequest);
    }

    @Override
    public int add(MemberInitRequest memberInitRequest,String phone) throws SmsException {
        MemberInit memberInit = new MemberInit();
        //初始化记录添加单据号
        String initNum = this.getNum(memberInitRequest.getStoreId());
        BeanUtils.copyProperties(memberInitRequest, memberInit);
        memberInit.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        memberInit.setInitNum(initNum);
        if(null == memberInitRequest.getValidTime() || 0 == memberInitRequest.getValidTime()){
            memberInit.setEndTime(null);
        }else{
            memberInit.setEndTime(DateUtils.diffMonth(new Date(), memberInitRequest.getValidTime()));
        }

        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getKey(phone))){
            staffResponse = redisClient.get(getKey(phone));
        }
        Set<String> keys = redisClient.keys(getKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        //设置修改人信息
        memberInit.setModifyId(staffResponse.getId());
        memberInit.setModifyBy(staffResponse.getStaffName());
        memberInit.setModifyDate(new Date());

        //设置录入人信息
        memberInit.setInputId(staffResponse.getId());
        memberInit.setInputBy(staffResponse.getStaffName());
        memberInit.setInputDate(new Date());

//        MemberRequest memberRequest = new MemberRequest();
//        BeanUtils.copyProperties(memberInitRequest, memberRequest);
//        MemberResponse memberResponse = ssmStoreMemberService.selectOne(memberRequest);
//        if (null != memberResponse) {
//            memberInit.setMemberId(memberResponse.getId());
//        }
//        else {
//            memberInit.setMemberId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
//        }
        memberInit.setInitState(1);
//        if (memberInit.getCardType() == 0){
//            RechargeType rechargeType = new RechargeType();
//            BeanUtils.copyProperties(memberInitRequest, rechargeType);
//            rechargeType.setRechargeTypeName(memberInit.getTradeName());
//            //TODO 关于状态问题
//            rechargeType = ssmRechargeTypeSevice.selectOne(rechargeType);
//            memberInit.setTradeId(rechargeType.getId());
//        }else {
//            BaseProject baseProject = new BaseProject();
//            BeanUtils.copyProperties(memberInitRequest, baseProject);
//            baseProject.setProjectName(memberInit.getTradeName());
//            baseProject = ssmProjectService.selectOne(baseProject);
//            memberInit.setTradeId(baseProject.getId());
//        }

//        //初始化账户
//        Long accountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
//        if (memberInitRequest.getCardType() == 0){
//            //充值账户
//            RechargeAccount rechargeAccount = new RechargeAccount();
//            BeanUtils.copyProperties(memberInitRequest, rechargeAccount);
//            rechargeAccount.setId(accountId);
//            rechargeAccount.setRechargeNum(memberInit.getDocNum());
//            rechargeAccount.setCardRestMoney(memberInit.getRestMoney());
//            rechargeAccount.setCardConsumeMoney(memberInit.getCardConsumeMoney());
////            rechargeAccount.setRechargeTypeId(memberInit.getTradeId());
//            rechargeAccount.setRechargeTypeName(memberInit.getTradeName());
//        }else {
//            //疗程账户
//
//        }
//        memberInit.setAccountId(accountId);
//        /**
//         * 判断是否有员工
//         */
//        if(memberInit.getCardType()==1){
//            if(memberInitRequest.getMemberInitStaffList()!=null && memberInitRequest.getMemberInitStaffList().size()>0){
//                List<MemberInitStaff> memberInitStaffList = memberInitRequest.getMemberInitStaffList();
//                for (MemberInitStaff memberInitStaff : memberInitStaffList) {
//                    if(memberInitStaff.getId()!=null) {
//                        memberInitStaff.setProjectId(memberInit.getTradeId());
//                        BaseProject baseProject = ssmProjectService.selectByPrimaryKey(memberInitStaff.getProjectId());
//                        memberInitStaff.setStaffId(memberInitStaff.getId());
//                        BeanUtils.copyProperties(baseProject, memberInitStaff);
//                        memberInitStaff.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
//                        memberInitStaff.setDocNum(initNum);
//                        memberInitStaff.setDocDate(new Date());
//                        memberInitStaff.setState(1);
//                        memberInitStaff.setMoney(memberInit.getCourseConsumePrice());
//                        memberInitStaff.setStoreId(memberInit.getStoreId());
//                        if(baseProject.getIsCooperation()!=null && baseProject.getIsCooperation()==1){
//                            //判断是固定抽成还是比例 1是比例2是固定
//                            if(baseProject.getSmokeCommissionWay()!=null && baseProject.getSmokeCommissionWay()==1){
//                                memberInitStaff.setIsCooperation(1);
//                                memberInitStaff.setBrokerage(baseProject.getBrokerage());
//                            }else if(baseProject.getSmokeCommissionWay()!=null && baseProject.getSmokeCommissionWay()==0){
//                                memberInitStaff.setIsCooperation(2);
//                                memberInitStaff.setBrokerage(baseProject.getBrokerage());
//                            }
//                        }
////                        memberInitStaffMapper.insert(memberInitStaff);
//                    }
//                }
//            }
//            if(memberInitRequest.getSalesmanList()!=null && memberInitRequest.getSalesmanList().size()>0){
//                List<Salesman> salesmanList = memberInitRequest.getSalesmanList();
//                for (Salesman salesman : salesmanList) {
//                    if(salesman.getId()!=null) {
//                        salesman.setStaffId(memberInit.getId());
//                        salesman.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
//                        salesman.setOrderId(memberInit.getId().toString());
//                        salesman.setOrderType(2);
//                        salesman.setOrderDate(memberInit.getDocDate());
//                        salesman.setProjectId(memberInit.getTradeId());
//                        salesman.setProjectNum(memberInit.getOldProjectNum());
//                        salesman.setStoreId(memberInit.getStoreId());
//                        salesman.setMoney(memberInit.getCourseRestPrice());
//                        salesman.setOrderNum(initNum);
//                        salesman.setState(1);
//                        salesman.setStoreName(memberInit.getStoreName());
//                        salesman.setStoreIdOrder(memberInit.getStoreId());
//                        salesman.setIsAddition(0);
//                        salesman.setOperatorBy(memberInit.getInputBy());
////                        ssmSalesmanService.save(salesman);
//                    }
//                }
//            }
//        }
        return dao.saveNotNull(memberInit);
    }


    @Override
    public int update(List<MemberInitRequest> requests, String phone) {
        List<MemberInit> list = new ArrayList<>();
        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getKey(phone))){
            staffResponse = redisClient.get(getKey(phone));
        }
        Set<String> keys = redisClient.keys(getKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        for (MemberInitRequest memberInitRequest : requests) {
            MemberInit memberInit = new MemberInit();
            BeanUtils.copyProperties(memberInitRequest, memberInit);
            //设置修改人信息
            memberInit.setModifyId(staffResponse.getId());
            memberInit.setModifyBy(staffResponse.getStaffName());
            memberInit.setModifyDate(new Date());
            list.add(memberInit);
            /**
             * 判断是否有员工
             */
            if(memberInit.getCardType()==1) {
                if (memberInitRequest.getMemberInitStaffList() != null && memberInitRequest.getMemberInitStaffList().size() > 0) {
                    List<MemberInitStaff> memberInitStaffList = memberInitRequest.getMemberInitStaffList();
                    MemberInitStaff staff = new MemberInitStaff();
                    staff.setDocNum(memberInitRequest.getInitNum());
//                    memberInitStaffMapper.delete(staff);
                    for (MemberInitStaff memberInitStaff : memberInitStaffList) {
                        if (memberInitStaff.getId() != null) {
                            memberInitStaff.setProjectId(memberInit.getTradeId());
                            BaseProject baseProject = ssmProjectService.selectByPrimaryKey(memberInitStaff.getProjectId());
                            memberInitStaff.setStaffId(memberInitStaff.getId());
                            BeanUtils.copyProperties(baseProject, memberInitStaff);
                            memberInitStaff.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                            memberInitStaff.setDocNum(memberInitRequest.getInitNum());
                            memberInitStaff.setDocDate(new Date());
                            memberInitStaff.setState(1);
                            memberInitStaff.setStoreId(memberInit.getStoreId());
                            memberInitStaff.setMoney(memberInit.getCourseConsumePrice());
//                            memberInitStaffMapper.insert(memberInitStaff);
                        }
                    }
                }
                if (memberInitRequest.getSalesmanList() != null && memberInitRequest.getSalesmanList().size() > 0) {
                    List<Salesman> salesmanList = memberInitRequest.getSalesmanList();
                    Salesman salesman1 = new Salesman();
                    salesman1.setOrderNum(memberInitRequest.getInitNum());
//                    try {
//                        ssmSalesmanService.delete(salesman1);
//                    } catch (SmsException e) {
//                        throw new RuntimeException(e);
//                    }
                    for (Salesman salesman : salesmanList) {
                        if (salesman.getId() != null) {
                            salesman.setStaffId(memberInit.getId());
                            salesman.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                            salesman.setOrderId(memberInit.getId().toString());
                            salesman.setOrderType(2);
                            salesman.setOrderDate(memberInit.getDocDate());
                            salesman.setProjectId(memberInit.getTradeId());
                            salesman.setProjectNum(memberInit.getOldProjectNum());
                            salesman.setStoreId(memberInit.getStoreId());
                            salesman.setMoney(memberInit.getCourseRestPrice());
                            salesman.setOrderNum(memberInitRequest.getInitNum());
                            salesman.setState(1);
                            salesman.setStoreName(memberInit.getStoreName());
                            salesman.setStoreIdOrder(memberInit.getStoreId());
                            salesman.setIsAddition(0);
                            salesman.setOperatorBy(memberInit.getInputBy());
//                            ssmSalesmanService.save(salesman);
                        }
                    }
                }
            }

        }

        return dao.updateBatch(list);
    }

    @Override
    public int insertBatch(List<MemberInit> list,String phone) {
        //初始化记录添加单据号
        //String initNum = this.getNum(storeId);

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

        for (MemberInit memberInit : list) {
            //设置修改人信息
            memberInit.setModifyId(staffResponse.getId());
            memberInit.setModifyBy(staffResponse.getStaffName());
            memberInit.setModifyDate(new Date());

            //初始化记录添加单据号
            String initNum = this.getNum(memberInit.getStoreId());
            memberInit.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            memberInit.setInitNum(initNum);
            memberInit.setInitState(1);
            int mm = Integer.parseInt(initNum.substring(initNum.length()-5, initNum.length())) + 1;
            String ymdNum = initNum.substring(2, initNum.length()-5);
            String num;
            if (mm < 10){
                num = "0000" + mm;
            }else if (mm < 100){
                num = "000" + mm;
            }else if (mm < 1000){
                num = "00" + mm;
            }else if (mm < 10000){
                num = "0" + mm;
            }else {
                num = String.valueOf(mm);
            }
            initNum = "CS" + ymdNum + num;
        }
        return  dao.insertBatch(list);
    }


    //校验上传列表数据是否存在异常
    public PageInfo<MemberInitResponse> checkList(MemberInitRequest memberInitRequest)throws SmsException{
        Long storeid = null;
        String storeName = null;
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(memberInitRequest.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                storeid=pagesorganization.getId();
                storeName=pagesorganization.getStoreName();
                break;
            }
        }

//        List<MemberInit> unusualList = new ArrayList<>();
        List<MemberInitResponse> unusualList = new ArrayList<>();
        RechargeTypeRequest rechargeTypeRequest = new RechargeTypeRequest();
        rechargeTypeRequest.setStoreId(storeid);
        List<RechargeType> rechargeTypeList = ssmRechargeTypeSevice.selectList(rechargeTypeRequest,storeid);
        BaseProject baseProject = new BaseProject();
        baseProject.setStoreId(memberInitRequest.getStoreId());
        List<BaseProject> projectList = ssmProjectService.select(baseProject);
        //会员列表
        StoreMemberList storeMemberList = new StoreMemberList();
//        BeanUtils.copyProperties(memberInitRequest, storeMemberList);
        //todo 查询所有会员
//        storeMemberList.setStoreId(storeid);
        storeMemberList.setStoreName(null);
        List<StoreMemberList> memberLists = ssmStoreMemberService.select(storeMemberList);

//        MemberInit m = new MemberInit();
//        BeanUtils.copyProperties(memberInitRequest, m);
//        List<MemberInit> list = dao.select(m);
        //改为分页查询
        PageInfo<MemberInit> initPageInfo = this.selectPage(memberInitRequest);
        List<MemberInit> list = initPageInfo.getList();
        Map<Object, Long> map = new HashMap<>();
        if (!list.isEmpty()) {
            List<MemberInit> recList = list.stream().collect(Collectors.groupingBy(MemberInit::getCardType)).get(0);
            if (recList != null && !recList.isEmpty()) {
                map = recList.stream().collect(Collectors.groupingBy(memberInit -> memberInit.getMemberName() + "-" + memberInit.getMobilePhone() + "-" + memberInit.getTradeName(),
                        Collectors.counting()));
            }
        }
//        map.keySet().forEach(key -> {
//            if(map.get(key) > 1){
//                unusualList.add(key);
//            }
//        });

//        List<MemberInit> unusualList1 = new ArrayList<>();
//        List<MemberInit> unusualList2 = new ArrayList<>();
//        List<MemberInit> unusualList3 = new ArrayList<>();
//        List<MemberInit> unusualList4 = new ArrayList<>();
//        List<MemberInit> unusualList5 = new ArrayList<>();
//        List<MemberInit> unusualList6 = new ArrayList<>();
//        Map<String, List<MemberInit>> listMap = new HashMap<>();

        for (MemberInit memberInit : list) {
            MemberInitResponse memberInitResponse = new MemberInitResponse();
            //充值账户
            if (memberInit.getCardType() == 0) {
                //剩余金额小于可用金额 异常记录
                if (BigDecimalUtils.compareTo(memberInit.getRestMoney(), memberInit.getCardConsumeMoney()) == -1) {
                    memberInit.setInitState(2);
                    BeanUtils.copyProperties(memberInit, memberInitResponse);
                    memberInitResponse.setUnusualReason("充值账户剩余金额小于可用金额");
                    unusualList.add(memberInitResponse);
//                    unusualList1.add(memberInit);
//                    listMap.put("充值账户剩余金额小于可用金额",unusualList1);
                    continue;
                }
                //充值类别不存在当前充值账户
                List<RechargeType> rechargeTypes =  rechargeTypeList.stream().filter(item->item.getRechargeTypeName().equals(memberInit.getTradeName())).collect(Collectors.toList());
                if (rechargeTypes.isEmpty()){
                    memberInit.setInitState(2);
                    BeanUtils.copyProperties(memberInit, memberInitResponse);
                    memberInitResponse.setUnusualReason("充值类别不存在当前充值账户");
                    unusualList.add(memberInitResponse);
//                    unusualList2.add(memberInit);
//                    listMap.put("充值类别不存在当前充值账户",unusualList2);
                    continue;
                }
                //校验
                if (map.get(memberInit.getMemberName() + "-" + memberInit.getMobilePhone() + "-" + memberInit.getTradeName()) > 1){
                    memberInit.setInitState(2);
                    BeanUtils.copyProperties(memberInit, memberInitResponse);
                    memberInitResponse.setUnusualReason("充值账户重复");
                    unusualList.add(memberInitResponse);
//                    unusualList3.add(memberInit);
//                    listMap.put("充值账户重复",unusualList3);
                    continue;
                }
            }else {//疗程账户
                //剩余次数小于可以次数
                if (memberInit.getRestCount() < memberInit.getCourseConsumeCount()){
                    memberInit.setInitState(2);
                    BeanUtils.copyProperties(memberInit, memberInitResponse);
                    memberInitResponse.setUnusualReason("疗程账户剩余次数小于可以次数");
                    unusualList.add(memberInitResponse);
//                    unusualList4.add(memberInit);
//                    listMap.put("疗程账户剩余次数小于可以次数",unusualList4);
                    continue;
                }
                //项目不存在当前疗程账户
                List<BaseProject> projects =  projectList.stream().filter(item->item.getProjectName().equals(memberInit.getTradeName())).collect(Collectors.toList());
                if (projects.isEmpty()){
                    memberInit.setInitState(2);
                    BeanUtils.copyProperties(memberInit, memberInitResponse);
                    memberInitResponse.setUnusualReason("项目不存在当前疗程账户");
                    unusualList.add(memberInitResponse);
//                    unusualList5.add(memberInit);
//                    listMap.put("项目不存在当前疗程账户",unusualList5);
                    continue;
                }
            }
            //会员信息
            List<StoreMemberList> members =  memberLists.stream().filter(item->item.getMemberName().equals(memberInit.getMemberName())).collect(Collectors.toList());
            if (members.isEmpty()){
                memberInit.setInitState(2);
                BeanUtils.copyProperties(memberInit, memberInitResponse);
                memberInitResponse.setUnusualReason("会员不存在");
                unusualList.add(memberInitResponse);
//                unusualList6.add(memberInit);
//                listMap.put("会员不存在",unusualList6);
                continue;
            }
            //正常数据状态设置
            memberInit.setInitState(3);
        }
//        list.stream()
//                .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) // 获得元素出现频率的 Map，键为元素，值为元素出现的次数
//                .entrySet().stream() // Set<Entry>转换为Stream<Entry>
//                .filter(entry -> entry.getValue() > 1) // 过滤出元素出现次数大于 1 的 entry
//                .map(entry -> entry.getKey()) // 获得 entry 的键（重复元素）对应的 Stream
//                .collect(Collectors.toList()); // 转化为 List
        if (!list.isEmpty()) {
            dao.updateBatch(list);
        }
        PageInfo<MemberInitResponse> pageInfo = new PageInfo<>(unusualList);
        pageInfo.setTotal(initPageInfo.getTotal());
        return pageInfo;

    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int memberInit(MemberInitRequest memberInitRequest) throws ParseException {
        int i=0;
        //查询是否是总店
        List<BaseStore> baseStoreList = ssmBaseStoreService.selectChildren(memberInitRequest.getStoreId());
        for (BaseStore baseStore : baseStoreList) {
            //查询正常状态的初始化记录
            MemberInit m = new MemberInit();
            memberInitRequest.setStoreId(baseStore.getId());
            memberInitRequest.setStoreName(baseStore.getStoreName());
            BeanUtils.copyProperties(memberInitRequest, m);
            List<MemberInit> list = dao.select(m);
            if(list!=null && list.size()>0) {
                //会员列表
                StoreMemberList storeMemberList = new StoreMemberList();
                BeanUtils.copyProperties(memberInitRequest, storeMemberList);
                List<StoreMemberList> memberLists = ssmStoreMemberService.select(storeMemberList);

                //查询充值类别列表
                RechargeType rechargeType = new RechargeType();
                BeanUtils.copyProperties(memberInitRequest, rechargeType);
//        rechargeType.setRechargeTypeName(memberInit.getTradeName());
                //TODO 关于状态问题
                List<RechargeType> rechargeTypes = ssmRechargeTypeSevice.select(rechargeType);

                //查询项目列表
                BaseProject baseProject = new BaseProject();
                BeanUtils.copyProperties(memberInitRequest, baseProject);
//        baseProject.setProjectName(memberInit.getTradeName());
                List<BaseProject> projects = ssmProjectService.select(baseProject);
                //充值账户列表
                List<RechargeAccount> rechargeAccountList = new ArrayList<>();
                //疗程账户列表
                List<CourseAccount> courseAccountList = new ArrayList<>();
                //欠款列表
                List<DebtList> debtLists = new ArrayList<>();
                //账户交易记录列表
                List<AccountTradeRecord> accountTradeRecordList = new ArrayList<>();
                //有效期门店参数
                StoreParament parament = StoreParaUtils.getStorePara(memberInitRequest.getStoreId(), Constant.allow_valid);


//        Map<String, List<RechargeType>> recMap = rechargeTypes.stream().collect(Collectors.groupingBy(RechargeType::getRechargeTypeName));
                for (MemberInit memberInit : list) {
                    memberInit.setInitState(4);
                    //会员根据名称和手机号状态判断是否存在
                    memberLists.stream().
                            filter(item -> item.getMemberName().equals(memberInit.getMemberName()) && AESUtils.encrypt(memberInit.getMobilePhone()).equals(item.getMobilePhone()) && item.getState() == 1).
                            forEach(item -> {
                                memberInit.setMemberId(item.getId());
                            });
                    //账户赋值
                    Long accountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                    if (memberInit.getCardType() == 0) {
                        rechargeTypes.stream().filter(item -> item.getRechargeTypeName().equals(memberInit.getTradeName()) && item.getState() == 1).forEach(item -> {
                            memberInit.setTradeId(item.getId());
                            memberInit.setDiscount(item.getDiscount());
                            memberInit.setCardGiftMoney(item.getGiftMoney());
                            memberInit.setTypeRatio(item.getTypeRatio());
                        });

                        //充值账户
                        RechargeAccount rechargeAccount = new RechargeAccount();
                        BeanUtils.copyProperties(memberInit, rechargeAccount);
                        rechargeAccount.setId(accountId);
                        rechargeAccount.setRechargeNum(memberInit.getInitNum());
                        rechargeAccount.setCardRechargeMoney(memberInit.getRestMoney());
                        rechargeAccount.setCardRestMoney(memberInit.getRestMoney());
                        rechargeAccount.setCardConsumeMoney(memberInit.getCardConsumeMoney());
                        rechargeAccount.setRechargeTypeId(memberInit.getTradeId());
                        rechargeAccount.setRechargeTypeName(memberInit.getTradeName());
                        rechargeAccount.setRechargeTypeNum(memberInit.getOldProjectNum());
                        rechargeAccount.setState(memberInit.getCardState());
//                if ("1".equals(parament.getParamentValue())) {
//                    rechargeAccount.setEndTime(DateUtils.ymdString2Date("2099-12-31"));
//                }
//                rechargeAccount.setEndTime(null);
                        //赠送不为null 赠送卡
                        if (null != memberInit.getCardConsumeMoney()) {
                            rechargeAccount.setType(0);
                        } else {
                            rechargeAccount.setType(1);
                        }
                        RechargeType rechargeType1 = new RechargeType();
                        rechargeType1.setId(memberInit.getTradeId());
                        RechargeType rechargeType2 = ssmRechargeTypeSevice.selectOne(rechargeType1);
                        rechargeAccount.setType(rechargeType2.getType());
                        rechargeAccount.setDiscountFreeAmount(rechargeType2.getDiscountFreeAmount());

                        //ssmAccountTradeRecordService.
                        rechargeAccount.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                        rechargeAccount.setStoreId(memberInit.getStoreId());
                        rechargeAccount.setStoreName(memberInit.getStoreName());
                        rechargeAccountList.add(rechargeAccount);
                        if(memberInit.getGiveType()!=null && memberInit.getGiveType()==1){
                            RechargeAccountGive accountGive = new RechargeAccountGive();
                            BeanUtils.copyProperties(rechargeAccount,accountGive);
                            accountGive.setAccountId(rechargeAccount.getId());
                            ssmRechargeAccountGiveService.save(accountGive);
                        }
                        //存在欠款
                        if (null != memberInit.getDebtMoney() && BigDecimalUtils.compareTo(memberInit.getDebtMoney(), BigDecimalUtils.bigDecimal("0")) > 1) {
                            DebtList debtList = new DebtList();
                            BeanUtils.copyProperties(memberInit, debtList);
                            debtList.setAccountId(accountId);
                            debtList.setTradeMoney(memberInit.getStandardMoney());
                            debtList.setDocType(Constant.doc_type_recharge);
                            debtLists.add(debtList);
                        }
                        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(memberInit, rechargeAccount);
                        accountTradeRecord.setInputBy(memberInit.getInputBy());
                        accountTradeRecord.setInputDate(memberInit.getInputDate());
                        accountTradeRecordList.add(accountTradeRecord);

                    } else {
                        projects.stream().filter(item -> item.getProjectName().equals(memberInit.getTradeName()) && item.getState() == 1).forEach(item -> {
                            memberInit.setTradeId(item.getId());
                        });

                        //疗程账户
                        CourseAccount courseAccount = new CourseAccount();
                        BeanUtils.copyProperties(memberInit, courseAccount);
                        courseAccount.setId(accountId);
                        courseAccount.setCourseNum(memberInit.getInitNum());
                        courseAccount.setCourseRestCount(memberInit.getRestCount());
                        courseAccount.setCourseConsumeCount(memberInit.getCourseConsumeCount());
                        courseAccount.setCourseProjectId(memberInit.getTradeId());
                        courseAccount.setCourseProjectName(memberInit.getTradeName());
                        courseAccount.setCourseProjectMoney(memberInit.getRestMoney().add(memberInit.getDebtMoney()));
                        courseAccount.setCourseCount(memberInit.getRestCount());
                        courseAccount.setCourseProjectMoneys(memberInit.getRestMoney().add(memberInit.getDebtMoney()));
                        courseAccount.setCourseCounts(memberInit.getRestCount());
                        courseAccount.setCourseStandardMoney(memberInit.getStandardMoney());
                        courseAccount.setCourseStandardCount(memberInit.getStandardCount());
                        courseAccount.setState(memberInit.getCardState());
                        courseAccount.setCourseRestPrice(memberInit.getCourseRestPrice());
                        courseAccount.setCourseConsumePrice(memberInit.getCourseConsumePrice());
                        courseAccount.setExpenditureMoney(BigDecimal.valueOf(0));
                        courseAccount.setPrice(memberInit.getCourseRestPrice().divide(BigDecimalUtils.bigDecimal(memberInit.getRestCount().toString()), 2, BigDecimal.ROUND_HALF_UP));
//                if ("1".equals(parament.getParamentValue())) {
//                    courseAccount.setEndTime(DateUtils.ymdString2Date("2099-12-31"));
//                }
//                courseAccount.setEndTime(null);
                        courseAccount.setCourseType("4");
                        courseAccountList.add(courseAccount);
                        //存在欠款
                        if (null != memberInit.getDebtMoney() && BigDecimalUtils.compareTo(memberInit.getDebtMoney(), BigDecimalUtils.bigDecimal("0")) > 1) {
                            DebtList debtList = new DebtList();
                            BeanUtils.copyProperties(memberInit, debtList);
                            debtList.setAccountId(accountId);
                            debtList.setTradeMoney(memberInit.getStandardMoney());
                            debtList.setDocType(Constant.doc_type_card_use);
                            debtLists.add(debtList);
                        }
                        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(memberInit, courseAccount);
                        accountTradeRecord.setInputBy(memberInit.getInputBy());
                        accountTradeRecord.setInputDate(memberInit.getInputDate());
                        accountTradeRecordList.add(accountTradeRecord);
                    }
                    memberInit.setAccountId(accountId);
                    //修改员工的状态
//                    memberInitStaffMapper.updateByDocNum(memberInit.getInitNum());
//                    ssmSalesmanService.updateByDocNum(memberInit.getInitNum());
                }
                //初始化账户
                if (!rechargeAccountList.isEmpty()) {
                    ssmRechargeAccountService.insertBatch(rechargeAccountList, memberInitRequest.getStoreId(), memberInitRequest.getStoreName());

                }
                if (!courseAccountList.isEmpty()) {
                    ssmCourseAccountService.insertBatch(courseAccountList, memberInitRequest.getStoreId(), memberInitRequest.getStoreName());
                }
                //初始化欠款
                if (!debtLists.isEmpty()) {
                    ssmDebtService.insertBatch(debtLists, memberInitRequest.getStoreId(), memberInitRequest.getStoreName());
                }
                //初始化账户交易记录
                if (!accountTradeRecordList.isEmpty()) {
                    ssmAccountTradeRecordService.insertBatch(accountTradeRecordList);
                }
                i += dao.updateBatch(list);
            }
        }
        return i;
    }

    @Override
    public List<MemberInit> selectFKJ(MemberInit memberInit) {
        return dao.selectFKJ(memberInit);
    }
    @Autowired
    private MemberInitMapper mapper;
    @Override
    public List<MemberInit> selectFKJByDate(MemberInit memberInit) {
        return mapper.selectFKJByDate(memberInit);
    }

    @Override
    public List<StaffStatistic> staff(MemberInitRequest memberInitRequest) {
        List<StaffStatistic> list = new ArrayList<>();
        List<MemberInitStaff> staffs = memberInitStaffMapper.selectStaff(memberInitRequest);
        if(staffs!=null && staffs.size()>0){
            List<Long> storeIds = staffs.stream().map(MemberInitStaff::getStoreId).collect(Collectors.toList());
            List<BaseStore> baseStores = ssmBaseStoreService.selectByIds(storeIds);
            Map<Long, List<MemberInitStaff>> listMap = staffs.stream().collect(Collectors.groupingBy(MemberInitStaff::getStaffId));
            Iterator<Map.Entry<Long, List<MemberInitStaff>>> iterator = listMap.entrySet().iterator();
            while (iterator.hasNext()){
                List<MemberInitStaff> value = iterator.next().getValue();
                StaffStatistic staffStatistic = new StaffStatistic();
                MemberInitStaff memberInitStaff1 = value.get(0);
                staffStatistic.setStaffId(memberInitStaff1.getStaffId());
                staffStatistic.setBrandNumber(memberInitStaff1.getBrandNumber());
                staffStatistic.setStaffName(memberInitStaff1.getStaffName());
                //疗程业绩
                for (BaseStore baseStore : baseStores) {
                    if(baseStore.getId().compareTo(memberInitStaff1.getStoreId())==0 || baseStore.getId().toString().equals(memberInitStaff1.getStoreId().toString())){
                        staffStatistic.setStoreNum(baseStore.getStoreNum());
                        staffStatistic.setStoreName(baseStore.getStoreName());
                    }
                }
                BigDecimal courseAchi = BigDecimal.ZERO;
                BigDecimal courseComm = BigDecimal.ZERO;
                BigDecimal courseCoop = BigDecimal.ZERO;
                BigDecimal bigDecimal = new BigDecimal("100");
                for (MemberInitStaff memberInitStaff : value) {
                    BigDecimal achi = BigDecimal.ZERO;
                    BigDecimal comm = BigDecimal.ZERO;
                    BigDecimal coopAchi = BigDecimal.ZERO;
                    //判断是否是合作项目   1是比例，2是固定
                    if(memberInitStaff.getIsCooperation()==1){
                        coopAchi = memberInitStaff.getRatio().multiply(memberInitStaff.getMoney()).multiply(memberInitStaff.getSalesAchievement()).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP)
                                .multiply(memberInitStaff.getBrokerage()).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP);
                    } else if (memberInitStaff.getIsCooperation()==2) {
                        coopAchi = memberInitStaff.getRatio().multiply(memberInitStaff.getSalesAchievement()).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP)
                                .multiply(memberInitStaff.getBrokerage());
                    }
                    if(memberInitStaff.getSalesAchievement().compareTo(new BigDecimal("1"))>=0){
                        achi = memberInitStaff.getRatio().multiply(memberInitStaff.getMoney()).multiply(memberInitStaff.getSalesAchievement()).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP);
                    }else {
                        achi = memberInitStaff.getRatio().multiply(memberInitStaff.getSalesAchievement()).multiply(memberInitStaff.getMoney()).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP);
                    }
                    courseAchi = courseAchi.add(achi).subtract(coopAchi);

                    if(memberInitStaff.getSalesCommission().compareTo(new BigDecimal("1"))>=0){
                        comm = memberInitStaff.getRatio().multiply(memberInitStaff.getSalesCommission()).divide(bigDecimal,4,BigDecimal.ROUND_HALF_UP);
                    }else {
                        comm = achi.subtract(coopAchi).multiply(memberInitStaff.getSalesCommission());
                    }
                    courseComm = courseComm.add(comm);
                    courseCoop = courseCoop.add(coopAchi);
                }
                staffStatistic.setCourseOfTreatmentYJ(courseAchi);
                staffStatistic.setTotaltc(courseComm);
                staffStatistic.setCooperationAchi(courseCoop);
                list.add(staffStatistic);
            }

        }
        return list;
    }

    @Override
    public int delete(MemberInitRequest memberInitRequest) {
        MemberInit memberInit = new MemberInit();
        BeanUtils.copyProperties(memberInitRequest, memberInit);
        memberInit.setInitState(0);
        return dao.updateByPrimaryKeySelective(memberInit);
    }

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

    public AccountTradeRecord setAccountTradeRecord(MemberInit memberInit,RechargeAccount rechargeAccount){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(memberInit.getStoreId());
        accountTradeRecord.setStoreName(memberInit.getStoreName());
        accountTradeRecord.setMemberId(memberInit.getMemberId());
        accountTradeRecord.setMemberName(memberInit.getMemberName());
        accountTradeRecord.setMemberPhone(memberInit.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        if(memberInit.getInitState() == 4) {
            accountTradeRecord.setAccountType(Constant.account_type_recharge);
            accountTradeRecord.setInputDate(new Date());
            //accountInMoney使用初始化时录入的剩余restMoney
            accountTradeRecord.setAccountInMoney(memberInit.getRestMoney());
        }
//        else {
//            accountTradeRecord.setAccountType(Constant.account_type_recharge_cancel);
//            accountTradeRecord.setInputDate(new Date());
//            accountTradeRecord.setAccountInMoney(memberInit.getRestMoney());
//        }
        accountTradeRecord.setDocId(memberInit.getId());
        accountTradeRecord.setDocNum(memberInit.getInitNum());
        accountTradeRecord.setDocType(Constant.doc_type_init);

        accountTradeRecord.setTradeId(rechargeAccount.getRechargeTypeId());
        accountTradeRecord.setTradeName(rechargeAccount.getRechargeTypeName());
        accountTradeRecord.setTradeMoney(rechargeAccount.getCardRechargeMoney());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        return accountTradeRecord;
    }


    /*
     * 账户交易记录属性赋值 疗程
     * */
    public AccountTradeRecord setAccountTradeRecord(MemberInit memberInit,CourseAccount courseAccount){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(memberInit.getStoreId());
        accountTradeRecord.setStoreName(memberInit.getStoreName());
        accountTradeRecord.setMemberId(memberInit.getMemberId());
        accountTradeRecord.setMemberName(memberInit.getMemberName());
        accountTradeRecord.setMemberPhone(memberInit.getMobilePhone());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());
        accountTradeRecord.setAccountInMoney(memberInit.getRestMoney());
        if(memberInit.getInitState() == 4) {
            accountTradeRecord.setAccountType(Constant.account_type_project);
            accountTradeRecord.setInputDate(new Date());
            accountTradeRecord.setAccountInCount(courseAccount.getCourseCount());
        }
//        else {
//            accountTradeRecord.setAccountType(Constant.account_type_project_cancel);
//            accountTradeRecord.setInputDate(new Date());
//            accountTradeRecord.setAccountInCount(courseAccount.getCourseCount());
//        }
        accountTradeRecord.setDocId(memberInit.getId());
        accountTradeRecord.setDocNum(memberInit.getInitNum());
        accountTradeRecord.setDocType(Constant.doc_type_init);
        accountTradeRecord.setTradeId(courseAccount.getCourseProjectId());
        accountTradeRecord.setTradeName(courseAccount.getCourseProjectName());
        accountTradeRecord.setTradeMoney(courseAccount.getCourseProjectMoney());
        accountTradeRecord.setTradeCount(courseAccount.getCourseCount());
        accountTradeRecord.setAccountRestCount(courseAccount.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(courseAccount.getCourseConsumeCount());
        return accountTradeRecord;
    }

    public String getNum(Long storeId){
//        //查询门店 获取门店编码
//        BaseStore store = ssmBaseStoreService.selectByPrimaryKey(storeId);
        //查询数据库门店 编码最新的一个
        String ymdDate = DateUtils.YMDFormat(new Date());
        Example example = new Example(MemberInit.class);
        Example.Criteria criteria = example.createCriteria();
        //按会员编码降序排列
        example.setOrderByClause("init_num desc");
        //通过时间模糊查询
        criteria.andLike("initNum","CS" + ymdDate + "%");
//        criteria.andEqualTo("storeId",storeId);
        List<MemberInit> memberLists = dao.selectByExample(example);
        String num;
        int mm = 0;
        if (memberLists != null && memberLists.size() > 0) {
            MemberInit memberInit = memberLists.get(0);
            String initNum = memberInit.getInitNum();
            mm = Integer.parseInt(initNum.substring(initNum.length()-5, initNum.length())) + 1;
            if (mm < 10){
                num = "0000" + mm;
            }else if (mm < 100){
                num = "000" + mm;
            }else if (mm < 1000){
                num = "00" + mm;
            }else if (mm < 10000){
                num = "0" + mm;
            }else {
                num = String.valueOf(mm);
            }

        }else {
            num = "00001" ;
        }
        num = "CS" + ymdDate + num;
        return num;
    }
}
