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.BeiSenUtils;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.*;
import com.ssm.manage.dto.BlackListDto;
import com.ssm.manage.dto.StaffTemporaryDto;
import com.ssm.manage.entity.*;
import com.ssm.manage.mapper.StaffTemporaryMapper;
import com.ssm.manage.query.CourseAccountRequest;
import com.ssm.manage.query.MemberRequest;
import com.ssm.manage.query.StaffRequest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.*;
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.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SsmBaseStaffServiceImpl extends BaseServiceImpl<BaseStaff> implements SsmBaseStaffService {
    @Autowired
    private RedisClient<List<BaseStaff>> redisClient;
    @Autowired
    private RedisClient<StaffResponse> redisClient1;

    @Autowired
    private StaffTemporaryNumberService staffTemporaryNumberService;

    @Autowired
    private RedisClient<MemberResponse> memberResponseRedisClient;

    @Autowired
    private RegionListDao regionListDao;

    @Autowired
    private BeiSenUtils beiSenUtils;

    @Autowired
    private BlackListDao blackListDao;

    @Autowired
    private RedisClient<StaffTemporaryVo> staffTemporaryVoRedisClient;

    @Autowired
    private StaffTemporaryDao staffTemporaryDao;
    @Autowired
    private StaffTemporaryMapper staffTemporaryMapper;

    @Autowired
    private RlRoleStaffDao rlRoleStaffDao;
    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;

    @Resource
    private SsmCourseAccountDao ssmCourseAccountDao;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @Autowired
    private SsmCourseService ssmCourseService;

    @Resource
    private SsmRepayTradeDao ssmRepayTradeDao;

    @Resource
    private SsmDebtDao ssmDebtDao;
    @Resource
    private SsmDocPromotionDao ssmDocPromotionDao;
    @Resource
    private SsmDocPromotionProjectDao ssmDocPromotionProjectDao;
    @Resource
    private SsmPromotionProjectDao projectDao;
    @Resource
    private SsmCardChangeDao cardChangeDao;
    @Resource
    private SsmCardChangeInProjectDao inProjectDao;
    @Autowired
    private SsmMemberInitService ssmMemberInitService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmBaseStaffDao dao;

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

    private static  String key = "staffList";

    @Override
    public PageInfo<StaffResponse> selectPage(StaffRequest staffRequest){
        if (StringUtils.isNotBlank(staffRequest.getMobilePhone())) {
            staffRequest.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
            try {
                String decrypt = AESUtils.decrypt(staffRequest.getMobilePhone());
            } catch (Exception e) {

            }
        }

//        staffRequest.setPageSize(999);
        PageInfo<StaffResponse> pageInfo = dao.selectPage(staffRequest);
        List<StaffResponse> lists = pageInfo.getList();
        if (lists != null && lists.size() > 0) {
            for (StaffResponse staffResponse : lists) {
                try {
                    //生产环境报空指针
                    String mobilePhone = staffResponse.getMobilePhone();
                    if(StringUtils.isNotBlank(mobilePhone)){
                        staffResponse.setMobilePhone(AESUtils.decrypt(mobilePhone).replaceAll("\u0000", ""));
                    }
                } catch (Exception e) {
                    log.error("SsmBaseStaffServiceImpl.selectPage:", e);
                }
            }
        }
        PageInfo<StaffResponse> p = new PageInfo<>(lists);
        p.setTotal(pageInfo.getTotal());
        return p;
    }

    @Override
    public PageInfo<StaffResponse> selectPageNew(StaffRequest staffRequest){
        if (StringUtils.isNotBlank(staffRequest.getMobilePhone())) {
            staffRequest.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
            try {
                String decrypt = AESUtils.decrypt(staffRequest.getMobilePhone());
            } catch (Exception e) {

            }
        }

//        staffRequest.setPageSize(999);
        PageInfo<StaffResponse> pageInfo = dao.selectPageNew(staffRequest);
        List<StaffResponse> lists = pageInfo.getList();
        if (lists != null && lists.size() > 0) {
            for (StaffResponse staffResponse : lists) {
                try {
                    //生产环境报空指针
                    String mobilePhone = staffResponse.getMobilePhone();
                    if(StringUtils.isNotBlank(mobilePhone)){
                        staffResponse.setMobilePhone(AESUtils.decrypt(mobilePhone).replaceAll("\u0000", ""));
                    }
                } catch (Exception e) {
                    log.error("SsmBaseStaffServiceImpl.selectPage:", e);
                }
            }
        }
        PageInfo<StaffResponse> p = new PageInfo<>(lists);
        p.setTotal(pageInfo.getTotal());
        return p;
    }

    @Override
    public PageInfo<StaffResponse> parentsStaff(StaffRequest staffRequest){
        if (StringUtils.isNotBlank(staffRequest.getMobilePhone())) {
            staffRequest.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
            try {
                String decrypt = AESUtils.decrypt(staffRequest.getMobilePhone());
            } catch (Exception e) {

            }
        }

//        staffRequest.setPageSize(999);
        PageInfo<StaffResponse> pageInfo = dao.parentsStaff(staffRequest);
        List<StaffResponse> lists = pageInfo.getList();
        if (lists != null && lists.size() > 0) {
            for (StaffResponse staffResponse : lists) {
                try {
                    //生产环境报空指针
                    String mobilePhone = staffResponse.getMobilePhone();
                    if(StringUtils.isNotBlank(mobilePhone)){
                        staffResponse.setMobilePhone(AESUtils.decrypt(mobilePhone).replaceAll("\u0000", ""));
                    }
                } catch (Exception e) {
                    log.error("SsmBaseStaffServiceImpl.selectPage:", e);
                }
            }
        }
        PageInfo<StaffResponse> p = new PageInfo<>(lists);
        p.setTotal(pageInfo.getTotal());
        return p;
    }

    @Override
    public PageInfo<StaffResponse> selectPagestaff(StaffRequest staffRequest){
        if (StringUtils.isNotBlank(staffRequest.getMobilePhone())) {
            staffRequest.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
        }
        PageInfo<StaffResponse> pageInfo = dao.selectPagestaff(staffRequest);
        List<StaffResponse> lists = pageInfo.getList();
        if (lists.size() > 0) {
            lists.forEach(staffResponse -> {
                try {
                    staffResponse.setMobilePhone(AESUtils.decrypt(staffResponse.getMobilePhone()).replaceAll("\u0000", ""));
                } catch (Exception e) {
                    log.error("SsmBaseStaffServiceImpl.selectPage:", e);
                }
            });
        }
        return pageInfo;
    }

    @Override
    public int addStaff(StaffRequest staffRequest, String phone) throws SmsException {
        int i=0;
        String checkp="";
        try {
            checkp=AESUtils.encrypt(staffRequest.getMobilePhone());
        }catch (Exception e){
            e.printStackTrace();
        }
            BaseStaff baseStaff = new BaseStaff();
            //判断员工手机 员工身份证号 水牌号 是否已存在
            getStaff(staffRequest.getMobilePhone(),staffRequest.getIdentityCard(),staffRequest.getBrandNumber(), staffRequest.getStoreId());
            baseStaff.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            baseStaff.setStaffNum(staffRequest.getStaffNum());
            baseStaff.setStaffName(staffRequest.getStaffName());
            baseStaff.setState(1);
            baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
            baseStaff.setIdentityCard(staffRequest.getIdentityCard());
            baseStaff.setQq(staffRequest.getQq());
            baseStaff.setWechat(staffRequest.getWechat());
            baseStaff.setJoinedDate(staffRequest.getJoinedDate());
            baseStaff.setJob(staffRequest.getJob());
            baseStaff.setSex(staffRequest.getSex());
            baseStaff.setUserState(staffRequest.getUserState());
            baseStaff.setGrade(staffRequest.getGrade());
            baseStaff.setBrandNumber(staffRequest.getBrandNumber());
            baseStaff.setPopularity(staffRequest.getPopularity());
            baseStaff.setGoodAt(staffRequest.getGoodAt());
            baseStaff.setBriefIntroduction(staffRequest.getBriefIntroduction());
            baseStaff.setRow(staffRequest.getRow());
//            //type == 2是收银
//            if(staffRequest.getType()==2){
//                staffRequest.setRoleNum("1");
//            }
//            //type == 1是普通员工
//            if(staffRequest.getType()==1){
//                staffRequest.setRoleNum("3");
//            }
            baseStaff.setRoleNum(staffRequest.getRoleNum());
            baseStaff.setRoleName(staffRequest.getRoleName());
            baseStaff.setRoleId(staffRequest.getRoleId());
            baseStaff.setStoreId(staffRequest.getStoreId());
            baseStaff.setStoreName(staffRequest.getStoreName());
            baseStaff.setRechargeAchi(staffRequest.getRechargeAchi());
            baseStaff.setCourseAchi(staffRequest.getCourseAchi());
            baseStaff.setCashAchi(staffRequest.getCashAchi());
            baseStaff.setBaseSalary(staffRequest.getBaseSalary());
            baseStaff.setSource(staffRequest.getSource());
            baseStaff.setType(staffRequest.getType());
            baseStaff.setDeptName(staffRequest.getDeptName());
            baseStaff.setPostId(staffRequest.getPostId());
            baseStaff.setPostNum(staffRequest.getPostNum());
            baseStaff.setPostName(staffRequest.getPostName());
            baseStaff.setWordTypeId(staffRequest.getWordTypeId());
            baseStaff.setWordTypeNum(staffRequest.getWordTypeNum());
            baseStaff.setWordTypeName(staffRequest.getWordTypeName());
            baseStaff.setPassword(staffRequest.getPassword());
            StaffResponse staffResponse = new StaffResponse();


        if(staffRequest.getMobilePhone()!=null){
            BaseStaff baseStaff1=new BaseStaff();
            baseStaff1.setMobilePhone(checkp);
            baseStaff1.setStoreId(staffRequest.getStoreId());
            List<StaffRequest> checkPhone=dao.CheckPhone(baseStaff1);
            if(checkPhone.size()>0){
                throw new SmsException(ResponseCode.MSG,"该手机号码已存在");
            }else {
                if (phone != null){
                    if (redisClient.hasKey(getKey(phone))) {
                        staffResponse = redisClient1.get(getKey(phone));
                        baseStaff.setInputId(staffResponse.getId());
                        baseStaff.setInputBy(staffResponse.getStaffName());
                    }
                    Set<String> keys = redisClient1.keys(getKey(phone) + "*");
                    //从redis查询 设置录单人信息 app使用
                    if (keys.size() > 0){
                        String key =  new ArrayList<>(keys).get(0);
                        staffResponse = redisClient1.get(key);
                        baseStaff.setInputId(staffResponse.getId());
                        baseStaff.setInputBy(staffResponse.getStaffName());
                    }
                    baseStaff.setInputDate(new Date());
                }
                baseStaff.setPassword(AESUtils.encrypt("123"));
                RlRoleStaff rlRoleStaff = new RlRoleStaff();
                rlRoleStaff.setStaffId(baseStaff.getId());
                rlRoleStaff.setRoleId(baseStaff.getRoleId());
                rlRoleStaffDao.insert(rlRoleStaff);
                i = this.addStaff(baseStaff);
            }
        }else{
            if (phone != null){
                if (redisClient.hasKey(getKey(phone))) {
                    staffResponse = redisClient1.get(getKey(phone));
                    baseStaff.setInputId(staffResponse.getId());
                    baseStaff.setInputBy(staffResponse.getStaffName());
                }
                Set<String> keys = redisClient1.keys(getKey(phone) + "*");
                //从redis查询 设置录单人信息 app使用
                if (keys.size() > 0){
                    String key =  new ArrayList<>(keys).get(0);
                    staffResponse = redisClient1.get(key);
                    baseStaff.setInputId(staffResponse.getId());
                    baseStaff.setInputBy(staffResponse.getStaffName());
                }
                baseStaff.setInputDate(new Date());
            }
//        //生成动态密码 发送到当前员工的手机上
//        String code = ObjectUtils.toString((int)((Math.random()*9+1)*1000));
//        String msg = "您所在门店的员工账户已开通,初始密码为:" + code + ",请妥善保管.您可以通过DCMY员工APP,用注册手机号进行登录";
////        UserResponse userResponse = ChuangLanSmsUtil.sendSmsCode(Constant.smsUrl, Constant.smsAccount,
////                Constant.smsPassword, staffRequest.getMobilePhone(), msg);
//        code = AESUtils.encrypt(code);
//        //baseStaff.setPassword(code);
//        // TODO 短信暂时拿掉 密码设为固定初始密码
//        baseStaff.setPassword(code);
//            baseStaff.setPassword(AESUtils.encrypt("123"));

            i = this.addStaff(baseStaff);
        }



        return i;
    }

    @Override
    public int addStaffTransition(StaffRequest staffRequest) throws SmsException {
        BaseStaff baseStaff1 = new BaseStaff();
        baseStaff1.setId(staffRequest.getId());
        BaseStaff baseStaff2 = dao.selectOne(baseStaff1);
        baseStaff2.setStoreId(staffRequest.getStoreId());
        baseStaff2.setStoreName(staffRequest.getStoreName());
        baseStaff2.setStoreCodeBefore(baseStaff2.getStoreId());
        baseStaff2.setStoreNameBefore(baseStaff2.getStoreName());
////        //生成动态密码 发送到当前员工的手机上
//        String code = ObjectUtils.toString((int)((Math.random()*9+1)*1000));
//        String msg = "您所在门店的员工账户已开通,初始密码为:" + code + ",请妥善保管.您可以通过DCMY员工APP,用注册手机号进行登录";
////        UserResponse userResponse = ChuangLanSmsUtil.sendSmsCode(Constant.smsUrl, Constant.smsAccount,
////                Constant.smsPassword, staffRequest.getMobilePhone(), msg);
//        code = AESUtils.encrypt(code);
//        //baseStaff.setPassword(code);
//        // TODO 短信暂时拿掉 密码设为固定初始密码
        //baseStaff.setPassword(staffRequest.getPassword());
        int i = dao.updateByPrimaryKeySelective(baseStaff2);
        redisClient.delete(getKey(staffRequest.getStoreId(),key));
        redisClient.delete(getKey(baseStaff2.getStoreCodeBefore(),key));
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addStaff(BaseStaff baseStaff){
        int i = dao.saveNotNull(baseStaff);
        redisClient.delete(getKey(baseStaff.getStoreId(),key));
        return i;
    }

    //校验
    @Override
    @Transactional(rollbackFor=Exception.class)
    public List<StaffRequest> selectCheck(BaseStaff baseStaff){
        List<StaffRequest> i= dao.selectCheck(baseStaff);
        return i;
    }

    @Override
    public List<BaseStaff> selectByAllSalemans() {
        return dao.selectByAllSalemans();
    }

    @Override
    public void staffAddRole(StaffRequest staffRequest) {
        //删除
        List<SysStoreRole> roleList = staffRequest.getRoleList();
        RlRoleStaff rlRoleStaff = new RlRoleStaff();
        rlRoleStaff.setStaffId(staffRequest.getId());
        rlRoleStaffDao.delete(rlRoleStaff);
        if (!CollectionUtils.isEmpty(roleList)) {
            for (SysStoreRole role : roleList) {
                RlRoleStaff roleStaff = new RlRoleStaff();
                roleStaff.setRoleId(role.getId());
                roleStaff.setStaffId(staffRequest.getId());
                rlRoleStaffDao.insert(roleStaff);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized StaffTemporaryVo staffLoginAndAddByWeChat(StaffRequest staffRequest) throws SmsException {
        // 手机号检验
        String mobilePhone = staffRequest.getMobilePhone();
        if (StringUtils.isBlank(mobilePhone)) {
            throw new SmsException(ResponseCode.MSG, "请输入手机号码");
        }
        mobilePhone = mobilePhone.trim();
        // 身份证校验
        String identityCard = staffRequest.getIdentityCard();
        if (StringUtils.isBlank(identityCard)) {
            throw new SmsException(ResponseCode.MSG, "请输入身份证号码");
        }
        identityCard = identityCard.trim();

        Date ruzhiTime = staffRequest.getRuzhiTime();
        if (ruzhiTime == null) {
            ruzhiTime = new Date();
        }
        // 获取当天的 09:00:00.000
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(ruzhiTime);
        calendar.set(Calendar.HOUR_OF_DAY, 9);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        ruzhiTime = calendar.getTime();

        // 检验当天是否有重复的数据存在
        /*Example staffExample = new Example(StaffTemporary.class);
        Example.Criteria staffCriteria = staffExample.createCriteria();
        staffCriteria.andEqualTo(StaffRequest.Fields.identityCard, identityCard);
        staffCriteria.andEqualTo("ruzhiTime", ruzhiTime);
        List<StaffTemporary> staffTemporaries = staffTemporaryDao.selectByExample(staffExample);
        if (!CollectionUtils.isEmpty(staffTemporaries)) {
            throw new SmsException(ResponseCode.MSG,"请勿重复提交");
        }*/
        Example example2 = new Example(StaffTemporary.class);
        example2.selectProperties("id");
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("identityCard",identityCard);
        criteria2.andEqualTo("ruzhiTime",ruzhiTime);
        List<StaffTemporary> staffTemporaries = staffTemporaryDao.selectByExample(example2);
        if(Objects.nonNull(staffTemporaries) && !staffTemporaries.isEmpty()){
            throw new SmsException(ResponseCode.MSG,"请勿重复提交");
        }

        Example example = new Example(BlackList.class);
        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo(StaffRequest.Fields.staffName,staffRequest.getStaffName());
        example.selectProperties("urgentName","urgentPhone","urgentRelationship","id","beisenUserId",
                "email","sex","staffNum","staffName","mobilePhone","identityCard","storeId","inputId",
                "inputName","inputDate","type","job","regionId","endType","endId","endName","endTime",
                "updateTime","employeeInformationId","employmentRecordId","isBeisen","isZhongkong","blacklistReasons");
        criteria.andEqualTo(StaffRequest.Fields.identityCard, identityCard);
        criteria.andEqualTo(StaffRequest.Fields.mobilePhone, mobilePhone);
        criteria.andEqualTo(StaffRequest.Fields.storeId,staffRequest.getStoreId());
        List<BlackList> list = blackListDao.selectByExample(example);
        //todo 修改重复入职时的条件判断（只有最新待入场信息为空 || 最新待入场信息中已离职的才能注册）
        StaffTemporary staffTemp1 = staffTemporaryMapper.selectByIdentityCardNew(identityCard);
        if(Objects.nonNull(staffTemp1)){
            if((staffTemp1.getZhongkongDimission()!=null && staffTemp1.getZhongkongDimission()!=1)
                    || (staffTemp1.getBeisenDimission()!=null && staffTemp1.getBeisenDimission()!=1)
                    || (!Objects.nonNull(staffTemp1.getZhongkongDimission()))){
//                stringRedisClient.set(Constant.ruzhiPhone+(staffTemp1.getId().toString()),"1");
                throw new SmsException(ResponseCode.MSG,"用户已注册，前往登录界面！");
            }
        }

//        if (!CollectionUtils.isEmpty(list)){
////            throw new SmsException(ResponseCode.MSG,"用户已注册！");
//            throw new SmsException(ResponseCode.MSG,"用户已注册，前往登录界面！");
//        }
        StaffTemporaryVo staffTemporaryVo = new StaffTemporaryVo();
        String token = UUID.randomUUID().toString();
        //插入临时员工表
        StaffTemporary temporary = new StaffTemporary();
        Long id = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        //TODO 修改在这里
        stringRedisClient.set(Constant.ruzhiPhone+(id.toString()),"1");

        temporary.setId(id);
        temporary.setScanTime(new Date());
        temporary.setIsUpdate(0);
        temporary.setRuzhiTime(ruzhiTime);
        temporary.setStaffName(staffRequest.getStaffName());
        temporary.setMobilePhone(mobilePhone);
        temporary.setIdentityCard(identityCard);
        temporary.setIdentityType(0);
        temporary.setType(staffRequest.getJob());
        temporary.setSex(staffRequest.getSex());
        temporary.setStoreId(staffRequest.getStoreId());
        temporary.setIsBeisen(0);
        temporary.setRemark(staffRequest.getRemark());
        temporary.setState(0);
        temporary.setIsOne(0);
        temporary.setUrgentName(staffRequest.getUrgentName());
        temporary.setUrgentPhone(staffRequest.getUrgentPhone());
        temporary.setUrgentRelationship(staffRequest.getUrgentRelationship());
//        temporary.setEmail(staffRequest.getEmail());
        if(staffRequest.getJob()==0){
            temporary.setEndType(0);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 = format.format(temporary.getRuzhiTime());
            format1 += " 23:59:00";
            try {
                Date parse = format2.parse(format1);
                temporary.setEndTime(parse);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }else {
            temporary.setEndType(2);
        }
        temporary.setFacesInformation(staffRequest.getFacesInformation());
        temporary.setRegionId(staffRequest.getRegionId());

        //查询有没有员工，判断是否是异常状态
//        Example blackExample = new Example(BlackList.class);
//        Example.Criteria blackExampleCriteria = blackExample.createCriteria();
//        //身份证、手机号、名字
//
//        blackExampleCriteria.andEqualTo(BlackListDto.Fields.identityCard, identityCard);
//        blackExample.or(blackExample.createCriteria().andEqualTo(BlackListDto.Fields.mobilePhone, mobilePhone));
//        blackExample.selectProperties("identityCard","type","staffName","mobilePhone");
//        List<BlackList> blackLists = blackListDao.selectByExample(blackExample);
//        if (!CollectionUtils.isEmpty(blackLists)){
//            for (BlackList blackList : blackLists) {
//                temporary.setIsOne(1);
//                //身份证相同、手机不同
//                //手机相同身份证不同
//                if (blackList.getIdentityCard().equals(temporary.getIdentityCard()) && blackList.getType()==1){
//                    throw new SmsException(ResponseCode.MSG,"已拉入系统黑名单，请联系管理员！");
//                }
//                if (blackList.getIdentityCard().equals(temporary.getIdentityCard())){
//                    if (!blackList.getMobilePhone().equals(temporary.getMobilePhone()) || !blackList.getStaffName().equals(temporary.getStaffName())){
//                        temporary.setState(1);
//                    }
//                }
//                if (blackList.getMobilePhone().equals(temporary.getMobilePhone())){
//                    if (!blackList.getIdentityCard().equals(temporary.getIdentityCard()) || !blackList.getStaffName().equals(temporary.getStaffName())){
//                        temporary.setState(1);
//                    }
//                }
//            }
//
//        }
        //查询有没有员工，判断是否是异常状态
        Example blackExample = new Example(StaffTemporary.class);
        Example.Criteria blackExampleCriteria = blackExample.createCriteria();
        //身份证、手机号、名字
        blackExampleCriteria.andEqualTo(BlackListDto.Fields.identityCard, identityCard);
        blackExample.or(blackExample.createCriteria().andEqualTo(BlackListDto.Fields.mobilePhone, mobilePhone));
        blackExample.setOrderByClause("scan_time desc");
        blackExample.selectProperties("identityCard","staffName","mobilePhone");
//        List<BlackList> blackLists = blackListDao.selectByExample(blackExample);
        List<StaffTemporary> staffTemporaries1 = staffTemporaryDao.selectByExample(blackExample);
        if (!CollectionUtils.isEmpty(staffTemporaries1)){
            StaffTemporary staffTemporary = staffTemporaries1.get(0);
            staffTemporary.setIsOne(1);
            //身份证相同、手机不同
            //手机相同身份证不同
            if (staffTemporary.getIdentityCard().equals(temporary.getIdentityCard())){
                if (!staffTemporary.getMobilePhone().equals(temporary.getMobilePhone()) || !staffTemporary.getStaffName().equals(temporary.getStaffName())){
                    temporary.setState(1);
                }
            }
            if (staffTemporary.getMobilePhone().equals(temporary.getMobilePhone())){
                if (!staffTemporary.getIdentityCard().equals(temporary.getIdentityCard()) || !staffTemporary.getStaffName().equals(temporary.getStaffName())){
                    temporary.setState(1);
                }
            }
        }

        //判断是否被拉进黑名单
        Example example3 = new Example(BlackList.class);
        example3.selectProperties("identityCard","staffName","mobilePhone","type");
        Example.Criteria criteria3 = example3.createCriteria();
        criteria3.andEqualTo(BlackListDto.Fields.identityCard, identityCard);
        example3.or(example3.createCriteria().andEqualTo(BlackListDto.Fields.mobilePhone, mobilePhone));
        List<BlackList> blackLists = blackListDao.selectByExample(example3);
        if(!CollectionUtils.isEmpty(staffTemporaries1)){
            for (BlackList blackList : blackLists) {
                if (blackList.getIdentityCard().equals(temporary.getIdentityCard()) && blackList.getType()==1){
                    throw new SmsException(ResponseCode.MSG,"已拉入系统黑名单，请联系管理员！");
                }
            }
        }

        //查询临时工是否存在，存在则带 ???
        StaffTemporary temporary1 = new StaffTemporary();
        temporary1.setIdentityCard(temporary.getIdentityCard());
//        List<StaffTemporary> select = staffTemporaryDao.select(temporary1);
//        if (!CollectionUtils.isEmpty(select)){
//            StaffTemporary staffTemporary = select.get(0);
//            temporary.setIsBeisen(staffTemporary.getIsBeisen());
//            temporary.setSendTime(staffTemporary.getSendTime());
//            temporary.setSendName(staffTemporary.getSendName());
//            temporary.setSendId(staffTemporary.getSendId());
//
//            temporary.setIsZhongkong(staffTemporary.getIsZhongkong());
//            temporary.setSendZhongkongTime(staffTemporary.getSendZhongkongTime());
//            temporary.setSendZhongkongName(staffTemporary.getSendZhongkongName());
//            temporary.setSendZhongkongId(staffTemporary.getSendZhongkongId());
//
//            temporary.setBeisenDimission(staffTemporary.getBeisenDimission());
//            temporary.setBeisenDimissionDate(staffTemporary.getBeisenDimissionDate());
//            temporary.setBeisenDeptId(staffTemporary.getBeisenDeptId());
//            temporary.setBeisenDeptNum(staffTemporary.getBeisenDeptNum());
//            temporary.setBeisenDeptName(staffTemporary.getBeisenDeptName());
//
//            temporary.setZhongkongDimission(staffTemporary.getZhongkongDimission());
//            temporary.setZhongkongDimissionDate(staffTemporary.getZhongkongDimissionDate());
//            temporary.setZhongkongDeptId(staffTemporary.getZhongkongDeptId());
//            temporary.setZhongkongDeptNum(staffTemporary.getZhongkongDeptNum());
//            temporary.setZhongkongDeptName(staffTemporary.getZhongkongDeptName());
//            temporary.setId(staffTemporary.getId());
//        }else {
//            staffTemporaryDao.insert(temporary);
//        }
        //TODO 注释了上面的逻辑，改为下面直接插入
        //todo 在待入场信息表中根据身份证去判断是否存在，存在则更新，导致重新入职的人都只是修改
        //todo 之前的数据，没有新添加新的记录，导致多次入场但只有一条记录
        staffTemporaryDao.insert(temporary);



        //查询当前用户信息,手机号、姓名、身份证号 todo 进行员工信息判断是否是异常


//        String beiSenUtilsToken = beiSenUtils.getToken();
        //如果有员工则进行更新
        BeanUtils.copyProperties(temporary, staffTemporaryVo);
        if(CollectionUtils.isEmpty(list)) {
            // 线程锁, 保证并发时生成的员工编号 staff_num 不会重复
            synchronized (SsmBaseStaffServiceImpl.class) {
                String staffNum = getStaffNum(staffRequest.getStoreId(),identityCard);
                String email = getEmail(staffRequest.getStoreId());
                temporary.setEmail(email);
//                temporary.setState(0);
                staffTemporaryVo.setStaffNum(staffNum);
                temporary.setStaffNum(staffNum);
                // TODO 更新可能导致数据被覆盖...
                staffTemporaryDao.updateByPrimaryKey(temporary);
                StaffTemporaryNumber staffTemporaryNumber = new StaffTemporaryNumber();
                BeanUtils.copyProperties(temporary,staffTemporaryNumber);
                //判断当前员工是否存在编码表中，存在不插入编码表，不存在再插入
                String s = staffTemporaryDao.selectByStoreId(staffRequest.getStoreId(), identityCard);
                if(StringUtils.isBlank(s)){
                    try {
                        staffTemporaryNumberService.save(staffTemporaryNumber);
                    }catch (Exception e){
                        throw new SmsException(ResponseCode.MSG,"人数太多，请重试！");
                    }
                }
//                try {
//                    staffTemporaryNumberService.save(staffTemporaryNumber);
//                }catch (Exception e){
//                    throw new SmsException(ResponseCode.MSG,"人数太多，请重试！");
//                }
                //加入白名单
                BlackList blackList = new BlackList();
                blackList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                blackList.setMobilePhone(mobilePhone);
                blackList.setStaffName(staffRequest.getStaffName());
                blackList.setIdentityCard(identityCard);
                blackList.setSex(staffRequest.getSex());
                blackList.setType(0);
                blackList.setIsZhongkong(0);
                blackList.setIsBeisen(0);
                blackList.setStaffNum(staffNum);
                blackList.setEmail(email);
                blackList.setInputDate(new Date());
                blackList.setStoreId(staffRequest.getStoreId());
                blackList.setFacesInformation(staffRequest.getFacesInformation());
                blackList.setJob(staffRequest.getJob());
                blackList.setUrgentName(staffRequest.getUrgentName());
                blackList.setUrgentPhone(staffRequest.getUrgentPhone());
                blackList.setUrgentRelationship(staffRequest.getUrgentRelationship());
                blackListDao.insert(blackList);
//                try {
//                    blackListDao.insert(blackList);
//                }catch (Exception e){
//                    log.error("blackList insert error", e);
//                }
            }


            //todo 推送北森
//            BeiSenCreatStaffRequest creatStaffRequest = new BeiSenCreatStaffRequest();
//            EmployeeInformation employeeInformation = new EmployeeInformation();
//            EmploymentRecord employmentRecord = new EmploymentRecord();

//            creatStaffRequest.setEmploymentRecord(employmentRecord);
//            creatStaffRequest.setEmployeeInformation(employeeInformation);
//
        } else {
            //进行更新操作
            BlackList blackList = list.get(0);
            temporary.setStaffNum(blackList.getStaffNum());
            temporary.setEmail(blackList.getEmail());
            if (blackList.getType()==0){
                staffTemporaryVo.setStaffNum(blackList.getStaffNum());
                blackList.setUpdateTime(new Date());
                blackList.setFacesInformation(staffRequest.getFacesInformation());
                blackList.setJob(temporary.getType());
//                blackList.setEmail(staffRequest.getEmail());
                blackList.setUrgentName(staffRequest.getUrgentName());
                blackList.setUrgentPhone(staffRequest.getUrgentPhone());
                blackList.setUrgentRelationship(staffRequest.getUrgentRelationship());
                blackList.setRegionId(staffRequest.getRegionId());
                blackListDao.updateByPrimaryKey(blackList);
                //todo 推送北森
                //todo 中控进行恢复离职
//                String url = "http://"+zhongkongHost+"/api/v2/employee/restore/?key="+zhongkongKey;
//                Map<String,Object> mapnew = new HashMap<>();
//                List<String> userList = new ArrayList<>();
//                userList.add(blackList.getStaffNum());
//                mapnew.put("userpin",userList);
//                JSONObject jsonObject = new JSONObject(mapnew);
//                JSONObject jsonobject = new JSONObject();
//                jsonobject.put("param", JSON.toJSON(jsonObject)) ;
//                String response = HttpClientUtil.doPost(url, jsonobject);
            }else {
                temporary.setState(2);
            }
            staffTemporaryDao.updateByPrimaryKey(temporary);


        }

        staffTemporaryVo.setBaseStores(ssmBaseStoreService.selectByPrimaryKey(staffTemporaryVo.getStoreId()));
        staffTemporaryVo.setRegionList(regionListDao.selectByPrimaryKey(staffTemporaryVo.getRegionId()));
        staffTemporaryVo.setToken(token);

        //查询新添加进黑白名单表的数据
        Example example1 = new Example(BlackList.class);
        Example.Criteria criteria1 = example1.createCriteria();
//        criteria.andEqualTo(StaffRequest.Fields.staffName,staffRequest.getStaffName());
        example1.selectProperties("urgentName","urgentPhone","urgentRelationship","id","beisenUserId",
                "email","sex","staffNum","staffName","mobilePhone","identityCard","storeId","inputId",
                "inputName","inputDate","type","job","regionId","endType","endId","endName","endTime",
                "updateTime","employeeInformationId","employmentRecordId","isBeisen","isZhongkong","blacklistReasons");
        criteria1.andEqualTo(StaffRequest.Fields.identityCard, identityCard);
        criteria1.andEqualTo(StaffRequest.Fields.mobilePhone, mobilePhone);
        criteria1.andEqualTo(StaffRequest.Fields.storeId,staffRequest.getStoreId());
        List<BlackList> blackLists1 = blackListDao.selectByExample(example1);
        if(!CollectionUtils.isEmpty(blackLists1)){
            staffTemporaryVo.setBlackList(blackLists1.get(0));
        }
        staffTemporaryVo.setBlackList(blackLists1.get(0));

        staffTemporaryVoRedisClient.set(Constant.staffTemporary + token,staffTemporaryVo,RedisClient.EXPIRE_TIME_ONE_DAY, TimeUnit.SECONDS);
        stringRedisClient.set(Constant.ruzhiPhoneAndTime + id.toString(),UUID.randomUUID().toString(),10800L,TimeUnit.SECONDS);

        return staffTemporaryVo;
    }

    @Value("${zhongkong.key}")
    private String zhongkongKey;
    @Value("${zhongkong.host}")
    private String zhongkongHost;



    @Override
    @Transactional
    public  StaffTemporaryVo staffAddByWeChat(StaffRequest staffRequest) throws SmsException {

        // 手机号检验
        String mobilePhone = staffRequest.getMobilePhone();
        if (StringUtils.isBlank(mobilePhone)) {
            throw new SmsException(ResponseCode.MSG, "请输入手机号码");
        }
        mobilePhone = mobilePhone.trim();
        // 身份证校验
        String identityCard = staffRequest.getIdentityCard();
        if (StringUtils.isBlank(identityCard)) {
            throw new SmsException(ResponseCode.MSG, "请输入身份证号码");
        }
        identityCard = identityCard.trim();

        Date ruzhiTime = staffRequest.getRuzhiTime();
        if (ruzhiTime != null) {
            // 获取当天的 09:00:00.000
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(ruzhiTime);

            calendar.set(Calendar.HOUR_OF_DAY, 9);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            ruzhiTime = calendar.getTime();

            // 检验当天是否有重复的数据存在
            Example staffExample = new Example(StaffTemporary.class);
            Example.Criteria staffCriteria = staffExample.createCriteria();
            staffCriteria.andEqualTo(StaffRequest.Fields.identityCard, identityCard);
            staffCriteria.andEqualTo("ruzhiTime", ruzhiTime);
            List<StaffTemporary> staffTemporaries = staffTemporaryDao.selectByExample(staffExample);
            if (!CollectionUtils.isEmpty(staffTemporaries)) {
                throw new SmsException(ResponseCode.MSG,"请勿重复提交");
            }
        }

        Example example = new Example(BlackList.class);
        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo(StaffRequest.Fields.staffName,staffRequest.getStaffName());
        criteria.andEqualTo(StaffRequest.Fields.identityCard, identityCard);
        criteria.andEqualTo(StaffRequest.Fields.mobilePhone, mobilePhone);
        criteria.andEqualTo(StaffRequest.Fields.storeId,staffRequest.getStoreId());
        List<BlackList> list = blackListDao.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)){
//            throw new SmsException(ResponseCode.MSG,"用户已注册！");
            throw new SmsException(ResponseCode.MSG,"用户已注册，前往登录界面！");
        }
        StaffTemporaryVo staffTemporaryVo = new StaffTemporaryVo();
        String token = UUID.randomUUID().toString();
        //插入临时员工表
        StaffTemporary temporary = new StaffTemporary();
        Long id = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        temporary.setId(id);
        temporary.setScanTime(new Date());
        temporary.setIsUpdate(0);
        if (Objects.isNull(ruzhiTime)){
            temporary.setRuzhiTime(new Date());
        }else {
            temporary.setRuzhiTime(ruzhiTime);
        }
        temporary.setStaffName(staffRequest.getStaffName());
        temporary.setMobilePhone(mobilePhone);
        temporary.setIdentityCard(identityCard);
        temporary.setIdentityType(0);
        temporary.setType(staffRequest.getJob());
        temporary.setSex(staffRequest.getSex());
        temporary.setStoreId(staffRequest.getStoreId());
        temporary.setIsBeisen(0);
        temporary.setRemark(staffRequest.getRemark());
        temporary.setState(0);
        temporary.setIsOne(0);
        temporary.setUrgentName(staffRequest.getUrgentName());
        temporary.setUrgentPhone(staffRequest.getUrgentPhone());
        temporary.setUrgentRelationship(staffRequest.getUrgentRelationship());
//        temporary.setEmail(staffRequest.getEmail());
        if(staffRequest.getJob()==0){
            temporary.setEndType(0);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 = format.format(temporary.getRuzhiTime());
            format1 += " 23:59:00";
            try {
                Date parse = format2.parse(format1);
                temporary.setEndTime(parse);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }else {
            temporary.setEndType(2);
        }
        temporary.setFacesInformation(staffRequest.getFacesInformation());
        temporary.setRegionId(staffRequest.getRegionId());

        //查询有没有员工，判断是否是异常状态
        Example blackExample = new Example(BlackList.class);
        Example.Criteria blackExampleCriteria = blackExample.createCriteria();
        //身份证、手机号、名字

        blackExampleCriteria.andEqualTo(BlackListDto.Fields.identityCard, identityCard);
        blackExample.or(blackExample.createCriteria().andEqualTo(BlackListDto.Fields.mobilePhone, mobilePhone));
        List<BlackList> blackLists = blackListDao.selectByExample(blackExample);
        if (!CollectionUtils.isEmpty(blackLists)){
            for (BlackList blackList : blackLists) {
                temporary.setIsOne(1);
                //身份证相同、手机不同
                //手机相同身份证不同
                if (blackList.getIdentityCard().equals(temporary.getIdentityCard()) && blackList.getType()==1){
                    throw new SmsException(ResponseCode.MSG,"已拉入系统黑名单，请联系管理员！");
                }
                if (blackList.getIdentityCard().equals(temporary.getIdentityCard())){
                    if (!blackList.getMobilePhone().equals(temporary.getMobilePhone()) || !blackList.getStaffName().equals(temporary.getStaffName())){
                        temporary.setState(1);
                    }
                }
                if (blackList.getMobilePhone().equals(temporary.getMobilePhone())){
                    if (!blackList.getIdentityCard().equals(temporary.getIdentityCard()) || !blackList.getStaffName().equals(temporary.getStaffName())){
                        temporary.setState(1);
                    }
                }
            }

        }

        //查询临时工是否存在，存在则带 ???
        StaffTemporary temporary1 = new StaffTemporary();
        temporary1.setIdentityCard(temporary.getIdentityCard());
        List<StaffTemporary> select = staffTemporaryDao.select(temporary1);
        if (!CollectionUtils.isEmpty(select)){
            StaffTemporary staffTemporary = select.get(0);
            temporary.setIsBeisen(staffTemporary.getIsBeisen());
            temporary.setSendTime(staffTemporary.getSendTime());
            temporary.setSendName(staffTemporary.getSendName());
            temporary.setSendId(staffTemporary.getSendId());

            temporary.setIsZhongkong(staffTemporary.getIsZhongkong());
            temporary.setSendZhongkongTime(staffTemporary.getSendZhongkongTime());
            temporary.setSendZhongkongName(staffTemporary.getSendZhongkongName());
            temporary.setSendZhongkongId(staffTemporary.getSendZhongkongId());

            temporary.setBeisenDimission(staffTemporary.getBeisenDimission());
            temporary.setBeisenDimissionDate(staffTemporary.getBeisenDimissionDate());
            temporary.setBeisenDeptId(staffTemporary.getBeisenDeptId());
            temporary.setBeisenDeptNum(staffTemporary.getBeisenDeptNum());
            temporary.setBeisenDeptName(staffTemporary.getBeisenDeptName());

            temporary.setZhongkongDimission(staffTemporary.getZhongkongDimission());
            temporary.setZhongkongDimissionDate(staffTemporary.getZhongkongDimissionDate());
            temporary.setZhongkongDeptId(staffTemporary.getZhongkongDeptId());
            temporary.setZhongkongDeptNum(staffTemporary.getZhongkongDeptNum());
            temporary.setZhongkongDeptName(staffTemporary.getZhongkongDeptName());
            temporary.setId(staffTemporary.getId());
        }else {
            staffTemporaryDao.insert(temporary);
        }



        //查询当前用户信息,手机号、姓名、身份证号 todo 进行员工信息判断是否是异常


//        String beiSenUtilsToken = beiSenUtils.getToken();
        //如果有员工则进行更新
        BeanUtils.copyProperties(temporary, staffTemporaryVo);
        if(CollectionUtils.isEmpty(list)) {
            // 线程锁, 保证并发时生成的员工编号 staff_num 不会重复
            synchronized (this) {
                String staffNum = getStaffNum(staffRequest.getStoreId(),identityCard);
                String email = getEmail(staffRequest.getStoreId());
                temporary.setEmail(email);
                temporary.setState(0);
                staffTemporaryVo.setStaffNum(staffNum);
                temporary.setStaffNum(staffNum);
                // TODO 更新可能导致数据被覆盖...
                staffTemporaryDao.updateByPrimaryKey(temporary);
                //加入白名单
                BlackList blackList = new BlackList();
                blackList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                blackList.setMobilePhone(mobilePhone);
                blackList.setStaffName(staffRequest.getStaffName());
                blackList.setIdentityCard(identityCard);
                blackList.setSex(staffRequest.getSex());
                blackList.setType(0);
                blackList.setIsZhongkong(0);
                blackList.setIsBeisen(0);
                blackList.setStaffNum(staffNum);
                blackList.setEmail(email);
                blackList.setInputDate(new Date());
                blackList.setStoreId(staffRequest.getStoreId());
                blackList.setFacesInformation(staffRequest.getFacesInformation());
                blackList.setJob(staffRequest.getJob());
                blackList.setUrgentName(staffRequest.getUrgentName());
                blackList.setUrgentPhone(staffRequest.getUrgentPhone());
                blackList.setUrgentRelationship(staffRequest.getUrgentRelationship());
                try {
                    blackListDao.insert(blackList);
                }catch (Exception e){
                    log.error("blackList insert error", e);
                }
            }
            //todo 推送北森
//            BeiSenCreatStaffRequest creatStaffRequest = new BeiSenCreatStaffRequest();
//            EmployeeInformation employeeInformation = new EmployeeInformation();
//            EmploymentRecord employmentRecord = new EmploymentRecord();
//
//
//
//            creatStaffRequest.setEmploymentRecord(employmentRecord);
//            creatStaffRequest.setEmployeeInformation(employeeInformation);
//
//            //todo 同步中控

        }
//        if(!CollectionUtils.isEmpty(list)) {
        else {
            //进行更新操作
            BlackList blackList = list.get(0);
            temporary.setStaffNum(blackList.getStaffNum());
            temporary.setEmail(blackList.getEmail());
            if (blackList.getType()==0){
                staffTemporaryVo.setStaffNum(blackList.getStaffNum());
                blackList.setUpdateTime(new Date());
                blackList.setFacesInformation(staffRequest.getFacesInformation());
                blackList.setJob(temporary.getType());
//                blackList.setEmail(staffRequest.getEmail());
                blackList.setUrgentName(staffRequest.getUrgentName());
                blackList.setUrgentPhone(staffRequest.getUrgentPhone());
                blackList.setUrgentRelationship(staffRequest.getUrgentRelationship());
                blackList.setRegionId(staffRequest.getRegionId());
                blackListDao.updateByPrimaryKey(blackList);
                //todo 推送北森
                //todo 中控进行恢复离职
//                String url = "http://"+zhongkongHost+"/api/v2/employee/restore/?key="+zhongkongKey;
//                Map<String,Object> mapnew = new HashMap<>();
//                List<String> userList = new ArrayList<>();
//                userList.add(blackList.getStaffNum());
//                mapnew.put("userpin",userList);
//                JSONObject jsonObject = new JSONObject(mapnew);
//                JSONObject jsonobject = new JSONObject();
//                jsonobject.put("param", JSON.toJSON(jsonObject)) ;
//                String response = HttpClientUtil.doPost(url, jsonobject);
            }else {
                temporary.setState(2);
            }
            staffTemporaryDao.updateByPrimaryKey(temporary);


        }

        staffTemporaryVo.setBaseStores(ssmBaseStoreService.selectByPrimaryKey(staffTemporaryVo.getStoreId()));
        staffTemporaryVo.setRegionList(regionListDao.selectByPrimaryKey(staffTemporaryVo.getRegionId()));
        staffTemporaryVo.setToken(token);
        staffTemporaryVoRedisClient.set(Constant.staffTemporary + token,staffTemporaryVo,RedisClient.EXPIRE_TIME_ONE_DAY, TimeUnit.SECONDS);
        stringRedisClient.set(Constant.ruzhiPhoneAndTime + id.toString(),UUID.randomUUID().toString(),10800L,TimeUnit.SECONDS);
        return staffTemporaryVo;
    }

    @Override
    public StaffTemporaryVo staffAddByPc(StaffRequest staffRequest) throws SmsException {
        // 手机号检验
        String mobilePhone = staffRequest.getMobilePhone();
        if (StringUtils.isBlank(mobilePhone)) {
            throw new SmsException(ResponseCode.MSG, "请输入手机号码");
        }
        mobilePhone = mobilePhone.trim();
        // 身份证校验
        String identityCard = staffRequest.getIdentityCard();
        if (StringUtils.isBlank(identityCard)) {
            throw new SmsException(ResponseCode.MSG, "请输入身份证号码");
        }
        identityCard = identityCard.trim();

        Date ruzhiTime = staffRequest.getRuzhiTime();
        if (ruzhiTime == null) {
            ruzhiTime = new Date();
        }
        // 获取当天的 09:00:00.000
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(ruzhiTime);
        calendar.set(Calendar.HOUR_OF_DAY, 9);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        ruzhiTime = calendar.getTime();

        StaffTemporary temporary = new StaffTemporary();
        temporary.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        //pc端手工录入
        //todo 手工录入修改
        stringRedisClient.set(Constant.ruzhiPhone+(temporary.getId().toString()),"1");

        // 新增入职检验
        StaffTemporary lastRuzhiStaffTemp = staffTemporaryMapper.selectLastRuzhiByIdentityCard(identityCard);
        if (lastRuzhiStaffTemp != null) {   // 已经注册过
            Integer isZhongkong = lastRuzhiStaffTemp.getIsZhongkong();
            if (isZhongkong == null || isZhongkong == 0) { // 中控未推送
                throw new SmsException(ResponseCode.MSG, "已存在待入职记录，无法修改");
            }
            Integer zhongkongDimission = lastRuzhiStaffTemp.getZhongkongDimission();
            if (zhongkongDimission == null || zhongkongDimission != 1) {
                throw new SmsException(ResponseCode.MSG, "未离职，无法添加");
            }
            // 检验通过, 设置编号
            temporary.setStaffNum(lastRuzhiStaffTemp.getStaffNum());
        }

        //插入临时员工表
        temporary.setScanTime(new Date());
        temporary.setIsUpdate(0);
        temporary.setRuzhiTime(ruzhiTime);
        temporary.setStaffName(staffRequest.getStaffName());
        temporary.setMobilePhone(mobilePhone);
        temporary.setIdentityCard(identityCard);
        temporary.setIdentityType(0);

        Integer job = staffRequest.getJob();
        temporary.setType(job);

        temporary.setSex(staffRequest.getSex());
        temporary.setStoreId(staffRequest.getStoreId());
        temporary.setIsBeisen(0);
        temporary.setRemark(staffRequest.getRemark());
        temporary.setState(0);
        temporary.setIsOne(0);
        temporary.setUrgentName(staffRequest.getUrgentName());
        temporary.setUrgentPhone(staffRequest.getUrgentPhone());
        temporary.setUrgentRelationship(staffRequest.getUrgentRelationship());
        if (job == 0) { // 日结设置离职时间
            temporary.setEndType(0);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 = format.format(temporary.getRuzhiTime());
            format1 += " 23:59:00";
            try {
                Date parse = format2.parse(format1);
                temporary.setEndTime(parse);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        } else if (job == 1) {  // 月结设置离职时间为空
            temporary.setEndTime(null);
        }
        temporary.setFacesInformation(staffRequest.getFacesInformation());
        temporary.setRegionId(staffRequest.getRegionId());

        // 查询有没有员工，判断是否是异常状态
        Example blackExample = new Example(BlackList.class);
        blackExample.selectProperties("identityCard","type","mobilePhone","staffName");
        Example.Criteria blackExampleCriteria = blackExample.createCriteria();
        blackExampleCriteria.andEqualTo(BlackListDto.Fields.identityCard, identityCard);
        List<BlackList> blackLists = blackListDao.selectByExample(blackExample);
        if (!CollectionUtils.isEmpty(blackLists)){
            for (BlackList blackList : blackLists) {
                temporary.setIsOne(1);
                if (blackList.getIdentityCard().equals(temporary.getIdentityCard()) && blackList.getType() == 1){
                    throw new SmsException(ResponseCode.MSG,"已拉入系统黑名单，请联系管理员！");
                }
                // 身份证相同、手机不同
                if (blackList.getIdentityCard().equals(temporary.getIdentityCard())){
                    if (!blackList.getMobilePhone().equals(temporary.getMobilePhone()) || !blackList.getStaffName().equals(temporary.getStaffName())){
                        temporary.setState(1);
                        break;
                    }
                }
                // 手机相同身份证不同
                if (blackList.getMobilePhone().equals(temporary.getMobilePhone())){
                    if (!blackList.getIdentityCard().equals(temporary.getIdentityCard()) || !blackList.getStaffName().equals(temporary.getStaffName())){
                        temporary.setState(1);
                        break;
                    }
                }
            }

        }

        if (lastRuzhiStaffTemp == null) {
            String staffNum = getStaffNum(staffRequest.getStoreId(),identityCard);
            temporary.setStaffNum(staffNum);
            StaffTemporaryNumber staffTemporaryNumber = new StaffTemporaryNumber();
            BeanUtils.copyProperties(temporary,staffTemporaryNumber);
            staffTemporaryNumberService.save(staffTemporaryNumber);

        }
        staffTemporaryDao.insert(temporary);
//        StaffTemporaryNumber staffTemporaryNumber = new StaffTemporaryNumber();
//        BeanUtils.copyProperties(temporary,staffTemporaryNumber);
//        staffTemporaryNumberService.save(staffTemporaryNumber);

        // 进行检验防止编号重复
//        Example staffTempExample = new Example(StaffTemporary.class);
//        Example.Criteria criteria = staffTempExample.createCriteria();
//        criteria.andEqualTo(StaffTemporaryDto.Fields.staffNum, temporary.getStaffNum());
//        List<StaffTemporary> staffTemporaries = staffTemporaryDao.selectByExample(staffTempExample);
//        if (!CollectionUtils.isEmpty(staffTemporaries)) {
        // TODO 判断是否有不同身份证的人拥有同个员工编号
//            String staffNum = getStaffNum(staffRequest.getStoreId());
//            temporary.setStaffNum(staffNum);
//            staffTemporaryDao.updateByPrimaryKey(temporary);
//        }
//        stringRedisClient.set(Constant.ruzhiPhone+(staffRequest.getId().toString()),"1");

        StaffTemporaryVo staffTemporaryVo = new StaffTemporaryVo();
        BeanUtils.copyProperties(temporary, staffTemporaryVo);
        staffTemporaryVo.setBaseStores(ssmBaseStoreService.selectByPrimaryKey(staffTemporaryVo.getStoreId()));
        staffTemporaryVo.setRegionList(regionListDao.selectByPrimaryKey(staffTemporaryVo.getRegionId()));
        return staffTemporaryVo;
    }

    @Override
    public StaffTemporaryVo staffAddByWeChatNew(StaffRequest staffRequest) throws SmsException {

        // 手机号检验
        String mobilePhone = staffRequest.getMobilePhone();
        if (StringUtils.isBlank(mobilePhone)) {
            throw new SmsException(ResponseCode.MSG, "请输入手机号码");
        }
        mobilePhone = mobilePhone.trim();
        // 身份证校验
        String identityCard = staffRequest.getIdentityCard();
        if (StringUtils.isBlank(identityCard)) {
            throw new SmsException(ResponseCode.MSG, "请输入身份证号码");
        }
        identityCard = identityCard.trim();

        Date ruzhiTime = staffRequest.getRuzhiTime();
        if (ruzhiTime != null) {
            // 获取当天的 09:00:00.000
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(ruzhiTime);

            calendar.set(Calendar.HOUR_OF_DAY, 9);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            ruzhiTime = calendar.getTime();

            // 检验当天是否有重复的数据存在
            Example staffExample = new Example(StaffTemporary.class);
            Example.Criteria staffCriteria = staffExample.createCriteria();
            staffCriteria.andEqualTo(StaffRequest.Fields.identityCard, identityCard);
            staffCriteria.andEqualTo("ruzhiTime", ruzhiTime);
            List<StaffTemporary> staffTemporaries = staffTemporaryDao.selectByExample(staffExample);
            if (!CollectionUtils.isEmpty(staffTemporaries)) {
                throw new SmsException(ResponseCode.MSG,"请勿重复提交");
            }
        }

        StaffTemporaryVo staffTemporaryVo = new StaffTemporaryVo();
        String token = UUID.randomUUID().toString();
        //插入临时员工表
        StaffTemporary temporary = new StaffTemporary();
        Long id = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        temporary.setId(id);
        temporary.setScanTime(new Date());
        temporary.setIsUpdate(0);
        if (Objects.isNull(ruzhiTime)){
            temporary.setRuzhiTime(new Date());
        }else {
            temporary.setRuzhiTime(ruzhiTime);
        }
        temporary.setStaffName(staffRequest.getStaffName());
        temporary.setMobilePhone(mobilePhone);
        temporary.setIdentityCard(identityCard);
        temporary.setIdentityType(0);
        temporary.setType(staffRequest.getJob());
        temporary.setSex(staffRequest.getSex());
        temporary.setStoreId(staffRequest.getStoreId());
//        temporary.setIsBeisen(0);
        temporary.setRemark(staffRequest.getRemark());
        temporary.setState(0);
        temporary.setIsOne(0);
        temporary.setUrgentName(staffRequest.getUrgentName());
        temporary.setUrgentPhone(staffRequest.getUrgentPhone());
        temporary.setUrgentRelationship(staffRequest.getUrgentRelationship());
//        temporary.setEmail(staffRequest.getEmail());
        if(staffRequest.getJob()==0){
            temporary.setEndType(0);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 = format.format(temporary.getRuzhiTime());
            format1 += " 23:59:00";
            try {
                Date parse = format2.parse(format1);
                temporary.setEndTime(parse);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }else {
            temporary.setEndType(2);
        }
        temporary.setFacesInformation(staffRequest.getFacesInformation());
        temporary.setRegionId(staffRequest.getRegionId());

        //查询有没有员工，判断是否是异常状态
        Example blackExample = new Example(BlackList.class);
        Example.Criteria blackExampleCriteria = blackExample.createCriteria();
        //身份证、手机号、名字

        blackExampleCriteria.andEqualTo(BlackListDto.Fields.identityCard, identityCard);
        blackExample.or(blackExample.createCriteria().andEqualTo(BlackListDto.Fields.mobilePhone, mobilePhone));
        List<BlackList> blackLists = blackListDao.selectByExample(blackExample);
        if (!CollectionUtils.isEmpty(blackLists)){
            for (BlackList blackList : blackLists) {
                temporary.setIsOne(1);
                //身份证相同、手机不同
                //手机相同身份证不同
                if (blackList.getIdentityCard().equals(temporary.getIdentityCard()) && blackList.getType()==1){
                    throw new SmsException(ResponseCode.MSG,"已拉入系统黑名单，请联系管理员！");
                }
                if (blackList.getIdentityCard().equals(temporary.getIdentityCard())){
                    if (!blackList.getMobilePhone().equals(temporary.getMobilePhone()) || !blackList.getStaffName().equals(temporary.getStaffName())){
                        temporary.setState(1);
                    }
                }
                if (blackList.getMobilePhone().equals(temporary.getMobilePhone())){
                    if (!blackList.getIdentityCard().equals(temporary.getIdentityCard()) || !blackList.getStaffName().equals(temporary.getStaffName())){
                        temporary.setState(1);
                    }
                }
            }

        }

        //查询临时工是否存在，存在则带 ???
        StaffTemporary temporary1 = new StaffTemporary();
        temporary1.setIdentityCard(temporary.getIdentityCard());
        List<StaffTemporary> select = staffTemporaryDao.select(temporary1);
        if (!CollectionUtils.isEmpty(select)){
            StaffTemporary staffTemporary = select.get(0);
//            temporary.setIsBeisen(staffTemporary.getIsBeisen());
//            temporary.setSendTime(staffTemporary.getSendTime());
            temporary.setSendName(staffTemporary.getSendName());
            temporary.setSendId(staffTemporary.getSendId());

//            temporary.setIsZhongkong(staffTemporary.getIsZhongkong());
//            temporary.setSendZhongkongTime(staffTemporary.getSendZhongkongTime());
            temporary.setSendZhongkongName(staffTemporary.getSendZhongkongName());
            temporary.setSendZhongkongId(staffTemporary.getSendZhongkongId());

            temporary.setBeisenDimission(staffTemporary.getBeisenDimission());
            temporary.setBeisenDimissionDate(staffTemporary.getBeisenDimissionDate());
            temporary.setBeisenDeptId(staffTemporary.getBeisenDeptId());
            temporary.setBeisenDeptNum(staffTemporary.getBeisenDeptNum());
            temporary.setBeisenDeptName(staffTemporary.getBeisenDeptName());

            temporary.setZhongkongDimission(staffTemporary.getZhongkongDimission());
            temporary.setZhongkongDimissionDate(staffTemporary.getZhongkongDimissionDate());
            temporary.setZhongkongDeptId(staffTemporary.getZhongkongDeptId());
            temporary.setZhongkongDeptNum(staffTemporary.getZhongkongDeptNum());
            temporary.setZhongkongDeptName(staffTemporary.getZhongkongDeptName());
            temporary.setId(staffTemporary.getId());
        }else {
            staffTemporaryDao.insert(temporary);
        }



        //查询当前用户信息,手机号、姓名、身份证号
        Example example = new Example(BlackList.class);
        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo(StaffRequest.Fields.staffName,staffRequest.getStaffName());
        criteria.andEqualTo(StaffRequest.Fields.identityCard, identityCard);
        criteria.andEqualTo(StaffRequest.Fields.mobilePhone, mobilePhone);
        criteria.andEqualTo(StaffRequest.Fields.storeId,staffRequest.getStoreId());
        List<BlackList> list = blackListDao.selectByExample(example);
        BeanUtils.copyProperties(temporary, staffTemporaryVo);
        if(CollectionUtils.isEmpty(list)) {
            // 未注册, 进行插入

            // 线程锁, 保证并发时生成的员工编号 staff_num 不会重复
            synchronized (this) {
                String staffNum = getStaffNum(staffRequest.getStoreId(),identityCard);
                String email = getEmail(staffRequest.getStoreId());
                temporary.setEmail(email);
                temporary.setState(0);
                staffTemporaryVo.setStaffNum(staffNum);
                temporary.setStaffNum(staffNum);
                // TODO 更新可能导致数据被覆盖...
//                staffTemporaryDao.updateByPrimaryKey(temporary);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Set<String> ruzhiTimeSet = select.stream().filter(staffTemporary -> staffTemporary != null && staffTemporary.getRuzhiTime() != null)
                        .map(staffTemporary -> sdf.format(staffTemporary.getRuzhiTime()))
                        .collect(Collectors.toSet());
                if (ruzhiTimeSet.contains(sdf.format(temporary.getRuzhiTime()))) {
                    throw new SmsException(ResponseCode.MSG, "当前入职记录已存在");
                }
                temporary.setId(id);
                staffTemporaryDao.insert(temporary);
                //加入白名单
                BlackList blackList = new BlackList();
                blackList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                blackList.setMobilePhone(mobilePhone);
                blackList.setStaffName(staffRequest.getStaffName());
                blackList.setIdentityCard(identityCard);
                blackList.setSex(staffRequest.getSex());
                blackList.setType(0);
                blackList.setIsZhongkong(0);
                blackList.setIsBeisen(0);
                blackList.setStaffNum(staffNum);
                blackList.setEmail(email);
                blackList.setInputDate(new Date());
                blackList.setStoreId(staffRequest.getStoreId());
                blackList.setFacesInformation(staffRequest.getFacesInformation());
                blackList.setJob(staffRequest.getJob());
                blackList.setUrgentName(staffRequest.getUrgentName());
                blackList.setUrgentPhone(staffRequest.getUrgentPhone());
                blackList.setUrgentRelationship(staffRequest.getUrgentRelationship());
                try {
                    blackListDao.insert(blackList);
                }catch (Exception e){
                    log.error("blackList insert error", e);
                }
            }

        }
        else {
            // 已存在入场记录，进行更新
            BlackList blackList = list.get(0);
            temporary.setStaffNum(blackList.getStaffNum());
            temporary.setEmail(blackList.getEmail());
            if (blackList.getType()==0){
                staffTemporaryVo.setStaffNum(blackList.getStaffNum());
                blackList.setUpdateTime(new Date());
                blackList.setFacesInformation(staffRequest.getFacesInformation());
                blackList.setJob(temporary.getType());
//                blackList.setEmail(staffRequest.getEmail());
                blackList.setUrgentName(staffRequest.getUrgentName());
                blackList.setUrgentPhone(staffRequest.getUrgentPhone());
                blackList.setUrgentRelationship(staffRequest.getUrgentRelationship());
                blackList.setRegionId(staffRequest.getRegionId());
                blackListDao.updateByPrimaryKey(blackList);
            }else {
                temporary.setState(2);
            }
            staffTemporaryDao.updateByPrimaryKey(temporary);
        }

        staffTemporaryVo.setBaseStores(ssmBaseStoreService.selectByPrimaryKey(staffTemporaryVo.getStoreId()));
        staffTemporaryVo.setRegionList(regionListDao.selectByPrimaryKey(staffTemporaryVo.getRegionId()));
        staffTemporaryVo.setToken(token);
        staffTemporaryVoRedisClient.set(Constant.staffTemporary + token,staffTemporaryVo,RedisClient.EXPIRE_TIME_ONE_DAY, TimeUnit.SECONDS);
        stringRedisClient.set(Constant.ruzhiPhoneAndTime + id,UUID.randomUUID().toString(),10800L,TimeUnit.SECONDS);
        return staffTemporaryVo;
    }

    @Autowired
    private RedisClient<String> stringRedisClient;

    @Override
    public StaffTemporaryVo staffLogin(StaffRequest staffRequest) throws SmsException {
        StaffTemporaryVo staffTemporaryVo = new StaffTemporaryVo();
        String token = UUID.randomUUID().toString();
        //插入临时员工表
        //查询当前用户信息,手机号、姓名、身份证号 todo 进行员工信息判断是否是异常
        Example example = new Example(BlackList.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isEmpty(staffRequest.getMobilePhone())){
            throw new SmsException(ResponseCode.MSG,"请输入手机号！");
        }
        criteria.andEqualTo(StaffRequest.Fields.mobilePhone,staffRequest.getMobilePhone());
        criteria.andEqualTo(StaffRequest.Fields.storeId,staffRequest.getStoreId());
        List<BlackList> list = blackListDao.selectByExample(example);
        if(CollectionUtils.isEmpty(list)) {
            throw new SmsException(ResponseCode.MSG,"用户未注册！");
        }
        else {
            //进行更新操作
            BlackList blackList = list.get(0);
            if (blackList.getType()==1){
                throw new SmsException(ResponseCode.MSG,"已拉入系统黑名单，请联系管理员！");
            }
            BeanUtils.copyProperties(blackList,staffTemporaryVo);
        }
        Example staffExample = new Example(StaffTemporary.class);
        Example.Criteria staffExampleCriteria = staffExample.createCriteria();
        staffExampleCriteria.andEqualTo(StaffTemporaryDto.Fields.identityCard,staffTemporaryVo.getIdentityCard());
        List<StaffTemporary> staffTemporaries = staffTemporaryDao.selectByExample(staffExample);
        if (!CollectionUtils.isEmpty(staffTemporaries)){
            staffTemporaryVo.setId(staffTemporaries.get(0).getId());
            staffTemporaryVo.setType(staffTemporaries.get(0).getType());
            staffTemporaryVo.setRegionId(staffTemporaries.get(0).getRegionId());
        }
        staffTemporaryVo.setBaseStores(ssmBaseStoreService.selectByPrimaryKey(staffTemporaryVo.getStoreId()));
        staffTemporaryVo.setRegionList(regionListDao.selectByPrimaryKey(staffTemporaryVo.getRegionId()));
        staffTemporaryVo.setToken(token);

        staffTemporaryVoRedisClient.set(Constant.staffTemporary + token,staffTemporaryVo,RedisClient.EXPIRE_TIME_ONE_DAY, TimeUnit.SECONDS);
        return staffTemporaryVo;
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private void releaseLock(String lockKey) {
        // 释放锁
        redisTemplate.delete(lockKey);
    }

    private String generateIncrementedStaffNum() {
        // 简单的自增方式生成员工编码
        long nextId = redisTemplate.opsForValue().increment("staff_num_increment_key", 1);
        return String.valueOf(nextId);
    }

//    public String getUniqueStaffNumDistributed(Long storeId) {
//        String staffNum = getStaffNum(storeId);
//
//        // TODO 分布式锁
//        return staffNum;
//    }

    public String getStaffNum(Long storeId,String identityCard) {
        String staffNum = "W";
        int num = 0;

        String numStr = staffTemporaryDao.selectByStoreId(storeId,identityCard);
        Example example = new Example(StaffTemporaryNumber.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(BlackListDto.Fields.storeId,storeId);
        example.setOrderByClause("staff_num desc");
        List<StaffTemporaryNumber> list = staffTemporaryNumberService.selectByExample(example);
//        这里如果重复表有了就用旧的，没有就要递增
        if (StringUtils.isNotEmpty(numStr)) {
            // 去除首个字母 "W" 再转 int
            num = Integer.parseInt(numStr.substring(1)) ;
            if (num < 10){
                numStr = "000" + num;
            }else if (num < 100){
                numStr = "00" + num;
            }
            else if (num < 1000){
                numStr = "0" + num;
            } else {
                numStr = String.valueOf(num);
            }
        }else if(org.apache.commons.collections.CollectionUtils.isNotEmpty(list)){
            // 获取最大的员工编号
            StaffTemporaryNumber cashList = list.get(0);
            // 去除首个字母 "W" 再转 int
            num = Integer.parseInt(cashList.getStaffNum().substring(1)) + 1;
            if (num < 10){
                numStr = "000" + num;
            }else if (num < 100){
                numStr = "00" + num;
            }
            else if (num < 1000){
                numStr = "0" + num;
            } else {
                numStr = String.valueOf(num);
            }
        }else{
            // 从 1 开始递增
            numStr = "0001" ;
        }
        staffNum += numStr;
        return staffNum;
    }

    public String getEmail(Long storeId) {
        String cashNum = "";
        Example example = new Example(BlackList.class);
        example.selectProperties("email");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(BlackListDto.Fields.storeId,storeId);
        example.setOrderByClause("email desc");
        List<BlackList> list = blackListDao.selectByExample(example);
        String num;
        int mm = 0;
        if (list != null && list.size() > 0) {
            BlackList cashList = list.get(0);
            mm = Integer.parseInt(cashList.getEmail().substring(0,10))+1;
            if (mm < 10){
                num = "000000000" + mm;
            }else if (mm < 100){
                num = "00000000" + mm;
            }
            else if (mm < 1000){
                num = "0000000" + mm;
            }
            else if (mm < 1000){
                num = "0000000" + mm;
            }
            else if (mm < 10000){
                num = "000000" + mm;
            }
            else if (mm < 100000){
                num = "00000" + mm;
            }
            else if (mm < 1000000){
                num = "0000" + mm;
            }
            else if (mm < 10000000){
                num = "000" + mm;
            }
            else if (mm < 100000000){
                num = "00" + mm;
            }
            else if (mm < 1000000000){
                num = "0" + mm;
            }
            else {
                num = String.valueOf(mm);
            }
        }else {
            num = "0000000001" ;
        }
        cashNum +=    num;
        cashNum += "@qq.com";
        return cashNum;
    }




    @Override
    @Transactional(rollbackFor=Exception.class)
    public int updateStaffStore(StaffRequest staffRequest){
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setId(staffRequest.getId());
        baseStaff.setStoreId(staffRequest.getStoreId());
        baseStaff.setStoreName(staffRequest.getStoreName());
        if (null != staffRequest.getBrandNumber()){
            baseStaff.setBrandNumber(staffRequest.getBrandNumber());
        }
        baseStaff.setStoreCodeBefore(staffRequest.getStoreCodeBefore());
        baseStaff.setStoreNameBefore(staffRequest.getStoreNameBefore());
        return dao.updateByPrimaryKeySelective(baseStaff);
    }

    @Override
    public int updateStaff(StaffRequest staffRequest, String phone) throws SmsException {
        int i=0;

        String checkp="";
        try {
            checkp=AESUtils.encrypt(staffRequest.getMobilePhone());
        }catch (Exception e){
            e.printStackTrace();
        }


        BaseStaff baseStaff = new BaseStaff();
        //判断员工手机 水牌号是否已存在
        getStaff(staffRequest.getMobilePhone(),null,staffRequest.getBrandNumber(), staffRequest.getStoreId());
        baseStaff.setStaffNum(staffRequest.getStaffNum());
        baseStaff.setStaffName(staffRequest.getStaffName());
        baseStaff.setJoinedDate(staffRequest.getJoinedDate());
        baseStaff.setId(staffRequest.getId());
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
        baseStaff.setQq(staffRequest.getQq());
        baseStaff.setWechat(staffRequest.getWechat());
        baseStaff.setJob(staffRequest.getJob());
        baseStaff.setGrade(staffRequest.getGrade());
        baseStaff.setBrandNumber(staffRequest.getBrandNumber());
        baseStaff.setPopularity(staffRequest.getPopularity());
        baseStaff.setGoodAt(staffRequest.getGoodAt());
        baseStaff.setBriefIntroduction(staffRequest.getBriefIntroduction());
        baseStaff.setRow(staffRequest.getRow());
        baseStaff.setRoleId(staffRequest.getRoleId());
        baseStaff.setRoleNum(staffRequest.getRoleNum());
        baseStaff.setRoleName(staffRequest.getRoleName());
        baseStaff.setStoreId(staffRequest.getStoreId());
        baseStaff.setStoreName(staffRequest.getStoreName());
        baseStaff.setRechargeAchi(staffRequest.getRechargeAchi());
        baseStaff.setCourseAchi(staffRequest.getCourseAchi());
        baseStaff.setCashAchi(staffRequest.getCashAchi());
        baseStaff.setBaseSalary(staffRequest.getBaseSalary());
        baseStaff.setSource(staffRequest.getSource());
        baseStaff.setType(staffRequest.getType());
        baseStaff.setDeptName(staffRequest.getDeptName());
        baseStaff.setSex(staffRequest.getSex());
        baseStaff.setUserState(staffRequest.getUserState());
        baseStaff.setIdentityCard(staffRequest.getIdentityCard());
        baseStaff.setPostId(staffRequest.getPostId());
        baseStaff.setPostNum(staffRequest.getPostNum());
        baseStaff.setPostName(staffRequest.getPostName());
        baseStaff.setWordTypeId(staffRequest.getWordTypeId());
        baseStaff.setWordTypeNum(staffRequest.getWordTypeNum());
        baseStaff.setWordTypeName(staffRequest.getWordTypeName());


        if(staffRequest.getMobilePhone()!=null && !staffRequest.getMobilePhone().equals("")) {
            BaseStaff baseStaff1 = new BaseStaff();
            baseStaff1.setMobilePhone(checkp);
            baseStaff1.setStoreId(staffRequest.getStoreId());
            List<StaffRequest> checkPhone = dao.CheckPhone(baseStaff1);
            if (checkPhone.size() > 0) {
                throw new SmsException(ResponseCode.MSG, "该手机号码已存在");
            }else{
                if (phone != null){
                    StaffResponse staffResponse = redisClient1.get(getKey(phone));
                    baseStaff.setModifyBy(staffResponse.getStaffName());
                    baseStaff.setModifyId(staffResponse.getId());
                    baseStaff.setModifyDate(new Date());
                }

                i = dao.updateByPrimaryKeySelective(baseStaff);
                if (i > 0) {
                    redisClient.delete(getKey(staffRequest.getStoreId(), key));
                }
            }
        }else{
            if (phone != null){
                StaffResponse staffResponse = redisClient1.get(getKey(phone));
                baseStaff.setModifyBy(staffResponse.getStaffName());
                baseStaff.setModifyId(staffResponse.getId());
                baseStaff.setModifyDate(new Date());
            }

            i = dao.updateByPrimaryKeySelective(baseStaff);
            if (i > 0) {
                redisClient.delete(getKey(staffRequest.getStoreId(), key));
            }
        }


        return i;
    }

    @Override
    public BaseStaff selectOne(StaffRequest staffRequest) {
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setId(staffRequest.getId());
        baseStaff = dao.selectOne(baseStaff);
        try {
            if(baseStaff.getMobilePhone()==null || baseStaff.getMobilePhone().length()==0){
                throw new SmsException("50100","该员工的手机号为空");
            }
            baseStaff.setMobilePhone(AESUtils.decrypt(baseStaff.getMobilePhone()).replaceAll("\u0000",""));
        } catch (Exception e) {
            log.error("SsmBaseStaffServiceImpl.selectOne:",e);
        }
        return baseStaff;
    }

    @Override
    public int setMonthjob(StaffRequest staffRequest) {
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setId(staffRequest.getId());
        baseStaff.setBaseSalary(staffRequest.getBaseSalary());
        baseStaff.setMonthTask(staffRequest.getMonthTask());
        baseStaff.setMonthRatio(staffRequest.getMonthRatio());
        baseStaff.setMonthHigherOne(staffRequest.getMonthHigherOne());
        baseStaff.setMonthHigherOneRatio(staffRequest.getMonthHigherOneRatio());
        baseStaff.setMonthHigherTwo(staffRequest.getMonthHigherTwo());
        baseStaff.setMonthHigherTwoRatio(staffRequest.getMonthHigherTwoRatio());
        baseStaff.setMonthHigherThree(staffRequest.getMonthHigherThree());
        baseStaff.setMonthHigherThreeRatio(staffRequest.getMonthHigherThreeRatio());
        baseStaff.setMonthHigherFour(staffRequest.getMonthHigherFour());
        baseStaff.setMonthHigherFourRatio(staffRequest.getMonthHigherFourRatio());
        baseStaff.setMonthLowerOne(staffRequest.getMonthLowerOne());
        baseStaff.setMonthLowerOneRatio(staffRequest.getMonthLowerOneRatio());
        baseStaff.setMonthLowerTwo(staffRequest.getMonthLowerTwo());
        baseStaff.setMonthLowerTwoRatio(staffRequest.getMonthLowerTwoRatio());
        baseStaff.setMonthLowerThree(staffRequest.getMonthLowerThree());
        baseStaff.setMonthLowerThreeRatio(staffRequest.getMonthLowerThreeRatio());
        baseStaff.setMonthLowerFour(staffRequest.getMonthLowerFour());
        baseStaff.setMonthLowerFourRatio(staffRequest.getMonthLowerFourRatio());
        baseStaff.setSource(staffRequest.getSource());
        int i = dao.updateByPrimaryKeySelective(baseStaff);
        if (i > 0) {
            redisClient.delete(getKey(staffRequest.getStoreId(), key));
        }
        return i;
    }

    @Override
    public int staffLeave(StaffRequest staffRequest) {
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setId(staffRequest.getId());
        baseStaff.setState(0);
        baseStaff.setLeaveDate(staffRequest.getLeaveDate());
        int i = dao.updateByPrimaryKeySelective(baseStaff);
        if (i > 0) {
            redisClient.delete(getKey(staffRequest.getStoreId(), key));
        }
        return i;
    }

    @Override
    public int staffStop(StaffRequest staffRequest) {
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setId(staffRequest.getId());
        baseStaff.setState(3);
        //baseStaff.setLeaveDate(staffRequest.getLeaveDate());
        int i = dao.updateByPrimaryKeySelective(baseStaff);
        if (i > 0) {
            redisClient.delete(getKey(staffRequest.getStoreId(), key));
        }
        return i;
    }

    @Override
    public int staffReinstated(StaffRequest staffRequest) throws SmsException {
        BaseStaff baseStaff = new BaseStaff();
        //复职员工需检查水牌号是否已存在
        getStaff(staffRequest.getMobilePhone(),null,staffRequest.getBrandNumber(), staffRequest.getStoreId(),staffRequest.getId());
        baseStaff.setId(staffRequest.getId());
        baseStaff.setBrandNumber(staffRequest.getBrandNumber());
        baseStaff.setState(1);
        baseStaff.setReinstateDate(new Date());
        int i = dao.updateByPrimaryKeySelective(baseStaff);
        if (i > 0) {
            redisClient.delete(getKey(staffRequest.getStoreId(), key));
        }
        return i;
    }

    //判断在职员工手机号码 身份证号 水牌号是否存在
    private void getStaff(String mobilePhone,String identityCard,String brandNumber, Long storeId) throws SmsException {
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(storeId);
        if(mobilePhone!=null && !mobilePhone.equals(""))
        mobilePhone = AESUtils.encrypt(mobilePhone);
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if (mobilePhone != null && !mobilePhone.equals("")) {
                BaseStaff baseStaff = new BaseStaff();
                baseStaff.setMobilePhone(mobilePhone);
                baseStaff.setStoreId(pagesorganization.getId());
                List<BaseStaff> baseStaffs = select(baseStaff);
                if (baseStaffs != null && baseStaffs.size() > 0){
                    throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"员工手机号码在"+baseStaffs.get(0).getStoreName()+"店");
                }
            }
            if (identityCard != null){
                BaseStaff baseStaff = new BaseStaff();
                baseStaff.setIdentityCard(identityCard);
                baseStaff.setStoreId(pagesorganization.getId());
                List<BaseStaff> baseStaffs = select(baseStaff);
                if (baseStaffs != null && baseStaffs.size() > 0){
                    throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"员工身份证号"+baseStaffs.get(0).getStoreName()+"店");
                }
            }
            /*if (brandNumber != null){
                BaseStaff baseStaff = new BaseStaff();
                baseStaff.setBrandNumber(brandNumber);
                baseStaff.setStoreId(pagesorganization.getId());
                baseStaff = selectOne(baseStaff);
                if (baseStaff != null){
                    throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"水牌号");
                }
            }*/

        }
        if (brandNumber != null){
            /*BaseStaff baseStaff = new BaseStaff();
            baseStaff.setBrandNumber(brandNumber);
            baseStaff.setStoreId(storeId);
            baseStaff = selectOne(baseStaff);*/

            StaffRequest staffRequest = new StaffRequest();
            staffRequest.setBrandNumber(brandNumber);
            staffRequest.setStoreId(storeId);
            List<BaseStaff> baseStaffs = dao.selectList(staffRequest);
            for (BaseStaff staff : baseStaffs) {
                //在职和启用
                if (staff.getState() == 1 || staff.getState() == 2){
                    throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"水牌号");
                }
            }
            //在职和启用
            /*if (baseStaff.getState() == 1 || baseStaff.getState() == 2){
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"水牌号");
            }*/
            /*if (baseStaff != null){
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"水牌号");
            }*/
        }
    }

    //判断在职员工手机号码 身份证号 水牌号是否存在
    private void getStaff(String mobilePhone,String identityCard,String brandNumber, Long storeId, Long staffId) throws SmsException {
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(storeId);
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        if (mobilePhone != null) {
            mobilePhone = AESUtils.encrypt(mobilePhone);
        }
        for (BaseStores pagesorganization : pagesorganizations) {
            if(mobilePhone!=null) {
                BaseStaff baseStaff = new BaseStaff();
                baseStaff.setMobilePhone(mobilePhone);
                baseStaff.setStoreId(pagesorganization.getId());
                List<BaseStaff> baseStaffs = select(baseStaff);
                if (baseStaffs != null && baseStaffs.size() > 0) {
                    if (!staffId.equals(baseStaffs.get(0).getId())) {
                        throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "员工手机号码在" + baseStaffs.get(0).getStoreName() + "店");
                    }
                }
            }
            if (identityCard != null){
                BaseStaff baseStaff = new BaseStaff();
                baseStaff.setIdentityCard(identityCard);
                baseStaff.setStoreId(pagesorganization.getId());
                List<BaseStaff> baseStaffs = select(baseStaff);
                if (baseStaffs != null && baseStaffs.size() > 0){
                    if(!staffId.equals(baseStaffs.get(0).getId())){
                        throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"员工身份证号"+baseStaffs.get(0).getStoreName()+"店");
                    }
                }
            }
            /*if (brandNumber != null){
                BaseStaff baseStaff = new BaseStaff();
                baseStaff.setBrandNumber(brandNumber);
                baseStaff.setStoreId(pagesorganization.getId());
                baseStaff = selectOne(baseStaff);
                if (baseStaff != null){
                    if(!staffId.equals(baseStaff.getId())){
                        throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"水牌号");
                    }
                }
            }*/

        }
        /*if (brandNumber != null){
            BaseStaff baseStaff = new BaseStaff();
            baseStaff.setBrandNumber(brandNumber);
            baseStaff.setStoreId(storeId);
            baseStaff = selectOne(baseStaff);
            if (baseStaff != null){
                if(!staffId.equals(baseStaff.getId())){
                    throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"水牌号");
                }
            }
        }*/
        if (brandNumber != null){
            /*BaseStaff baseStaff = new BaseStaff();
            baseStaff.setBrandNumber(brandNumber);
            baseStaff.setStoreId(storeId);
            baseStaff = selectOne(baseStaff);*/
            StaffRequest staffRequest = new StaffRequest();
            staffRequest.setBrandNumber(brandNumber);
            staffRequest.setStoreId(storeId);
            List<BaseStaff> baseStaffs = dao.selectList(staffRequest);
            for (BaseStaff staff : baseStaffs) {
                if (staff.getState() == 1 || staff.getState() == 2){
                    throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"水牌号");
                }
            }
            /*if (baseStaff != null){
                if(!staffId.equals(baseStaff.getId())){
                    throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"水牌号");
                }
            }*/
        }
    }

    @Override
    public PageInfo<StaffResponse> staffMemberPage(StaffRequest staffRequest) {
        //默认查询在职员工
        staffRequest.setState(1);
        if (StringUtils.isNotBlank(staffRequest.getMobilePhone())) {
            staffRequest.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
        }
        PageInfo<StaffResponse> pageInfo = dao.selectPage(staffRequest);
        List<StaffResponse> list = pageInfo.getList();
        for (StaffResponse staffResponse : list) {
            StoreMemberList storeMemberList = new StoreMemberList();
            storeMemberList.setConnStoreId(staffResponse.getStoreId());
            storeMemberList.setStaffId(staffResponse.getId());
            int count = ssmStoreMemberService.selectCount(storeMemberList);
            staffResponse.setCount(count);
        }
        return pageInfo;
    }

    @Override
    public List<BaseStaff> selectList(StaffRequest staffRequest) {
        List<BaseStaff> list = new ArrayList<>();
        if (redisClient.hasKey(getKey(staffRequest.getStoreId(),key))){
            list = redisClient.get(getKey(staffRequest.getStoreId(),key));
        }else {
            BaseStaff staff = new BaseStaff();
            staff.setState(1);
            staff.setStoreId(staffRequest.getStoreId());
            if(null != staffRequest.getType()){
                staff.setType(staffRequest.getType());
            }
            list = dao.select(staff);
            redisClient.set(getKey(staffRequest.getStoreId(),key),list,RedisClient.EXPIRE_TIME_ONE_DAY);
        }
//        for (BaseStaff baseStaff : list) {
//
//        }
        return list;
    }

    @Override
    public List<BaseStaff> selectListtype(StaffRequest staffRequest) {
        List<BaseStaff> list = new ArrayList<>();
        BaseStaff staff = new BaseStaff();
        staff.setState(1);
        if(null != staffRequest.getType()){
            staff.setType(staffRequest.getType());
        }
        staff.setStoreId(staffRequest.getStoreId());
        if(null != staffRequest.getStaffName()){
            staff.setStaffName(staffRequest.getStaffName());
        }
        list = dao.select(staff);
        return list;
    }

    /*@Override
    public int start(StaffRequest staffRequest) throws SmsException {
        BaseStaff baseStaff = dao.selectByPrimaryKey(staffRequest.getId());
        getStaff(baseStaff.getMobilePhone(),null,staffRequest.getBrandNumber(), staffRequest.getStoreId());
        baseStaff.setState(1);
        int i =  dao.updateByPrimaryKeySelective(baseStaff);
        if (i > 0) {
            redisClient.delete(getKey(staffRequest.getStoreId(), key));
        }
        return i;
    }*/
    @Override
    public int start(StaffRequest staffRequest) throws SmsException {
        BaseStaff baseStaff = dao.selectByPrimaryKey(staffRequest.getId());
        getStaff(baseStaff.getMobilePhone(),null,staffRequest.getBrandNumber(), staffRequest.getStoreId());
        baseStaff.setState(1);
        baseStaff.setBrandNumber(staffRequest.getBrandNumber());
        int i =  dao.updateByPrimaryKeySelective(baseStaff);
        if (i > 0) {
            redisClient.delete(getKey(staffRequest.getStoreId(), key));
        }
        return i;
    }

    @Override
    public int insertBatch(List<BaseStaff> list) {
        return dao.insertBatch(list);
    }

    @Override
    public List<PersonZBResponse> selectPersonZB(CourseAccountRequest request) {
        List<PersonZBResponse> infoList = new ArrayList<>();
        //会员记录查询
        CourseAccount courseAccount = ssmCourseAccountDao.selectByPrimaryKey(request.getId());
//        BaseStore baseStore1 = new BaseStore();
//        baseStore1.setId(courseAccount.getStoreId());
//        BaseStore store = ssmBaseStoreService.selectOne(baseStore1);
        if(courseAccount==null){
            request.setCourseProjectId(request.getId());
            List<CourseAccount> courseAccount1=ssmCourseAccountDao.selectMessage(request);
            courseAccount=courseAccount1.get(0);
        }

        //销售金额
        BigDecimal amount = BigDecimal.ZERO;
        //实收金额
        BigDecimal reallyAmount = BigDecimal.ZERO;
        //欠款金额
        BigDecimal debtMoney = BigDecimal.ZERO;
        BigDecimal cardSalesAchievement = BigDecimal.ZERO;//卡付销售业绩标准
        BigDecimal cardSalesCommission = BigDecimal.ZERO;//卡付销售提成标准
        BigDecimal cardAchievementAmount = BigDecimal.ZERO;//卡付销售业绩
        BigDecimal cardCommissionAmount = BigDecimal.ZERO;//卡付销售提成

        //疗程
        if ("0".equals(courseAccount.getCourseType())){

            CourseList courseList = new CourseList();
            courseList.setCourseReatmentNum(courseAccount.getCourseNum());
            courseList.setMemberId(courseAccount.getMemberId());
            courseList.setStoreId(courseAccount.getStoreId());
            courseList.setIsCancel(0);
            String courseNum = courseAccount.getCourseNum();
            if(courseNum!=null && courseNum.length()>0){
                String substring = courseNum.substring(0+courseNum.length()-11, 6+courseNum.length()-11);
                try {
                    Date date = DateUtils.YMParse(substring);
                    courseList.setDate(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }


            //DateUtils.YMParse()
            /*Date date = DateUtils.YMParse(courseListRequest.getSelectDate());
            courseListRequest.setDate(date);*/
            //转门店的订单门店id没有改变，需要根据订单前缀的门店编码查询出门店ID
            BaseStore baseStore=new BaseStore();
            if(courseNum.startsWith("LC")){
                baseStore.setStoreNum(courseNum.substring(2, courseNum.length()-11));
            }else {
                baseStore.setStoreNum(courseNum.substring(0, courseNum.length()-11));
            }
            baseStore=ssmBaseStoreService.selectOne(baseStore);
            courseList.setStoreId(baseStore.getId());
            //疗程卡查询信息
            List<CourseList> courseLists = ssmCourseService.selectList(courseList);
            CourseList courseOne = courseLists.get(0);
            //todo 不带出管理员
//            Salesman salesman = new Salesman();
//            salesman.setOrderNum(courseOne.getCourseReatmentNum());
//            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
//            if(salesmen!=null && salesmen.size()>0){
//
//                List<PersonZBResponse> collect = salesmen.stream().map(item -> {
//                    PersonZBResponse personZBResponse = new PersonZBResponse();
//                        personZBResponse.setId(item.getId());
//                        personZBResponse.setStaffId(item.getStaffId());
//                        personZBResponse.setBrandNumber(item.getBrandNumber());
//                        personZBResponse.setStaffName(item.getStaffName());
//                        personZBResponse.setSale_ratio(item.getRatio());
//                        personZBResponse.setRatio(item.getRatio().divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_HALF_UP).multiply(item.getMoney()));
//                        personZBResponse.setType(item.getStaffType());
//                return personZBResponse;
//            }).collect(Collectors.toList());
//                infoList.addAll(collect);
//            }
            /*for (CourseList courseOne : lists) {*/
                List<PersonZBResponse> infoList1 = new ArrayList<>();
                //销售金额
                amount = courseOne.getAmount();
                //实收金额
                reallyAmount = courseOne.getCourseReatmentAmount();

            cardSalesAchievement = courseOne.getCardSalesAchievement();//卡付销售业绩标准
            cardSalesCommission = courseOne.getCardSalesCommission();//卡付销售提成标准
            cardAchievementAmount = courseOne.getCardAchievementAmount();//卡付销售业绩
            cardCommissionAmount = courseOne.getCardCommissionAmount();//卡付销售提成

            //未欠款
                if (courseOne.getIsDebt() == 0){
                    infoList1 = getSaleInfo(courseOne);
                    if (infoList1.size() > 0){
                        for (PersonZBResponse personZBResponse : infoList1) {
                            //personZBResponse.setIndex_ratio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
//                            personZBResponse.setRatio(personZBResponse.getSale_ratio().divide(new BigDecimal(100),2, RoundingMode.DOWN));
                            personZBResponse.setRatio(personZBResponse.getSale_ratio());
                            infoList.add(personZBResponse);
                        }
                    }

                }else {
                    debtMoney = courseOne.getDebtMoney();
                    //欠款单ID
                    Long docId = courseOne.getId();
                    DebtList debtList = new DebtList();
                    debtList.setDocId(docId);

                    /*infoList1 = getSaleInfo(courseOne);
                    if (infoList1.size() > 0){
                        for (PersonZBResponse personZBResponse : infoList1) {
                            personZBResponse.setIndex_ratio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                            infoList.add(personZBResponse);
                        }
                    }*/

                    //获取欠款单信息
                    List<DebtList> debtLists = ssmDebtDao.queryByDocId(debtList);
                    DebtList debtOne = debtLists.get(0);
                    if (debtOne.getState() == 1){
                        debtMoney = BigDecimal.valueOf(0);
                        infoList1 = getSaleInfo(courseOne);
                        if (infoList1.size() > 0){
                            for (PersonZBResponse personZBResponse : infoList1) {
                                personZBResponse.setRatio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                                infoList.add(personZBResponse);
                            }
                        }

                        List<RepayTradeList> tradeLists = ssmRepayTradeDao.queryByDocId(docId);
                        for (RepayTradeList tradeList : tradeLists) {
                            List<PersonZBResponse> info1 = getSaleInfo(tradeList);
                            if (info1.size()>0){
                                for (PersonZBResponse personZBResponse : info1) {
                                    personZBResponse.setRatio(((tradeList.getPayMoney()).multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),4, RoundingMode.DOWN));
                                    infoList.add(personZBResponse);
                                }
                            }

                        }
                        BigDecimal reduce = infoList.stream().map(PersonZBResponse::getRatio).reduce(BigDecimal.ZERO, BigDecimal::add);
                        for (PersonZBResponse personZBResponse : infoList) {
                            personZBResponse.setRatio(personZBResponse.getRatio().divide(reduce,4,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                            personZBResponse.setSale_ratio(personZBResponse.getRatio());
                        }
                    }
                    else if (debtOne.getState() == 0){
                        infoList1 = getSaleInfo(courseOne);
                        if (infoList1.size() > 0){
                            for (PersonZBResponse personZBResponse : infoList1) {
                                //personZBResponse.setIndex_ratio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                                personZBResponse.setRatio(personZBResponse.getSale_ratio());
                                infoList.add(personZBResponse);
                            }
                        }
                    }
                    else if(debtOne.getState()==2){
                        infoList1 = getSaleInfo(courseOne);
                        //取消欠款，查询是否有还款的操作
                        List<RepayTradeList> tradeLists = ssmRepayTradeDao.queryByDocId(docId);
                        if(tradeLists!=null && tradeLists.size()>0){


                            for (RepayTradeList tradeList : tradeLists) {
                                List<PersonZBResponse> info1 = getSaleInfo(tradeList);
                                if (info1.size()>0){
                                    for (PersonZBResponse personZBResponse : info1) {
                                        personZBResponse.setRatio(((tradeList.getPayMoney()).multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                                        infoList1.add(personZBResponse);
                                    }
                                }

                        }
                            BigDecimal reduce = infoList1.stream().map(PersonZBResponse::getRatio).reduce(BigDecimal.ZERO, BigDecimal::add);
                            //进行员工合并
                            Map<Long, List<PersonZBResponse>> collect = infoList1.stream().collect(Collectors.groupingBy(PersonZBResponse::getId));
                            infoList1 = new ArrayList<>();
                            Iterator<Map.Entry<Long, List<PersonZBResponse>>> iterator = collect.entrySet().iterator();
                            while (iterator.hasNext()){
                                List<PersonZBResponse> value = iterator.next().getValue();
                                PersonZBResponse personZBResponse = new PersonZBResponse();
                                BeanUtils.copyProperties(value.get(0),personZBResponse);
                                BigDecimal bigDecimal = value.stream().map(PersonZBResponse::getRatio).reduce(BigDecimal.ZERO, BigDecimal::add);
                                personZBResponse.setRatio(bigDecimal.divide(reduce,4,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")));
                                personZBResponse.setSale_ratio(personZBResponse.getRatio());
                                infoList1.add(personZBResponse);
                            }
//                            for (PersonZBResponse personZBResponse : infoList1) {
//                                personZBResponse.setRatio(personZBResponse.getRatio().divide(reduce,4,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
//                                personZBResponse.setSale_ratio(personZBResponse.getRatio());
//                            }
                        }


                        if (infoList1.size() > 0){
                            for (PersonZBResponse personZBResponse : infoList1) {
                                //personZBResponse.setIndex_ratio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
//                            personZBResponse.setRatio(personZBResponse.getSale_ratio().divide(new BigDecimal(100),2, RoundingMode.DOWN));
                                personZBResponse.setRatio(personZBResponse.getSale_ratio());
                                infoList.add(personZBResponse);
                            }
                        }
                    }
                }
                if (infoList1.size() == 0){
                    PersonZBResponse personZBResponse = new PersonZBResponse();
                    personZBResponse.setCardSalesAchievement(cardSalesAchievement);
                    personZBResponse.setCardSalesCommission(cardSalesCommission);
                    personZBResponse.setCardAchievementAmount(cardAchievementAmount);
                    personZBResponse.setCardCommissionAmount(cardCommissionAmount);
                    infoList.add(personZBResponse);
                }
            /*}*/

        }
        else if ( "1".equals(courseAccount.getCourseType()) || "2".equals(courseAccount.getCourseType()) ){
            List<PersonZBResponse> infoList1 = new ArrayList<>();

            //促销，根据促销id在促销活动单据表中查询信息
            DocPromotion promotion = new DocPromotion();
            promotion.setId(courseAccount.getPromotionDocId());
            DocPromotion docPromotion = ssmDocPromotionDao.selectOne(promotion);

            DocPromotionProject project = new DocPromotionProject();
            project.setCourseAccountId(courseAccount.getId());
            project.setDocNum(docPromotion.getDocNum());
            project.setPromotionId(docPromotion.getPromotionId());
            DocPromotionProject promotionProject = ssmDocPromotionProjectDao.queryOne(project);

            PromotionProject project1 = new PromotionProject();
            project1.setPromotionId(promotionProject.getPromotionId());
            List<PromotionProject> pros = projectDao.getPros(project1);
            int size = pros.size();

            //cardSalesAchievement = docPromotion.getCardSalesAchievement();//卡付销售业绩标准
            cardSalesCommission = docPromotion.getCardSalesCommission();//卡付销售提成标准
            cardAchievementAmount = docPromotion.getCardAchievementAmount();//卡付销售业绩
            cardCommissionAmount = docPromotion.getCardCommissionAmount();//卡付销售提成

            amount = docPromotion.getAmount();

                /*//未欠款
                List<PersonZBResponse> list = getSaleInfo(docPromotion);
                //reallyAmount = (docPromotion.getCollectionCashAmount()).add(docPromotion.getCollectionRechargeAmount());
                reallyAmount = promotionProject.getProjectTotalMoney();
                if (list.size() > 0){
                    for (PersonZBResponse personZBResponse : list) {
                        //personZBResponse.setIndex_ratio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                        personZBResponse.setIndex_ratio(personZBResponse.getSale_ratio());
                        infoList.add(personZBResponse);
                    }
                }*/

            if (docPromotion.getIsDebt() == 0){
                //未欠款
                infoList1 = getSaleInfo(docPromotion);
                //reallyAmount = (docPromotion.getCollectionCashAmount()).add(docPromotion.getCollectionRechargeAmount());
                reallyAmount = promotionProject.getProjectTotalMoney();
                if (infoList1.size() > 0){
                    for (PersonZBResponse personZBResponse : infoList1) {
                        //personZBResponse.setIndex_ratio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                        personZBResponse.setRatio(personZBResponse.getSale_ratio());
                        infoList.add(personZBResponse);
                    }
                }
            }else {
                //欠款金额
                debtMoney = docPromotion.getDebtMoney();
                //平均每个项目欠款
                BigDecimal debtAvgMoney = debtMoney.divide(new BigDecimal(size),2, RoundingMode.DOWN);
                //欠款单ID
                Long docId = courseAccount.getPromotionDocId();
                DebtList debtList = new DebtList();
                debtList.setDocId(docId);

                reallyAmount = promotionProject.getProjectTotalMoney();
                //结果是: -1：小于； 0 ：等于； 1 ：大于；
                if (reallyAmount.compareTo(debtAvgMoney) > 0){
                    reallyAmount = reallyAmount.subtract(debtAvgMoney);
                }else {
                    reallyAmount = BigDecimal.ZERO;
                }

                //获取欠款单信息
                DebtList debtOne = ssmDebtDao.queryByDocId(debtList).get(0);
                if (debtOne.getState() == 0){//没还款
                    infoList1 = getSaleInfo(docPromotion);
                    //reallyAmount = (docPromotion.getCollectionCashAmount()).add(docPromotion.getCollectionRechargeAmount());
                    /*reallyAmount = promotionProject.getProjectTotalMoney();
                    //结果是: -1：小于； 0 ：等于； 1 ：大于；
                    if (reallyAmount.compareTo(debtAvgMoney) > 1){
                        reallyAmount = reallyAmount.subtract(debtAvgMoney);
                    }*/
                    if (infoList1.size() > 0){
                        for (PersonZBResponse personZBResponse : infoList1) {
                            //personZBResponse.setIndex_ratio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                            personZBResponse.setRatio(personZBResponse.getSale_ratio());
                            infoList.add(personZBResponse);
                        }
                    }
                }else if (debtOne.getState() == 1){
                    infoList1 = getSaleInfo(docPromotion);
                    if (infoList1.size() > 0){
                        for (PersonZBResponse personZBResponse : infoList1) {
                            personZBResponse.setRatio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                            infoList.add(personZBResponse);
                        }
                    }

                    List<RepayTradeList> tradeLists = ssmRepayTradeDao.queryByDocId(debtOne.getDocId());
                    for (RepayTradeList tradeList : tradeLists) {
                        List<PersonZBResponse> info1 = getSaleInfo(tradeList);
                        if (info1.size()>0){
                            for (PersonZBResponse personZBResponse : info1) {
                                personZBResponse.setRatio((((tradeList.getPayMoney()).divide(new BigDecimal(size),2, RoundingMode.DOWN)).multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                                infoList.add(personZBResponse);
                            }
                        }

                    }
                }
            }
            if (infoList1.size() == 0){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setCardSalesAchievement(cardSalesAchievement);
                personZBResponse.setCardSalesCommission(cardSalesCommission);
                personZBResponse.setCardAchievementAmount(cardAchievementAmount);
                personZBResponse.setCardCommissionAmount(cardCommissionAmount);
                infoList.add(personZBResponse);
            }

        }/*else if ("2".equals(courseAccount.getCourseType())){

        }*/
        else if ("3".equals(courseAccount.getCourseType())){
            List<PersonZBResponse> infoList1 = new ArrayList<>();
            //加价转疗程
            CardChangeList cardChangeList = new CardChangeList();
            cardChangeList.setDocNum(courseAccount.getCourseNum());
            //转门店的订单门店id没有改变，需要根据订单前缀的门店编码查询出门店ID
            BaseStore baseStore=new BaseStore();
            if(courseAccount.getCourseNum().startsWith("LCNT")){
                baseStore.setStoreNum(courseAccount.getCourseNum().substring(4, courseAccount.getCourseNum().length()-11));
            }else {
                baseStore.setStoreNum(courseAccount.getCourseNum().substring(3, courseAccount.getCourseNum().length()-11));
            }
            baseStore=ssmBaseStoreService.selectOne(baseStore);
            cardChangeList.setStoreId(baseStore.getId());

            CardChangeList changeList = cardChangeDao.selectListDocNum(cardChangeList).get(0);

            CardChangeInProject inProject = new CardChangeInProject();
            inProject.setDocNum(courseAccount.getCourseNum());
            inProject.setStoreId(baseStore.getId());
            List<CardChangeInProject> cardChangeInProjects = inProjectDao.queryByDocNum(inProject);
            CardChangeInProject changeInProject = cardChangeInProjects.get(0);

            cardSalesAchievement = changeInProject.getCardSalesAchievement();//卡付销售业绩标准
            cardSalesCommission = changeInProject.getCardSalesCommission();//卡付销售提成标准
            cardAchievementAmount = changeInProject.getCardAchievementAmount();//卡付销售业绩
            cardCommissionAmount = changeInProject.getCardCommissionAmount();//卡付销售提成

            amount = changeInProject.getChangeInMoney();
            reallyAmount = amount.subtract(changeList.getDebtMoney());
            if (changeList.getDebtMoney().compareTo(BigDecimal.valueOf(0)) == 0){
                //未欠款
                infoList1 = getSaleInfo(changeInProject);
                if (infoList1.size() > 0){
                    for (PersonZBResponse personZBResponse : infoList1) {
                        //personZBResponse.setIndex_ratio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
//                        personZBResponse.setRatio(personZBResponse.getSale_ratio().divide(new BigDecimal(100),2, RoundingMode.DOWN));
                        personZBResponse.setRatio(personZBResponse.getSale_ratio());
                        infoList.add(personZBResponse);
                    }
                }
            }else {
                debtMoney = changeList.getDebtMoney();
                //欠款单ID
//                Long docId = courseOne.getId();
                String docNum = changeList.getDocNum();
                DebtList debtList = new DebtList();
//                debtList.setDocId(docId);
                debtList.setDocNum(docNum);
                    /*infoList1 = getSaleInfo(courseOne);
                    if (infoList1.size() > 0){
                        for (PersonZBResponse personZBResponse : infoList1) {
                            personZBResponse.setIndex_ratio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                            infoList.add(personZBResponse);
                        }
                    }*/

                //获取欠款单信息
                DebtList debtOne = ssmDebtDao.queryByDocId(debtList).get(0);
                if (debtOne.getState() == 1){
                    debtMoney = BigDecimal.valueOf(0);
                    infoList1 = getSaleInfo(changeInProject);
                    if (infoList1.size() > 0){
                        for (PersonZBResponse personZBResponse : infoList1) {
                            personZBResponse.setRatio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                            infoList.add(personZBResponse);
                        }
                    }

                    List<RepayTradeList> tradeLists = ssmRepayTradeDao.queryByDocNum(docNum);
                    for (RepayTradeList tradeList : tradeLists) {
                        List<PersonZBResponse> info1 = getSaleInfo(tradeList);
                        if (info1.size()>0){
                            for (PersonZBResponse personZBResponse : info1) {
                                personZBResponse.setRatio(((tradeList.getPayMoney()).multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                                infoList.add(personZBResponse);
                            }
                        }

                    }
                    BigDecimal reduce = infoList.stream().map(PersonZBResponse::getRatio).reduce(BigDecimal.ZERO, BigDecimal::add);
                    for (PersonZBResponse personZBResponse : infoList) {
                        personZBResponse.setRatio(personZBResponse.getRatio().divide(reduce,4,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                        personZBResponse.setSale_ratio(personZBResponse.getRatio());
                    }
                }else if (debtOne.getState() == 0){
                    infoList1 = getSaleInfo(changeInProject);
                    if (infoList1.size() > 0){
                        for (PersonZBResponse personZBResponse : infoList1) {
                            //personZBResponse.setIndex_ratio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                            personZBResponse.setRatio(personZBResponse.getSale_ratio());
                            infoList.add(personZBResponse);
                        }
                    }
                }
            }

            /*amount = changeList.getChangeInMoney();

            reallyAmount = (changeList.getChangeInPayMoney()).add(changeList.getChangeOutMoney());
            if (changeList.getIsDebt() == 0){
                //未欠款
                List<PersonZBResponse> list = getSaleInfo(changeList);
                if (list.size() > 0){
                    for (PersonZBResponse personZBResponse : list) {
                        //personZBResponse.setIndex_ratio((reallyAmount.multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                        personZBResponse.setIndex_ratio(personZBResponse.getSale_ratio().divide(new BigDecimal(100),2, RoundingMode.DOWN));
                        infoList.add(personZBResponse);
                    }
                }
            }else {
                //欠款金额
                //BigDecimal debtMoney = changeList.getDebtMoney();
            }*/
            if (infoList1.size() == 0){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setCardSalesAchievement(cardSalesAchievement);
                personZBResponse.setCardSalesCommission(cardSalesCommission);
                personZBResponse.setCardAchievementAmount(cardAchievementAmount);
                personZBResponse.setCardCommissionAmount(cardCommissionAmount);
                infoList.add(personZBResponse);
            }

        }
        else if ("4".equals(courseAccount.getCourseType())){
            MemberInit memberInit = new MemberInit();
            memberInit.setMemberId(courseAccount.getMemberId());
            memberInit.setInitNum(courseAccount.getCourseNum());
            memberInit.setStoreId(courseAccount.getStoreId());
            memberInit.setInitState(4);
            MemberInit init = ssmMemberInitService.selectOne(memberInit);
            //存在欠款
            if (null != init.getDebtMoney() && BigDecimalUtils.compareTo(init.getDebtMoney(), BigDecimalUtils.bigDecimal("0")) > 1){
                amount = init.getStandardMoney();
                debtMoney = init.getDebtMoney();
                reallyAmount = init.getCourseConsumePrice();
                DebtList debtList = new DebtList();
                BeanUtils.copyProperties(init, debtList);
                debtList.setAccountId(init.getAccountId());
                debtList.setTradeMoney(init.getStandardMoney());
                debtList.setDocType(Constant.doc_type_card_use);
                DebtList debtOne = ssmDebtDao.selectOne(debtList);
                Long docId = debtOne.getDocId();

                if (debtOne.getState() == 1){

                    List<RepayTradeList> tradeLists = ssmRepayTradeDao.queryByDocId(docId);
                    for (RepayTradeList tradeList : tradeLists) {
                        cardSalesAchievement = tradeList.getCardSalesAchievement();
                        cardSalesCommission = tradeList.getCardSalesCommission();
                        List<PersonZBResponse> info1 = getSaleInfo(tradeList);
                        if (info1.size()>0){
                            for (PersonZBResponse personZBResponse : info1) {
                                personZBResponse.setRatio(((tradeList.getPayMoney()).multiply(personZBResponse.getSale_ratio())).divide(new BigDecimal(100),2, RoundingMode.DOWN));
                                personZBResponse.setRatio(personZBResponse.getRatio().multiply(BigDecimal.valueOf(100)));
                                infoList.add(personZBResponse);
                            }
                        }

                    }
                }
            }
        }

        if (0 == debtMoney.compareTo(BigDecimal.ZERO)){
            for (PersonZBResponse personZBResponse : infoList) {
                personZBResponse.setCardSalesAchievement(cardSalesAchievement);
                personZBResponse.setCardSalesCommission(cardSalesCommission);
                personZBResponse.setCardAchievementAmount(cardAchievementAmount);
                personZBResponse.setCardCommissionAmount(cardCommissionAmount);
//                if (null != personZBResponse.getRatio()){
//                    personZBResponse.setRatio(personZBResponse.getRatio().multiply(BigDecimal.valueOf(100)));
//                }
            }
            List<PersonZBResponse> collect1 = infoList.stream().filter(item -> item.getId() != null).collect(Collectors.toList());
            Map<Long, List<PersonZBResponse>> collect = collect1.stream().collect(Collectors.groupingBy(PersonZBResponse::getId));
            Iterator<Map.Entry<Long, List<PersonZBResponse>>> iterator = collect.entrySet().iterator();
            List<PersonZBResponse> personZBResponseList = new ArrayList<>();

            while (iterator.hasNext()){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                List<PersonZBResponse> value = iterator.next().getValue();
                personZBResponse.setRatio(BigDecimal.valueOf(0));
                personZBResponse.setSale_ratio(BigDecimal.valueOf(0));
                for (PersonZBResponse p : value){
                    personZBResponse.setStaffId(p.getId());
                    personZBResponse.setId(p.getId());
                    personZBResponse.setType(p.getType());
                    personZBResponse.setRatio(personZBResponse.getRatio().add(p.getRatio()));
                    personZBResponse.setSale_ratio(personZBResponse.getSale_ratio().add(p.getSale_ratio()));
                    personZBResponse.setBrandNumber(p.getBrandNumber());
                    personZBResponse.setStaffName(p.getStaffName());
                }
                personZBResponseList.add(personZBResponse);
            }
            return personZBResponseList;
        }
        else {
            BigDecimal total = reallyAmount;
            BigDecimal totalDebt = debtMoney;
            List<PersonZBResponse> list = new ArrayList<>();

            Map<Long, List<PersonZBResponse>> collect = infoList.stream().collect(Collectors.groupingBy(o ->
                    o.getId(), Collectors.toList()));

            collect.forEach((i, transfer)->{
                transfer.stream()
                        .reduce(
                                (a,b)
                                        ->new PersonZBResponse(a.getId(),
                                        a.getBrandNumber(),
                                        a.getStaffName(),
                                        a.getSale_ratio(),
                                        ((a.getRatio()==null?BigDecimal.valueOf(0):a.getRatio()).add(b.getRatio()==null?BigDecimal.valueOf(0):b.getRatio()))
                                                .divide((total
                                                        .add(totalDebt)),2, RoundingMode.DOWN)))
                        .ifPresent(list::add); //a.getIndex_ratio().add(b.getIndex_ratio())
            });
            for (PersonZBResponse personZBResponse : list) {
                personZBResponse.setCardSalesAchievement(cardSalesAchievement);
                personZBResponse.setCardSalesCommission(cardSalesCommission);
                personZBResponse.setCardAchievementAmount(cardAchievementAmount);
                personZBResponse.setCardCommissionAmount(cardCommissionAmount);
//                if (null != personZBResponse.getRatio()){
//                    personZBResponse.setRatio(personZBResponse.getRatio().multiply(BigDecimal.valueOf(100)));
//                }
            }

            List<PersonZBResponse> collect2 = list.stream().filter(item -> item.getId() != null).collect(Collectors.toList());
            Map<Long, List<PersonZBResponse>> collect1 = collect2.stream().collect(Collectors.groupingBy(PersonZBResponse::getId));
            Iterator<Map.Entry<Long, List<PersonZBResponse>>> iterator = collect1.entrySet().iterator();
            List<PersonZBResponse> personZBResponseList = new ArrayList<>();

            while (iterator.hasNext()){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                List<PersonZBResponse> value = iterator.next().getValue();
                personZBResponse.setRatio(BigDecimal.valueOf(0));
                personZBResponse.setSale_ratio(BigDecimal.valueOf(0));
                for (PersonZBResponse p : value){
                    personZBResponse.setStaffId(p.getId());
                    personZBResponse.setBrandNumber(p.getBrandNumber());
                    personZBResponse.setStaffName(p.getStaffName());
                    personZBResponse.setId(p.getId());
                    personZBResponse.setType(p.getType());
                    personZBResponse.setRatio(personZBResponse.getRatio().add(p.getRatio()));
                    personZBResponse.setSale_ratio(personZBResponse.getSale_ratio().add(p.getSale_ratio()));
                }
                personZBResponseList.add(personZBResponse);
            }
            return personZBResponseList;
        }
        //infoList.stream()

        //return infoList;
    }

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

    //获取销售员占比信息
    public List<PersonZBResponse> getSaleInfo(Object obj){
        List<PersonZBResponse> list = new ArrayList<>();
        BigDecimal hundred = new BigDecimal("100");
        if (obj instanceof CourseList){
            CourseList courseList = (CourseList) obj;

            if (courseList.getSaleOneStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(courseList.getSaleOneStaffId());
                personZBResponse.setBrandNumber(courseList.getSaleOneNumber());
                personZBResponse.setStaffName(courseList.getSaleOneStaffName());
                personZBResponse.setSale_ratio(courseList.getSaleOneRatio());
                personZBResponse.setRatio(courseList.getAchievementAmount().multiply(personZBResponse.getSale_ratio()).divide(hundred));
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (courseList.getSaleTwoStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(courseList.getSaleTwoStaffId());
                personZBResponse.setBrandNumber(courseList.getSaleTwoNumber());
                personZBResponse.setStaffName(courseList.getSaleTwoStaffName());
                personZBResponse.setSale_ratio(courseList.getSaleTwoRatio());
                personZBResponse.setRatio(courseList.getAchievementAmount().multiply(personZBResponse.getSale_ratio()).divide(hundred));
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (courseList.getSaleThreeStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(courseList.getSaleThreeStaffId());
                personZBResponse.setBrandNumber(courseList.getSaleThreeNumber());
                personZBResponse.setStaffName(courseList.getSaleThreeStaffName());
                personZBResponse.setSale_ratio(courseList.getSaleThreeRatio());
                personZBResponse.setRatio(courseList.getAchievementAmount().multiply(personZBResponse.getSale_ratio()).divide(hundred));
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (courseList.getSaleFourStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(courseList.getSaleFourStaffId());
                personZBResponse.setBrandNumber(courseList.getSaleFourNumber());
                personZBResponse.setStaffName(courseList.getSaleFourStaffName());
                personZBResponse.setSale_ratio(courseList.getSaleFourRatio());
                personZBResponse.setRatio(courseList.getAchievementAmount().multiply(personZBResponse.getSale_ratio()).divide(hundred));
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (courseList.getSaleFiveStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(courseList.getSaleFiveStaffId());
                personZBResponse.setBrandNumber(courseList.getSaleFiveNumber());
                personZBResponse.setStaffName(courseList.getSaleFiveStaffName());
                personZBResponse.setSale_ratio(courseList.getSaleFiveRatio());
                personZBResponse.setRatio(courseList.getAchievementAmount().multiply(personZBResponse.getSale_ratio()).divide(hundred));
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (courseList.getSaleSixStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(courseList.getSaleSixStaffId());
                personZBResponse.setBrandNumber(courseList.getSaleSixNumber());
                personZBResponse.setStaffName(courseList.getSaleSixStaffName());
                personZBResponse.setSale_ratio(courseList.getSaleSixRatio());
                personZBResponse.setRatio(courseList.getAchievementAmount().multiply(personZBResponse.getSale_ratio()).divide(hundred));
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (courseList.getSaleSevenStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(courseList.getSaleSevenStaffId());
                personZBResponse.setBrandNumber(courseList.getSaleSevenNumber());
                personZBResponse.setStaffName(courseList.getSaleSevenStaffName());
                personZBResponse.setSale_ratio(courseList.getSaleSevenRatio());
                personZBResponse.setRatio(courseList.getAchievementAmount().multiply(personZBResponse.getSale_ratio()).divide(hundred));
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (courseList.getSaleEightStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(courseList.getSaleEightStaffId());
                personZBResponse.setBrandNumber(courseList.getSaleEightNumber());
                personZBResponse.setStaffName(courseList.getSaleEightStaffName());
                personZBResponse.setSale_ratio(courseList.getSaleEightRatio());
                personZBResponse.setRatio(courseList.getAchievementAmount().multiply(personZBResponse.getSale_ratio()).divide(hundred));
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }
        }
        else if (obj instanceof RepayTradeList){
            RepayTradeList repayTradeList = (RepayTradeList) obj;
            if (repayTradeList.getSaleOneStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(repayTradeList.getSaleOneStaffId());
                personZBResponse.setBrandNumber(repayTradeList.getSaleOneNumber());
                personZBResponse.setStaffName(repayTradeList.getSaleOneStaffName());
                personZBResponse.setSale_ratio(repayTradeList.getSaleOneRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (repayTradeList.getSaleTwoStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(repayTradeList.getSaleTwoStaffId());
                personZBResponse.setBrandNumber(repayTradeList.getSaleTwoNumber());
                personZBResponse.setStaffName(repayTradeList.getSaleTwoStaffName());
                personZBResponse.setSale_ratio(repayTradeList.getSaleTwoRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (repayTradeList.getSaleThreeStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(repayTradeList.getSaleThreeStaffId());
                personZBResponse.setBrandNumber(repayTradeList.getSaleThreeNumber());
                personZBResponse.setStaffName(repayTradeList.getSaleThreeStaffName());
                personZBResponse.setSale_ratio(repayTradeList.getSaleThreeRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (repayTradeList.getSaleFourStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(repayTradeList.getSaleFourStaffId());
                personZBResponse.setBrandNumber(repayTradeList.getSaleFourNumber());
                personZBResponse.setStaffName(repayTradeList.getSaleFourStaffName());
                personZBResponse.setSale_ratio(repayTradeList.getSaleFourRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }
        }
        else if (obj instanceof DocPromotion){
            DocPromotion docPromotion = (DocPromotion) obj;
            if (docPromotion.getSaleOneStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(docPromotion.getSaleOneStaffId());
                personZBResponse.setBrandNumber(docPromotion.getSaleOneNumber());
                personZBResponse.setStaffName(docPromotion.getSaleOneStaffName());
                personZBResponse.setSale_ratio(docPromotion.getSaleOneRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (docPromotion.getSaleTwoStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(docPromotion.getSaleTwoStaffId());
                personZBResponse.setBrandNumber(docPromotion.getSaleTwoNumber());
                personZBResponse.setStaffName(docPromotion.getSaleTwoStaffName());
                personZBResponse.setSale_ratio(docPromotion.getSaleTwoRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (docPromotion.getSaleThreeStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(docPromotion.getSaleThreeStaffId());
                personZBResponse.setBrandNumber(docPromotion.getSaleThreeNumber());
                personZBResponse.setStaffName(docPromotion.getSaleThreeStaffName());
                personZBResponse.setSale_ratio(docPromotion.getSaleThreeRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (docPromotion.getSaleFourStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(docPromotion.getSaleFourStaffId());
                personZBResponse.setBrandNumber(docPromotion.getSaleFourNumber());
                personZBResponse.setStaffName(docPromotion.getSaleFourStaffName());
                personZBResponse.setSale_ratio(docPromotion.getSaleFourRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }
        }
        else if (obj instanceof CardChangeInProject){
            CardChangeInProject cardChangeList = (CardChangeInProject) obj;
            if (cardChangeList.getSaleOneStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(cardChangeList.getSaleOneStaffId());
                personZBResponse.setBrandNumber(cardChangeList.getSaleOneNumber());
                personZBResponse.setStaffName(cardChangeList.getSaleOneStaffName());
                personZBResponse.setSale_ratio(cardChangeList.getSaleOneRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (cardChangeList.getSaleTwoStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(cardChangeList.getSaleTwoStaffId());
                personZBResponse.setBrandNumber(cardChangeList.getSaleTwoNumber());
                personZBResponse.setStaffName(cardChangeList.getSaleTwoStaffName());
                personZBResponse.setSale_ratio(cardChangeList.getSaleTwoRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (cardChangeList.getSaleThreeStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(cardChangeList.getSaleThreeStaffId());
                personZBResponse.setBrandNumber(cardChangeList.getSaleThreeNumber());
                personZBResponse.setStaffName(cardChangeList.getSaleThreeStaffName());
                personZBResponse.setSale_ratio(cardChangeList.getSaleThreeRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (cardChangeList.getSaleFourStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(cardChangeList.getSaleFourStaffId());
                personZBResponse.setBrandNumber(cardChangeList.getSaleFourNumber());
                personZBResponse.setStaffName(cardChangeList.getSaleFourStaffName());
                personZBResponse.setSale_ratio(cardChangeList.getSaleFourRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (cardChangeList.getSaleFiveStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(cardChangeList.getSaleFiveStaffId());
                personZBResponse.setBrandNumber(cardChangeList.getSaleFiveNumber());
                personZBResponse.setStaffName(cardChangeList.getSaleFiveStaffName());
                personZBResponse.setSale_ratio(cardChangeList.getSaleFiveRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (cardChangeList.getSaleSixStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(cardChangeList.getSaleSixStaffId());
                personZBResponse.setBrandNumber(cardChangeList.getSaleSixNumber());
                personZBResponse.setStaffName(cardChangeList.getSaleSixStaffName());
                personZBResponse.setSale_ratio(cardChangeList.getSaleSixRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (cardChangeList.getSaleSevenStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(cardChangeList.getSaleSevenStaffId());
                personZBResponse.setBrandNumber(cardChangeList.getSaleSevenNumber());
                personZBResponse.setStaffName(cardChangeList.getSaleSevenStaffName());
                personZBResponse.setSale_ratio(cardChangeList.getSaleSevenRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }if (cardChangeList.getSaleEightStaffId() != null){
                PersonZBResponse personZBResponse = new PersonZBResponse();
                personZBResponse.setId(cardChangeList.getSaleEightStaffId());
                personZBResponse.setBrandNumber(cardChangeList.getSaleEightNumber());
                personZBResponse.setStaffName(cardChangeList.getSaleEightStaffName());
                personZBResponse.setSale_ratio(cardChangeList.getSaleEightRatio());
                personZBResponse.setType(2);
                list.add(personZBResponse);
            }

        }

        return list;
    }


    public String getKey(String phone){
        String key = "";
        if (StringUtils.isNotBlank(phone)){
            key = Constant.staffKey + phone;
        }
        return key;
    }
    @Override
    public StaffTemporaryVo uniPhoneLogin(MemberRequest memberRequest) throws SmsException {

        //获取redis codeKey值
        String codeKey = getPasscodeKey(memberRequest.getMobilePhone());
        StaffTemporaryVo staffTemporaryVo = new StaffTemporaryVo();
        String token = "";
        String passCode = memberRequest.getPassCode();
        Example example = new Example(BlackList.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isEmpty(memberRequest.getMobilePhone())){
            throw new SmsException(ResponseCode.MSG,"请输入手机号！");
        }
        criteria.andEqualTo(StaffRequest.Fields.mobilePhone,memberRequest.getMobilePhone());
//        criteria.andEqualTo(StaffRequest.Fields.storeId,memberRequest.getStoreId());
        List<BlackList> list = blackListDao.selectByExample(example);
        if(CollectionUtils.isEmpty(list)) {
            throw new SmsException(ResponseCode.MSG,"用户未注册！");
        }else {
            BlackList blackList = list.get(0);
            BeanUtils.copyProperties(blackList, staffTemporaryVo);
        }
        //从redis查询
        if (redisClient.hasKey(codeKey)){
            //校验验证码
            if (passCode.equals(memberResponseRedisClient.get(codeKey).getPassCode())) {
                Example staffExample = new Example(StaffTemporary.class);
                Example.Criteria staffExampleCriteria = staffExample.createCriteria();
                staffExampleCriteria.andEqualTo(StaffTemporaryDto.Fields.identityCard,staffTemporaryVo.getIdentityCard());
                staffExample.setOrderByClause("end_time desc, ruzhi_time desc");
//                PageHelper.startPage(1,999,"end_time desc,ruzhi_time desc");
                List<StaffTemporary> staffTemporaries = staffTemporaryDao.selectByExample(staffExample);
                if (!CollectionUtils.isEmpty(staffTemporaries)){
                    staffTemporaryVo.setId(staffTemporaries.get(0).getId());
                    staffTemporaryVo.setType(staffTemporaries.get(0).getType());
                    staffTemporaryVo.setRegionId(staffTemporaries.get(0).getRegionId());
                    staffTemporaryVo.setRuzhiTime(staffTemporaries.get(0).getRuzhiTime());
                    staffTemporaryVo.setRemark(staffTemporaries.get(0).getRemark());
                    staffTemporaryVo.setIsBeisen(staffTemporaries.get(0).getIsBeisen());
                    staffTemporaryVo.setIsZhongkong(staffTemporaries.get(0).getIsZhongkong());
                    if (staffTemporaries.size()>1) {
                        staffTemporaryVo.setIsOne(0);
                    }else {
                        staffTemporaryVo.setIsOne(1);
                    }
                }
                staffTemporaryVo.setFacesInformation(null);
                staffTemporaryVo.setBaseStores(ssmBaseStoreService.selectByPrimaryKey(staffTemporaryVo.getStoreId()));

                staffTemporaryVo.setRegionList(regionListDao.selectByPrimaryKey(staffTemporaryVo.getRegionId()));
                token = UUID.randomUUID().toString();
                staffTemporaryVo.setToken(token);

                staffTemporaryVoRedisClient.set(Constant.staffTemporary + token,staffTemporaryVo,RedisClient.EXPIRE_TIME_ONE_DAY, TimeUnit.SECONDS);
            }
        }else {
            //redis不存在 验证码已过期
            throw new SmsException(ResponseCode.MSG,"验证码已过期，请重新发送");
        }

        staffTemporaryVo.setFacesInformation(list.get(0).getFacesInformation());
        return staffTemporaryVo;
    }

    @Override
    public StaffTemporaryVo uniPhoneLoginNew(MemberRequest memberRequest) throws SmsException {
        //获取redis codeKey值
        String codeKey = getPasscodeKey(memberRequest.getMobilePhone());
        StaffTemporaryVo staffTemporaryVo = new StaffTemporaryVo();
        String token = "";
        String passCode = memberRequest.getPassCode();
        Example example = new Example(BlackList.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isEmpty(memberRequest.getMobilePhone())){
            throw new SmsException(ResponseCode.MSG,"请输入手机号！");
        }
        if(ObjectUtils.isEmpty(passCode)){
            throw new SmsException(ResponseCode.MSG,"请输入验证码");
        }
        criteria.andEqualTo(StaffRequest.Fields.mobilePhone, memberRequest.getMobilePhone());
        criteria.andEqualTo(StaffRequest.Fields.storeId, memberRequest.getStoreId());
        List<BlackList> list = blackListDao.selectByExample(example);
        BlackList blackList;
        if(CollectionUtils.isEmpty(list)) {
            throw new SmsException(ResponseCode.MSG,"用户未注册！");
        }else {
            blackList = list.get(0);
            BeanUtils.copyProperties(blackList, staffTemporaryVo, "id");
        }

        Example staffExample = new Example(StaffTemporary.class);
        Example.Criteria staffExampleCriteria = staffExample.createCriteria();
        staffExampleCriteria.andEqualTo(StaffTemporaryDto.Fields.identityCard, staffTemporaryVo.getIdentityCard());
        staffExample.setOrderByClause("ruzhi_time desc,end_time desc");
//                PageHelper.startPage(1,999,"end_time desc,ruzhi_time desc");
        List<StaffTemporary> staffTemporaries = staffTemporaryDao.selectByExample(staffExample);
        StaffTemporary staffTemporary;
        if (CollectionUtils.isEmpty(staffTemporaries)) {
            log.error("找不到对应的身份信息: {}", staffTemporaryVo);
            throw new SmsException(ResponseCode.FAILED);
        } else {
            staffTemporary = staffTemporaries.get(0);
            staffTemporaryVo.setId(staffTemporary.getId());
        }

        //TODO 取消校验限制
        //从redis查询  if (redisClient.hasKey(codeKey))  if (passCode.equals(memberResponseRedisClient.get(codeKey).getPassCode()))
        if (redisClient.hasKey(codeKey)){
            //校验验证码
            if (passCode.equals(memberResponseRedisClient.get(codeKey).getPassCode())){
                staffTemporaryVo.setId(staffTemporary.getId());
                staffTemporaryVo.setType(staffTemporary.getType());
                staffTemporaryVo.setRegionId(staffTemporary.getRegionId());
                staffTemporaryVo.setRuzhiTime(staffTemporary.getRuzhiTime());
                staffTemporaryVo.setRemark(staffTemporary.getRemark());
                staffTemporaryVo.setIsBeisen(staffTemporary.getIsBeisen());
                staffTemporaryVo.setIsZhongkong(staffTemporary.getIsZhongkong());
                if (staffTemporaries.size()>1) {
                    staffTemporaryVo.setIsOne(0);
                }else {
                    staffTemporaryVo.setIsOne(1);
                }

                staffTemporaryVo.setFacesInformation(null);
                staffTemporaryVo.setBaseStores(ssmBaseStoreService.selectByPrimaryKey(staffTemporaryVo.getStoreId()));

                staffTemporaryVo.setRegionList(regionListDao.selectByPrimaryKey(staffTemporaryVo.getRegionId()));
                token = UUID.randomUUID().toString();
                staffTemporaryVo.setToken(token);

                // 设置 Token
                staffTemporaryVoRedisClient.set(Constant.staffTemporary + token, staffTemporaryVo, RedisClient.EXPIRE_TIME_ONE_DAY, TimeUnit.SECONDS);
                // 删除验证码, 不允许重用验证码
                redisClient.delete(codeKey);
            } else {
                throw new SmsException(ResponseCode.MSG, "验证码错误");
            }
        }else {
            //redis不存在 验证码已过期
            throw new SmsException(ResponseCode.MSG,"验证码已过期，请重新发送");
        }

        staffTemporaryVo.setFacesInformation(blackList.getFacesInformation());
        return staffTemporaryVo;
    }

    @Override
    public Boolean staffSelect(StaffRequest staffRequest) {
        Example blackExample = new Example(BlackList.class);
        Example.Criteria blackExampleCriteria = blackExample.createCriteria();
        blackExampleCriteria.andEqualTo(BlackListDto.Fields.identityCard,staffRequest.getIdentityCard());
        blackExample.or(blackExample.createCriteria().andEqualTo(BlackListDto.Fields.mobilePhone,staffRequest.getMobilePhone()));
        List<BlackList> blackLists = blackListDao.selectByExample(blackExample);
        if (!CollectionUtils.isEmpty(blackLists)){
            return true;
        }
        return false;
    }

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