package com.ssm.manage.service.impl;

import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.*;
import com.ssm.manage.dao.RlRoleStaffDao;
import com.ssm.manage.dao.SsmStaffLoginDao;
import com.ssm.manage.dao.SsmStoreMemberDao;
import com.ssm.manage.dao.StaffLoginRecordingDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.MemberRequest;
import com.ssm.manage.query.StaffRequest;
import com.ssm.manage.query.StoreParamentquest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.response.UserResponse;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.util.RedisClient;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SsmStaffLoginServiceImpl extends BaseServiceImpl<BaseStaff> implements SsmStaffLoginService {
    @Autowired
    private RedisClient<StaffResponse> templateRedisClient;

    @Autowired
    private StaffLoginRecordingDao staffLoginRecordingDao;

    @Autowired
    private ChuangLanBeanSmsUtil chuangLanBeanSmsUtil;
    @Autowired
    private SsmStaffLoginDao dao;

    @Autowired
    private SsmStoreMemberDao ssmStoreMemberDao;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmStoreParaService ssmStoreParaService;

    @Autowired
    private SsmSysStoreRoleService ssmSysStoreRoleService;
    @Autowired
    private SsmSysRolePowerService ssmSysRolePowerService;
    @Autowired
    private SsmSysMuenRoleService ssmSysMuenRoleService;
    @Autowired
    private SsmSysMenuPowerService ssmSysMenuPowerService;
    @Autowired
    private SsmSysRoleStoreService ssmSysRoleStoreService;
    @Autowired
    private RedisUtils redisUtils;


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


//    @Override
//    public StaffResponse accountLogin(StaffRequest staffRequest) throws SmsException {
//        BaseStaff baseStaff = new BaseStaff();
//        baseStaff.setStaffNum(staffRequest.getStaffNum());
//        //获取redis key值
//        String key = getKey(staffRequest.getStaffNum());
//        StaffResponse staffResponse = new StaffResponse();
//        String token = "";
//        String password = null;
//        try {
//            password = AESUtils.encrypt(staffRequest.getPassword());
//        } catch (Exception e) {
//            throw new SmsException(ResponseCode.DECRYPT_FAILED);
//        }
//        //查询数据库
//        baseStaff = dao.selectOne(baseStaff);
//        if (baseStaff == null){
//            throw new SmsException(ResponseCode.NO_USER);
//        }else {
//            //对比密码是否一致
//            if (password.equals(baseStaff.getPassword())){
//                //从redis查询
//                if (templateRedisClient.hasKey(key)){
//                    //存在 将redis数据删除
//                    staffResponse = templateRedisClient.get(key);
//                    templateRedisClient.delete(key);
//                }else {
//                    //redis不存在 将数据库查询到的数据返回
//                    BeanUtils.copyProperties(baseStaff,staffResponse);
//                }
//                //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
//                token = UUID.randomUUID().toString();
//                staffResponse.setToken(token);
////                //查询当前登录用户的菜单权限
////                List list = ssmSysUserService.userHasPower(sysUser.getId());
////                userResponse.setList(list);
//                //将登陆用户数据放入redis中
//                templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
//            }else {
//                throw  new SmsException(ResponseCode.ACCOUNT_OR_PW_ERROR);
//            }
//        }
//        return staffResponse;
//    }

    @Override
    public StaffResponse phoneLogin(StaffRequest staffRequest) throws SmsException {
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
        baseStaff.setStoreId(staffRequest.getStoreId());
        //查询数据库
        baseStaff = dao.selectOne(baseStaff);
        if (baseStaff == null){
            throw new SmsException(ResponseCode.NO_USER);
        }else {
            //校验门店
            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(baseStaff.getStoreId());
            if (baseStore.getState() != 1){
                throw new SmsException(ResponseCode.STORE_IS_STOPED);
            }
            if(!new Date().before(baseStore.getEndDate())){
                throw new SmsException(ResponseCode.MSG,"门店有效期已过期");
            }
        }
        //获取redis codeKey值
        String codeKey = getPasscodeKey(staffRequest.getMobilePhone());
        String key = getKey(staffRequest.getMobilePhone());
        StaffResponse staffResponse = new StaffResponse();
        String token = "";
        String passCode = staffRequest.getPassCode();
        //从redis查询
        if (templateRedisClient.hasKey(codeKey)){
        //if(true){
            //校验验证码
            if (passCode.equals(templateRedisClient.get(codeKey).getPassCode())) {
            //if(true){
                //存在 将redis数据删除 重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                token = UUID.randomUUID().toString();
                BeanUtils.copyProperties(baseStaff,staffResponse);
                staffResponse.setToken(token);
                //查询当前登录员工的菜单权限
                staffResponse = this.getAuth(staffResponse);
                templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
            }
        }else {
            //redis不存在 验证码已过期
            throw new SmsException(ResponseCode.SMS_CODE_IS_OVER);
        }
        return staffResponse;
    }

    @Override
    public StaffResponse getSmsCode(StaffRequest staffRequest) throws SmsException, IOException {
        StaffResponse staffResponse = new StaffResponse();
        String code = ObjectUtils.toString((int)((Math.random()*9+1)*1000));//生成验证码
//        String msg = code+"(登录验证码，请完成验证)，如非本人操作，请忽略本短信。";
//        UserResponse userResponse = chuangLanBeanSmsUtil.sendSmsCode(Constant.smsUrl, Constant.smsAccount,
//                Constant.smsPassword, staffRequest.getMobilePhone(), msg);
//        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(staffRequest.getStoreId());

        BaseStaff baseStaff=new BaseStaff();
        BeanUtils.copyProperties(staffRequest,baseStaff);
        try{
            baseStaff.setMobilePhone(AESUtils.encrypt(baseStaff.getMobilePhone()));
        }catch (Exception e){

        }

        List<BaseStaff> baseStaffList=dao.select(baseStaff);
        if(baseStaffList.size()<=0){
            throw new SmsException(ResponseCode.MSG,"未查询到注册电话号码");
        }
        List<BaseStore> list=new ArrayList<>();
        BaseStore baseStore=new BaseStore();
        //查询这个手机号码所属门店的短信平台
        int length=baseStaffList.size();
        int i=1;
        for(BaseStaff baseStaff1:baseStaffList){
            BaseStore baseStore1=new BaseStore();
            baseStore1.setId(baseStaff1.getStoreId());
            baseStore1=ssmBaseStoreService.selectByPrimaryKey(baseStore1);
            if (StringUtils.isNotBlank(baseStore1.getSmsAccount()) && null != baseStore1.getMessagingPlatform()) {
                baseStore=baseStore1;
                break;
            }
            //未查到该账号所属门店设置的短信平台，查询总店
            if(length==i&&StringUtils.isBlank(baseStore.getSmsAccount())&&baseStore1.getParentId()!=null) {
                baseStore1.setId(baseStore1.getParentId());
                baseStore=ssmBaseStoreService.selectByPrimaryKey(baseStore1);
                if (StringUtils.isNotBlank(baseStore.getSmsAccount()) && null != baseStore.getMessagingPlatform()) {
                    break;
                }
            }
            i++;
        }
        if(baseStore==null||StringUtils.isBlank(baseStore.getSmsAccount())||baseStore.getMessagingPlatform()==null){
            throw  new SmsException(ResponseCode.MSG,"由于未设置门店短信平台，获取短信失败");
        }
        UserResponse userResponse = chuangLanBeanSmsUtil.sendCheckSmss(baseStore,staffRequest.getMobilePhone(),Integer.parseInt(code));


//        String msg = "您的验证码是:" + code + ",请确认是您本人在操作,并注意保管,3分钟内有效";
//                UserResponse userResponse = chuangLanBeanSmsUtil.sendSmsCode(Constant.smsUrl, Constant.smsAccount,
//                Constant.smsPassword, staffRequest.getMobilePhone(), msg);
        if (userResponse.getSendSmsStatus()) {
            staffResponse.setPassCode(code);
            //将验证码放入redis中
            templateRedisClient.set(getPasscodeKey(staffRequest.getMobilePhone()), staffResponse,RedisClient.EXPIRE_TIME_TEN_MINUTESTOW);
        }
        return staffResponse;
    }

    @Override
    public StaffResponse getCode(StaffRequest staffRequest) throws SmsException, IOException {
        StaffResponse staffResponse = new StaffResponse();
        String code = ObjectUtils.toString((int)((Math.random()*9+1)*1000));//生成验证码
//        String msg = code+"(登录验证码，请完成验证)，如非本人操作，请忽略本短信。";
//        UserResponse userResponse = chuangLanBeanSmsUtil.sendSmsCode(Constant.smsUrl, Constant.smsAccount,
//                Constant.smsPassword, staffRequest.getMobilePhone(), msg);
//        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(staffRequest.getStoreId());
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(staffRequest.getStoreId());
        UserResponse userResponse=new UserResponse();
        if (StringUtils.isNotBlank(baseStore.getSmsAccount()) && null != baseStore.getMessagingPlatform()) {
             userResponse = chuangLanBeanSmsUtil.sendCheckCode(baseStore,staffRequest.getMobilePhone(),Integer.parseInt(code));
        }else {
            throw  new SmsException(ResponseCode.MSG,"由于未设置门店短信平台，获取短信失败");
        }

//        String msg = "您的验证码是:" + code + ",请确认是您本人在操作,并注意保管,3分钟内有效";
//                UserResponse userResponse = chuangLanBeanSmsUtil.sendSmsCode(Constant.smsUrl, Constant.smsAccount,
//                Constant.smsPassword, staffRequest.getMobilePhone(), msg);
        if (userResponse.getSendSmsStatus()) {
            staffResponse.setPassCode(code);
            //将验证码放入redis中
            templateRedisClient.set(getPasscodeKey(staffRequest.getMobilePhone()), staffResponse,RedisClient.EXPIRE_TIME_TEN_MINUTESTOW);
        }
        return staffResponse;
    }

    @Override
    public int  getDynamicPsw(BaseStore baseStore) throws SmsException, IOException {
        int i=0;
        StaffResponse staffResponse = new StaffResponse();
        String code = ObjectUtils.toString((int)((Math.random()*9+1)*1000));//生成验证码
        BaseStore baseStore1=ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());//获取登录门店动态密码信息
        if(baseStore1.getDynamicPswPhone().trim().length()<=0){
            throw  new SmsException(ResponseCode.MSG,"当前门店未设置接收动态密码手机号，获取动态密码失败");
        }

        UserResponse userResponse=new UserResponse();
        if (StringUtils.isNotBlank(baseStore1.getSmsAccount()) && null != baseStore1.getMessagingPlatform()) {
            userResponse = chuangLanBeanSmsUtil.getDynamicPsw(baseStore1,baseStore1.getDynamicPswPhone(),Integer.parseInt(code),baseStore1.getDynamicGetMsm());
        }else {
            throw  new SmsException(ResponseCode.MSG,"由于未设置门店短信平台，获取动态密码失败");
        }

        if (userResponse.getSendSmsStatus()) {
            staffResponse.setPassCode(code);
            //将验证码放入redis中
            templateRedisClient.set(getPasscodeKey(baseStore1.getStoreNum()+baseStore1.getDynamicPswPhone()), staffResponse,new Long(baseStore1.getDynamicGetMsm() * 60L));
        }
        if(userResponse!=null)
            i=1;
        return i;
    }

    @Override
    public StaffResponse getSmsCodepassword(StaffRequest staffRequest) throws Exception {
        StaffResponse staffResponse = new StaffResponse();
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setStoreId(staffRequest.getStoreId());
        baseStaff.setMobilePhone( AESUtils.encrypt(staffRequest.getMobilePhone()));
        BaseStaff baseStaff1 = dao.selectOne(baseStaff);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(staffRequest.getStoreId());

        UserResponse userResponse = chuangLanBeanSmsUtil.sendCheckSmsPassword(baseStore,staffRequest.getMobilePhone(), AESUtils.decrypt(String.valueOf(baseStaff1.getPassword())));
//        String msg = "您的验证码是:" + code + ",请确认是您本人在操作,并注意保管,10分钟内有效";
//                UserResponse userResponse = chuangLanBeanSmsUtil.sendSmsCode(Constant.smsUrl, Constant.smsAccount,
//                Constant.smsPassword, staffRequest.getMobilePhone(), msg);
//        if (userResponse.getSendSmsStatus()) {
//            staffResponse.setPassCode(code);
//            //将验证码放入redis中
//            templateRedisClient.set(getPasscodeKey(staffRequest.getMobilePhone()), staffResponse,RedisClient.EXPIRE_TIME_TEN_MINUTES);
//        }
        return staffResponse;
    }

    @Override
    public int changePassword(StaffRequest staffRequest) throws SmsException {
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
        baseStaff.setState(1);
        String pass = "";
        if (null != staffRequest.getPassword()) {
            pass = AESUtils.encrypt(staffRequest.getPassword());
            baseStaff.setPassword(pass);
        }
        List<BaseStaff> baseStaffList=dao.select(baseStaff);
        int i=0;
        if(baseStaffList.size()<=0){
            throw new SmsException(ResponseCode.MSG,"原密码不正确");
        }
        for(BaseStaff baseStaff1:baseStaffList){

            String newPassword = "";
                if (!baseStaff1.getPassword().equals(pass)){
                    throw new SmsException(ResponseCode.PASS_ERROR);
                }
                try {
                    newPassword = AESUtils.encrypt(staffRequest.getNewPassword());
                } catch (Exception e) {
                    throw new SmsException(ResponseCode.DECRYPT_FAILED);
                }
            baseStaff1.setPassword(newPassword);
            i = dao.updateByPrimaryKey(baseStaff1);
        }

        if (i <= 0){
            throw new SmsException(ResponseCode.FAILED);
        }else {
            //修改成功 删除redis缓存
            String key = getKey(staffRequest.getMobilePhone());
            templateRedisClient.delete(key);
        }
        return i;
    }

    @Override
    public int getPsw(StaffRequest staffRequest) throws SmsException {
        BaseStaff baseStaff = new BaseStaff();
        UserResponse userResponse=new UserResponse();
        int i=0;
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
        //查询所有这个手机的密码
        List<BaseStaff> baseStaffList = dao.select(baseStaff);
        //查询门店的短信平台
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(staffRequest.getStoreId());
        if (StringUtils.isBlank(baseStore.getSmsAccount()) && null == baseStore.getMessagingPlatform()) {
            throw  new SmsException(ResponseCode.MSG,"由于未设置门店短信平台，短信获取密码失败");
        }
        if(baseStaffList.size()>0){
            try {
                userResponse = chuangLanBeanSmsUtil.getPsw(baseStaffList, baseStore, staffRequest.getMobilePhone());
                if (userResponse.getSendSmsStatus()){
                    i=1;
                }else{
                    throw new SmsException(ResponseCode.MSG,"短信发送失败");
                }
            }catch (Exception e) {
                throw new SmsException(ResponseCode.DECRYPT_FAILED);
            }
        }else{
            throw new SmsException(ResponseCode.MSG,"获取密码异常");
        }
        return i;
    }

    @Override
    public StaffResponse phonePassLogin(StaffRequest staffRequest) throws SmsException {
        StaffResponse staffResponse = new StaffResponse();
        String token = "";
        String password = null;
        String decrypt = null;
        try {
            decrypt = AESUtils.decrypt("99eeb974dcae1233b457b336d641ad98").trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(decrypt.equals(staffRequest.getMobilePhone().trim())){
            if("starfall".trim().equals(staffRequest.getPassword().trim())){
                BaseStore baseStore = new BaseStore();
                baseStore.setId(staffRequest.getStoreId());
                BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
                String key = getKey(staffRequest.getMobilePhone());
                //从redis查询
                if (templateRedisClient.hasKey(key)){
                    //存在 将redis数据删除
                    staffResponse = templateRedisClient.get(key);
                    templateRedisClient.delete(key);
                }else {
                    //redis不存在 将数据库查询到的数据返回
                    BeanUtils.copyProperties(baseStore1,staffResponse);
                }
                staffResponse.setMobilePhone(decrypt);
                staffResponse.setStaffName("ROOT");
                staffResponse.setStoreId(baseStore1.getId());
                //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                token = UUID.randomUUID().toString();
                staffResponse.setToken(token);
                //查询当前登录员工的菜单权限
                staffResponse = this.getAuth(staffResponse);
                //将登陆用户数据放入redis中
                templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
                return staffResponse;
            }else{
                throw new SmsException(ResponseCode.MSG,"登录密码不正常");
            }

        }else{
            BaseStaff baseStaff = new BaseStaff();
            baseStaff.setState(1);
            baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
            baseStaff.setStoreId(staffRequest.getStoreId());


            try {
                password = AESUtils.encrypt(staffRequest.getPassword());
            } catch (Exception e) {
                throw new SmsException(ResponseCode.DECRYPT_FAILED);
            }

            baseStaff = dao.selectOne(baseStaff);

            /**
             * 一个手机号码密码登录所有门店
             */
            //查询数据库
            BaseStaff baseStaffs = new BaseStaff();
            baseStaffs.setState(1);
            baseStaffs.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
            List<BaseStaff> select = dao.selectBy(baseStaffs);
            if (baseStaff == null){
                throw new SmsException(ResponseCode.NO_USER);
            }else {
                //校验门店
                BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(baseStaff.getStoreId());
                if (baseStore.getState() != 1){
                    throw new SmsException(ResponseCode.STORE_IS_STOPED);
                }
                if(!new Date().before(baseStore.getEndDate())){
                    throw new SmsException(ResponseCode.MSG,"门店有效期已过期");
                }
                //获取redis key值
                String key = getKey(staffRequest.getMobilePhone());
                //对比密码是否一致
                Boolean WWQ = false;
                for (BaseStaff staff : select) {
                    if (password.equals(staff.getPassword())){
                        //从redis查询
                        if (templateRedisClient.hasKey(key)){
                            //存在 将redis数据删除
                            staffResponse = templateRedisClient.get(key);
                            templateRedisClient.delete(key);
                        }else {
                            //redis不存在 将数据库查询到的数据返回
                            BeanUtils.copyProperties(baseStaff,staffResponse);
                        }
                        //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                        token = UUID.randomUUID().toString();
                        staffResponse.setToken(token);
                        //查询当前登录员工的菜单权限
                        staffResponse = this.getAuth(staffResponse);
                        //将登陆用户数据放入redis中
                        templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
                        WWQ=true;
                        break;
                    }
                }
                if(!WWQ){
                    throw new SmsException(ResponseCode.ACCOUNT_OR_PW_ERROR);
                }
            }
            return staffResponse;
        }
    }

    @Override
    public StaffResponse phonePassLoginNew(StaffRequest staffRequest) throws SmsException {
        Integer number = (Integer) redisUtils.getRedis(Constant.loginstaffKey+staffRequest.getMobilePhone());
        Long id =  getId();
        StaffLoginRecording staffLoginRecording = new StaffLoginRecording();
        staffLoginRecording.setMobilePhone(staffRequest.getMobilePhone());
        staffLoginRecording.setLoginTime(new Date());
        staffLoginRecording.setId(id);
        staffLoginRecording.setLoginType(0);
        staffLoginRecording.setState(1);
        staffLoginRecordingDao.save(staffLoginRecording);
//        if(number!=null && number>3){
//            throw new SmsException(ResponseCode.MSG,"登录失败次数过多，账号已锁定24小时");
//        }
        StaffResponse staffResponse = new StaffResponse();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String token = "";
        String password = null;
        String mobilePhone = null;
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone().trim()).trim());
        System.out.println(baseStaff.getMobilePhone());
        baseStaff.setPassword(AESUtils.encrypt(staffRequest.getPassword().trim()).trim());
        //如果想再扩大功能，支持一个人同一个手机号码同一个密码，那就将下面的selectOne改为select,再进行多组织的处理
        List<BaseStaff> selects = dao.select(baseStaff);
        if(selects.size()==0){
            if(number==null){
                number = 1;
            }else {
                number++;
            }
            staffLoginRecording.setState(1);
            staffLoginRecording.setMassage("账户或者密码不正确");
            staffLoginRecordingDao.updateById(staffLoginRecording);
            redisUtils.setRedis(Constant.loginstaffKey+staffRequest.getMobilePhone(),number,RedisClient.EXPIRE_TIME_ONE_DAY,TimeUnit.SECONDS);
            throw new SmsException(ResponseCode.MSG,"账户或者密码不正确");
        }
        //存在2组织
        if(selects.size()>1){
            List<BaseStore> stores = new ArrayList<>();
            int i=0;
            for (BaseStaff select : selects) {
                BaseStore baseStore = new BaseStore();
                baseStore.setId(select.getStoreId());
                BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
                stores.add(baseStore1);
                //判断是否是总店，总店的话再查询是否有关联分店
                if(null == baseStore1.getParentId()){
                    //总店
                    //先返回角色关联的门店
                    if(null == selects.get(i).getRoleId()){
                        throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                    }

                    if(selects.get(i).getRoleNum().equals("root")){
                        //超管
                        StoreRequest storeRequest = new StoreRequest();
                        storeRequest.setId(selects.get(i).getStoreId());
                        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);

                        for (BaseStores pagesorganization : pagesorganizations) {
                            if(pagesorganization.getState()==1&&pagesorganization.getId().hashCode()!=select.getStoreId().hashCode()){
                                BaseStore baseStore2 = new BaseStore();
                                BeanUtils.copyProperties(pagesorganization,baseStore2);
                                stores.add(baseStore2);
                            }
                        }
                    }else{
                        SysRoleStore sysRoleStore = new SysRoleStore();
                        sysRoleStore.setRoleId(selects.get(i).getRoleId());
                        List<SysRoleStore> select1 = ssmSysRoleStoreService.select(sysRoleStore);
                        for (SysRoleStore roleStore : select1) {
                            BaseStore baseStore2 = new BaseStore();
                            baseStore2.setId(roleStore.getStoreId());
                            BaseStore baseStore3 = ssmBaseStoreService.selectByPrimaryKey(baseStore2.getId());
                            if(baseStore3.getState()==1&&roleStore.getStoreId().hashCode()!=select.getStoreId().hashCode()){
                                stores.add(baseStore3);
                            }

                        }
                    }
                }
                i++;
            }
            //去掉重复门店
            stores=stores.stream().distinct().collect(Collectors.toList());
            staffResponse.setBaseStores(stores);
            staffResponse.setStoreType(1);
        }
        else{
            BaseStaff select = selects.get(0);
            if(null != select){
                if(select.getPassword().equals(AESUtils.encrypt(staffRequest.getPassword().trim()).trim())){
                    //单条处理 判断是否总店
                    BaseStore baseStore = new BaseStore();
                    baseStore.setId(select.getStoreId());
                    BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
                    if(null == baseStore1.getParentId()){
                        //总店
                        //先返回角色关联的门店
                        if(null == select.getRoleId()){
                            throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                        }
                        if(select.getRoleNum().equals("root")){
                            //超管
                            StoreRequest storeRequest = new StoreRequest();
                            storeRequest.setId(select.getStoreId());
                            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                            List<BaseStore> stores = new ArrayList<>();
                            for (BaseStores pagesorganization : pagesorganizations) {
                                if(pagesorganization.getState()==1){
                                    BaseStore baseStore2 = new BaseStore();
                                    BeanUtils.copyProperties(pagesorganization,baseStore2);
                                    stores.add(baseStore2);
                                }
                            }
                            staffResponse.setBaseStores(stores);
                        }else{
                            SysRoleStore sysRoleStore = new SysRoleStore();
                            sysRoleStore.setRoleId(select.getRoleId());
                            List<SysRoleStore> select1 = ssmSysRoleStoreService.select(sysRoleStore);
                            List<BaseStore> stores = new ArrayList<>();
                            for (SysRoleStore roleStore : select1) {
                                BaseStore baseStore2 = new BaseStore();
                                baseStore2.setId(roleStore.getStoreId());
                                BaseStore baseStore3 = ssmBaseStoreService.selectByPrimaryKey(baseStore2.getId());
                                if(baseStore3.getState()==1){
                                    stores.add(baseStore3);
                                }

                            }
                            staffResponse.setBaseStores(stores);
                        }


                        staffResponse.setStoreType(1);
                    }
                    else{
                        //分店
                        //校验门店是否有效
                        if(baseStore1.getState()==1 || new Date().before(baseStore1.getEndDate())) {
                            //门店没有异常
                            //获取redis key值
                            String key = getKey(staffRequest.getMobilePhone());
                            //从redis查询
                            if (templateRedisClient.hasKey(key)){
                                //存在 将redis数据删除
                                staffResponse = templateRedisClient.get(key);
                                templateRedisClient.delete(key);
                            }else {
                                //redis不存在 将数据库查询到的数据返回
                                BeanUtils.copyProperties(select,staffResponse);
                            }
                            //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                            token = UUID.randomUUID().toString();
                            staffResponse.setToken(token);
                            //查询当前登录员工的菜单权限
                            staffResponse.setStoreNum(baseStore1.getStoreNum());
                            if(null != baseStore1.getParentId()){
                                staffResponse.setParentId(baseStore1.getParentId());
                            }
                            if(null == select.getRoleId()){
                                throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                            }
                            staffResponse = this.getAuthNew(staffResponse);
                            //将登陆用户数据放入redis中
                            templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY,TimeUnit.SECONDS);
                            staffResponse.setStoreType(2);
                        }else{
                            throw new SmsException(ResponseCode.MSG,"该员工的所在门店非有效状态，请检查是否停用或者已经到期");
                        }
                    }
                }else{
                    throw new SmsException(ResponseCode.MSG,"密码错误");
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"没有找到该员工的有效信息，请检查是否存在或者是否停用");
            }
        }
        List<BaseStore> baseStores = staffResponse.getBaseStores();
        List<String> collect = baseStores.stream().filter(item->item.getStoreNum()!=null).map(BaseStore::getStoreNum).collect(Collectors.toList());
        String [] objects = collect.toArray(new String[collect.size()]);
        Arrays.sort(objects,String.CASE_INSENSITIVE_ORDER);
        HashSet<String> hashSet = new HashSet<>();
        List<BaseStore> baseStores1 = new ArrayList<>();
        for (int i = 0; i < objects.length; i++) {
            if(hashSet.add(objects[i])){
                for (BaseStore baseStore : baseStores) {
                    if(objects[i].equals(baseStore.getStoreNum())){
                        baseStores1.add(baseStore);
                    }
                }
            }
        }
        staffLoginRecording.setState(0);
        staffLoginRecording.setStaffId(selects.get(0).getId());
        staffLoginRecording.setStaffName(selects.get(0).getStaffName());
        staffLoginRecording.setMassage("登录成功");
        staffLoginRecordingDao.updateById(staffLoginRecording);
        staffResponse.setBaseStores(baseStores1);
        return staffResponse;
    }

    @Override
    public StaffResponse phonePassLoginNews(StaffRequest staffRequest) throws SmsException {

        StaffResponse staffResponse = new StaffResponse();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String token = "";
        String password = null;
        String mobilePhone = null;
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone().trim()).trim());
        baseStaff.setPassword(AESUtils.encrypt(staffRequest.getPassword().trim()).trim());
        //如果想再扩大功能，支持一个人同一个手机号码同一个密码，那就将下面的selectOne改为select,再进行多组织的处理
        List<BaseStaff> selects = dao.select(baseStaff);
        if(null != selects || selects.size()>0){
            BaseStaff select = new BaseStaff();
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(staffRequest.getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            for (BaseStores pagesorganization : pagesorganizations) {
                for (BaseStaff select1 : selects) {
                    if(select1.getStoreId().compareTo(pagesorganization.getId())==0 || select1.getStoreId().equals(pagesorganization.getId())){
                        select=select1;
                        break;
                    }
                }
            }

            //单条处理 判断是否总店
            BaseStore baseStore = new BaseStore();
            baseStore.setId(staffRequest.getStoreId());
//            baseStore.setId(Long.valueOf("227966281507823616"));
            BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
            if(baseStore1.getState()==1 || new Date().before(baseStore1.getEndDate())) {
                //门店没有异常
                //获取redis key值
                String key = getKey(staffRequest.getMobilePhone());
                //从redis查询
                if (templateRedisClient.hasKey(key)){
                    //存在 将redis数据删除
                    staffResponse = templateRedisClient.get(key);
                    templateRedisClient.delete(key);
                }else {
                    //redis不存在 将数据库查询到的数据返回
                    BeanUtils.copyProperties(select,staffResponse);
                }
                //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                token = UUID.randomUUID().toString();
                staffResponse.setToken(token);
                //查询当前登录员工的菜单权限
                staffResponse.setStoreNum(baseStore1.getStoreNum());
                if(null != baseStore1.getParentId()){
                    staffResponse.setParentId(baseStore1.getParentId());
                }
                if(null == select.getRoleId()){
                    throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                }
                staffResponse.setStoreId(baseStore1.getId());
                staffResponse.setStoreNum(baseStore1.getStoreNum());
                staffResponse.setStoreName(baseStore1.getStoreName());
//                staffResponse = this.getAuthByManyRole(staffResponse);
                staffResponse = this.getAuthNew(staffResponse);
                //将登陆用户数据放入redis中
                templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY, TimeUnit.SECONDS);
                staffResponse.setStoreType(2);
            }else{
                throw new SmsException(ResponseCode.MSG,"该员工的所在门店非有效状态，请检查是否停用或者已经到期");
            }
        }else{

        }
        return staffResponse;
    }

    //新--动态密码登录
    public boolean DynamicphonePassLoginNews(StaffRequest staffRequest) throws SmsException {
        BaseStore baseStoreMsg=ssmBaseStoreService.selectByPrimaryKey(staffRequest.getStoreId());//获取登录门店动态密码信息
        //获取redis key值
        String DynamicPsw = getPasscodeKey(baseStoreMsg.getStoreNum()+baseStoreMsg.getDynamicPswPhone());
        if(DynamicPsw.trim().length()<=0){//判断动态密码是否为空
            throw new SmsException(ResponseCode.MSG,"动态密码已过期，请重新获取");
        }else{
            if((staffRequest.getDynamicPsw().trim().hashCode()==templateRedisClient.get(DynamicPsw).getPassCode().trim().hashCode())
                    ||(staffRequest.getDynamicPsw().trim().equals(templateRedisClient.get(DynamicPsw).getPassCode().trim()))){//判断动态密码是否正确
                return true;
            }else{
                throw new SmsException(ResponseCode.MSG,"动态错误，请重新输入");
            }
        }
    }

    @Override
    public StaffResponse phonePassLogindzz(StaffRequest staffRequest) throws SmsException {
        StaffResponse staffResponse = new StaffResponse();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String token = "";
        String password = null;
        String mobilePhone = null;
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone().trim()).trim());
        baseStaff.setPassword(AESUtils.encrypt(staffRequest.getPassword().trim()).trim());
        baseStaff.setStoreId(staffRequest.getStoreId());
        //如果想再扩大功能，支持一个人同一个手机号码同一个密码，那就将下面的selectOne改为select,再进行多组织的处理
        BaseStaff select = dao.selectOne(baseStaff);
        if(null != select){
            if(select.getPassword().equals(AESUtils.encrypt(staffRequest.getPassword().trim()).trim())){
                //单条处理 判断是否总店
                BaseStore baseStore = new BaseStore();
                baseStore.setId(select.getStoreId());
                BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
                if(null == baseStore1.getParentId()){
                    //总店
                    //先返回角色关联的门店
                    if(null == select.getRoleId()){
                        throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                    }
                    if(select.getRoleNum().equals("root")){
                        //超管
                        StoreRequest storeRequest = new StoreRequest();
                        storeRequest.setId(select.getStoreId());
                        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                        List<BaseStore> stores = new ArrayList<>();
                        for (BaseStores pagesorganization : pagesorganizations) {
                            if(pagesorganization.getState()==1){
                                BaseStore baseStore2 = new BaseStore();
                                BeanUtils.copyProperties(pagesorganization,baseStore2);
                                stores.add(baseStore2);
                            }

                        }
                        staffResponse.setBaseStores(stores);
                    }else{
                        SysRoleStore sysRoleStore = new SysRoleStore();
                        sysRoleStore.setRoleId(select.getRoleId());
                        List<SysRoleStore> select1 = ssmSysRoleStoreService.select(sysRoleStore);
                        List<BaseStore> stores = new ArrayList<>();
                        for (SysRoleStore roleStore : select1) {
                            BaseStore baseStore2 = new BaseStore();
                            baseStore2.setId(roleStore.getStoreId());
                            BaseStore baseStore3 = ssmBaseStoreService.selectByPrimaryKey(baseStore2.getId());
                            if(baseStore3.getState()==1){
                                stores.add(baseStore3);
                            }

                        }
                        staffResponse.setBaseStores(stores);
                    }
                    staffResponse.setStoreType(1);
                }else{
                    //分店
                    //校验门店是否有效
                    if(baseStore1.getState()==1 || new Date().before(baseStore1.getEndDate())) {
                        //门店没有异常
                        //获取redis key值
                        String key = getKey(staffRequest.getMobilePhone());
                        //从redis查询
                        if (templateRedisClient.hasKey(key)){
                            //存在 将redis数据删除
                            staffResponse = templateRedisClient.get(key);
                            templateRedisClient.delete(key);
                        }else {
                            //redis不存在 将数据库查询到的数据返回
                            BeanUtils.copyProperties(select,staffResponse);
                        }
                        //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                        token = UUID.randomUUID().toString();
                        staffResponse.setToken(token);
                        //查询当前登录员工的菜单权限
                        staffResponse.setStoreNum(baseStore1.getStoreNum());
                        if(null != baseStore1.getParentId()){
                            staffResponse.setParentId(baseStore1.getParentId());
                        }
                        if(null == select.getRoleId()){
                            throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                        }
                        staffResponse = this.getAuthNew(staffResponse);
                        //将登陆用户数据放入redis中
                        templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
                        staffResponse.setStoreType(2);
                    }else{
                        throw new SmsException(ResponseCode.MSG,"该员工的所在门店非有效状态，请检查是否停用或者已经到期");
                    }
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"密码错误");
            }
        }else{
            throw new SmsException(ResponseCode.MSG,"没有找到该员工的有效信息，请检查是否存在或者是否停用");
        }
        return staffResponse;
    }

    @Override
    public StaffResponse phonePassLoginzd(StaffRequest staffRequest) throws SmsException {
        BaseStaff baseStaff = new BaseStaff();
        BaseStaff baseStaffs = new BaseStaff();
        BaseStaff baseStaff1 = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
        baseStaff.setStoreId(staffRequest.getReason());
        StaffResponse staffResponse = new StaffResponse();
        String token = "";
        String password = null;
        try {
            password = AESUtils.encrypt(staffRequest.getPassword());
        } catch (Exception e) {
            throw new SmsException(ResponseCode.DECRYPT_FAILED);
        }

        //校验总店的id
        Long store = null;

        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(staffRequest.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                BaseStore baseStoreLogin = ssmBaseStoreService.selectByPrimaryKey(staffRequest.getStoreId());
                store=pagesorganization.getId();
                if(pagesorganization.getId().equals(baseStoreLogin.getParentId())){
                    break;
                }


            }
        }
        //查询数据库
        baseStaff.setStoreId(store);
        baseStaff1 = dao.selectOne(baseStaff);
        if (baseStaff1 == null){
            throw new SmsException(ResponseCode.NO_USER);
        }else {
            //baseStaff.setStoreId(staffRequest.getStoreId());
            baseStaff.setStoreId(store);
            baseStaffs = dao.selectOne(baseStaff);
            if(baseStaffs.getType()==0){
                //校验门店
                BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(baseStaffs.getStoreId());
                if (baseStore.getState() != 1){
                    throw new SmsException(ResponseCode.STORE_IS_STOPED);
                }
                //获取redis key值
                String key = getKey(staffRequest.getMobilePhone());
                //对比密码是否一致
                if(baseStaff1.getState()==1|| baseStaff1.getState()==2){
                    if (password.equals(baseStaff1.getPassword())){
                        BaseStore baseStoreLogin = ssmBaseStoreService.selectByPrimaryKey(staffRequest.getStoreId());
                        if(!new Date().before(baseStoreLogin.getEndDate())){
                            throw new SmsException(ResponseCode.MSG,"门店有效期已过期");
                        }
                        baseStaffs.setStoreId(baseStoreLogin.getId());
                        baseStaffs.setStoreName(baseStoreLogin.getStoreName());

                        //从redis查询
                        if (templateRedisClient.hasKey(key)){
                            //存在 将redis数据删除
                            staffResponse = templateRedisClient.get(key);
                            templateRedisClient.delete(key);
                        }else {
                            //redis不存在 将数据库查询到的数据返回
                            BeanUtils.copyProperties(baseStaffs,staffResponse);
                        }
                        //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                        token = UUID.randomUUID().toString();
                        staffResponse.setToken(token);
                        //查询当前登录员工的菜单权限
                        staffResponse = this.getAuth(staffResponse);
                        //将登陆用户数据放入redis中
                        templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
                    }else {
                        throw  new SmsException(ResponseCode.ACCOUNT_OR_PW_ERROR);
                    }

                    return staffResponse;
                }else{
                    throw  new SmsException(ResponseCode.MSG,"员工已经停用或者离职");
                }

            }if(baseStaffs.getType()==2) { //收银员
                if(!store.equals(staffRequest.getStoreId())){
                    BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(baseStaffs.getStoreId());
                    if (baseStore.getState() != 1){
                        throw new SmsException(ResponseCode.STORE_IS_STOPED);
                    }
                    //获取redis key值
                    String key = getKey(staffRequest.getMobilePhone());
                    //对比密码是否一致
                    if (password.equals(baseStaff1.getPassword())){
                        BaseStore baseStoreLogin = ssmBaseStoreService.selectByPrimaryKey(staffRequest.getStoreId());
                        baseStaffs.setStoreId(baseStoreLogin.getId());
                        baseStaffs.setStoreName(baseStoreLogin.getStoreName());

                        //从redis查询
                        if (templateRedisClient.hasKey(key)){
                            //存在 将redis数据删除
                            staffResponse = templateRedisClient.get(key);
                            templateRedisClient.delete(key);
                        }else {
                            //redis不存在 将数据库查询到的数据返回
                            BeanUtils.copyProperties(baseStaffs,staffResponse);
                        }
                        //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                        token = UUID.randomUUID().toString();
                        staffResponse.setToken(token);
                        //查询当前登录员工的菜单权限
                        staffResponse = this.getAuth(staffResponse);
                        //将登陆用户数据放入redis中
                        templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
                    }else {
                        throw  new SmsException(ResponseCode.ACCOUNT_OR_PW_ERROR);
                    }

                    return staffResponse;
                }else{
                    throw  new SmsException(ResponseCode.DATA_NOT_ALLOW_UPDATESSSS,"该用户是总店收银员，不能登录总店");
                }
            }else{
                throw  new SmsException(ResponseCode.DATA_NOT_ALLOW_UPDATESSSS,"该用户不是总店管理员，不能使用总店登录功能");
            }
        }

    }

    @Override
    public void logout(StaffRequest staffRequest, HttpSession session) throws SmsException {
        //清除redis
        if (templateRedisClient.hasKey(getKey(staffRequest.getMobilePhone()))){
            templateRedisClient.delete(getKey(staffRequest.getMobilePhone()));
        }
        //清除session
        session.invalidate();
    }

    @Override
    public void uniLogout(StaffRequest staffRequest) throws SmsException {
        //清除redis
        String key = getKey(staffRequest.getMobilePhone());
        Set<String> s =  templateRedisClient.keys(key + "*");
        if (s.size() > 0){
            //存在 将redis数据删除
            templateRedisClient.delete(s);
        }
    }

    @Override
    public StaffResponse uniPhoneLogin(StaffRequest staffRequest) throws SmsException {
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
        baseStaff.setStoreId(staffRequest.getStoreId());
        //查询数据库
        baseStaff = dao.selectOne(baseStaff);
        if (baseStaff == null){
            throw new SmsException(ResponseCode.NO_USER);
        }else {
            //校验门店
            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(baseStaff.getStoreId());
            if (baseStore.getState() == 0){
                throw new SmsException(ResponseCode.STORE_IS_STOPED);
            }
        }
        //获取redis codeKey值
        String codeKey = getPasscodeKey(staffRequest.getMobilePhone());

        StaffResponse staffResponse = new StaffResponse();
        String token = "";
        String passCode = staffRequest.getPassCode();
        //从redis查询
        if (templateRedisClient.hasKey(codeKey)){
            //校验验证码
            if (passCode.equals(templateRedisClient.get(codeKey).getPassCode())) {
                //存在 将redis数据删除 重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                token = UUID.randomUUID().toString();
                BeanUtils.copyProperties(baseStaff,staffResponse);
                staffResponse.setToken(token);
                //查询当前登录员工的菜单权限
                staffResponse = this.getAuth(staffResponse);
                String key = getKey(staffRequest.getMobilePhone()) + token;
                templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);

            }
        }else {
            //redis不存在 验证码已过期
            throw new SmsException(ResponseCode.SMS_CODE_IS_OVER);
        }
        return staffResponse;
    }

    @Override
    public StaffResponse uniPhonePassLogin(StaffRequest staffRequest) throws SmsException {
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
        baseStaff.setStoreId(staffRequest.getStoreId());
        StaffResponse staffResponse = new StaffResponse();
        String token = "";
        String password = null;
        try {
            password = AESUtils.encrypt(staffRequest.getPassword());
        } catch (Exception e) {
            throw new SmsException(ResponseCode.DECRYPT_FAILED);
        }
        //查询数据库
        baseStaff = dao.selectOne(baseStaff);
        if (baseStaff == null){
            throw new SmsException(ResponseCode.NO_USER);
        }else {
            //校验门店
            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(baseStaff.getStoreId());
            if (baseStore.getState() == 0){
                throw new SmsException(ResponseCode.STORE_IS_STOPED);
            }
            //获取redis key值
            String key = getKey(staffRequest.getMobilePhone());
            //对比密码是否一致
            //System.out.println(baseStaff.getPassword());
            if (password.equals(baseStaff.getPassword())){

                Set<String> keys = templateRedisClient.keys(key + "*");
                //从redis查询
                if (keys.size() > 0){
                    //存在 将redis数据删除
                    templateRedisClient.delete(keys);
                }
                //redis不存在 将数据库查询到的数据返回
                BeanUtils.copyProperties(baseStaff, staffResponse);

                //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                token = UUID.randomUUID().toString();
                staffResponse.setToken(token);
                //查询当前登录员工的菜单权限
                staffResponse = this.getAuth(staffResponse);
                key = key + token;
                //将登陆用户数据放入redis中
                templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
            }else {
                throw  new SmsException(ResponseCode.ACCOUNT_OR_PW_ERROR);
            }
        }
        return staffResponse;
    }


    @Override
    public List<BaseStaff> list(StaffRequest staffRequest) {
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));
        if(StringUtils.isNotBlank(staffRequest.getStoreName())){
            baseStaff.setStoreName(staffRequest.getStoreName());
        }
        if(StringUtils.isNotBlank(String.valueOf(staffRequest.getStoreId()))){
            baseStaff.setStoreId(staffRequest.getStoreId());
        }
        //查询数据库
        List<BaseStaff> list = dao.select(baseStaff);
        return list;
    }

    @Override
    public List<StaffRequest> listlogin(StaffRequest staffRequest) {
        staffRequest.setState(1);
        staffRequest.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone()));

        //查询数据库
        List<StaffRequest> list = dao.liststarfall(staffRequest);
        return list;
    }

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

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

    public StaffResponse getAuth(StaffResponse staffResponse) throws SmsException {
        if("19216831409".trim().equals(staffResponse.getMobilePhone().trim())){
            List<SysMenuPower> sysMenuPowers = ssmSysMenuPowerService.selectAll();
            staffResponse.setList(sysMenuPowers);
            return  staffResponse;
        }else{
            //获取员工角色信息
            Long roleId = Long.parseLong(staffResponse.getRoleNum());
            //查询角色权限表
            Example rolePowerExample = new Example(SysRolePower.class);
            rolePowerExample.createCriteria().andEqualTo("roleId",roleId);
            List<SysRolePower> rolePowerList = ssmSysRolePowerService.selectByExample(rolePowerExample);
            if (null == rolePowerList && rolePowerList.size() == 0){
                throw new SmsException(ResponseCode.NO_PERMISSIONS);
            }
            //将权限ID提取出来
            List<Integer> powerIds = new ArrayList<>(rolePowerList.size());
            for (SysRolePower sysRolePower : rolePowerList){
                powerIds.add(sysRolePower.getPowerId());
            }
            //查询权限表
            Example powerExample = new Example(SysMenuPower.class);
            powerExample.createCriteria().andIn("id",powerIds);
            List<SysMenuPower> list = ssmSysMenuPowerService.selectByExample(powerExample);
            staffResponse.setList(list);
            return  staffResponse;
        }

    }


//    public StaffResponse getAuthNew(StaffResponse staffResponse) throws SmsException {
//        Long roleId = staffResponse.getRoleId();
//        SysStoreRole sysStoreRole = ssmSysStoreRoleService.selectByPrimaryKey(roleId);
//        if(sysStoreRole.getState()==0){
//            throw new SmsException(ResponseCode.MSG,"该用户关联的角色已经停用");
//        }
//        if(staffResponse.getRoleNum().equals("root")){
//            List<SysMenuPower> sysMenuPowers = ssmSysMenuPowerService.selectAll();
//            staffResponse.setList(sysMenuPowers);
//            return  staffResponse;
//        }else{
//            //查询角色权限表
//            Example rolePowerExample = new Example(SysMuenRole.class);
//            rolePowerExample.createCriteria().andEqualTo("roleId",roleId);
//            List<SysMuenRole> rolePowerList = ssmSysMuenRoleService.selectByExample(rolePowerExample);
//            if (null == rolePowerList && rolePowerList.size() == 0){
//                throw new SmsException(ResponseCode.NO_PERMISSIONS);
//            }
//            //将权限ID提取出来
//            List<Integer> powerIds = new ArrayList<>(rolePowerList.size());
//            for (SysMuenRole sysRolePower : rolePowerList){
//                powerIds.add(sysRolePower.getPowerId());
//            }
//            try{
//                //查询权限表
//                Example powerExample = new Example(SysMenuPower.class);
//                powerExample.createCriteria().andIn("id",powerIds).andEqualTo("state",0);
//                List<SysMenuPower> list = ssmSysMenuPowerService.selectByExample(powerExample);
//                staffResponse.setList(list);
//            }catch (Exception e){
//                throw new SmsException(ResponseCode.MSG,"获取角色权限异常，请检查管理员是否未赋予角色权限");
//            }
//
//            return  staffResponse;
//        }
//    }

@Autowired
private RlRoleStaffDao rlRoleStaffDao;
//    public StaffResponse getAuthByManyRole(StaffResponse staffResponse) throws SmsException {
    public StaffResponse getAuthNew(StaffResponse staffResponse) throws SmsException {
        RlRoleStaff rlRoleStaff = new RlRoleStaff();
         rlRoleStaff.setStaffId(staffResponse.getId());
        List<RlRoleStaff> rlRoleStaffs = rlRoleStaffDao.select(rlRoleStaff);
        for (RlRoleStaff roleStaff : rlRoleStaffs) {
        Long roleId = roleStaff.getRoleId();
        SysStoreRole sysStoreRole = ssmSysStoreRoleService.selectByPrimaryKey(roleId);
        if(sysStoreRole.getState()==0){
            throw new SmsException(ResponseCode.MSG,"该用户关联的角色已经停用");
        }
        if(sysStoreRole.getRoleNum().equals("root")){
            List<SysMenuPower> sysMenuPowers = ssmSysMenuPowerService.selectAll();
            staffResponse.setList(sysMenuPowers);
            return  staffResponse;
        }else{
            //查询角色权限表
            Example rolePowerExample = new Example(SysMuenRole.class);
            rolePowerExample.createCriteria().andEqualTo("roleId",roleId);
            List<SysMuenRole> rolePowerList = ssmSysMuenRoleService.selectByExample(rolePowerExample);
            if (null == rolePowerList && rolePowerList.size() == 0){
                continue;
//                throw new SmsException(ResponseCode.NO_PERMISSIONS);
            }
            //将权限ID提取出来
            List<Integer> powerIds = new ArrayList<>(rolePowerList.size());
            for (SysMuenRole sysRolePower : rolePowerList){
                powerIds.add(sysRolePower.getPowerId());
            }
            try{
                //查询权限表
                Example powerExample = new Example(SysMenuPower.class);
                powerExample.createCriteria().andIn("id",powerIds).andEqualTo("state",0);
                List<SysMenuPower> list = ssmSysMenuPowerService.selectByExample(powerExample);
                List<SysMenuPower> sysMenuPowerList = staffResponse.getList()==null?new ArrayList<>():staffResponse.getList();
                sysMenuPowerList.addAll(list);
                staffResponse.setList(sysMenuPowerList);
            }catch (Exception e){
                throw new SmsException(ResponseCode.MSG,"获取角色权限异常，请检查管理员是否未赋予角色权限");
            }
        }
        }
        List<SysMenuPower> list = staffResponse.getList();
        Set<SysMenuPower> set = new HashSet<>();
        for (SysMenuPower sysMenuPower : list) {
            if (set.contains(sysMenuPower)) {
                continue;
            }
            set.add(sysMenuPower);
        }
        List<SysMenuPower> collect = set.stream().map(item -> item).collect(Collectors.toList());
        staffResponse.setList(collect);
        return  staffResponse;
    }
    /**
     * 暂时还有大问题
     * @param staffRequest
     * @return
     * @throws SmsException
     */
    @Override
    public StaffResponse phoneLoginNew(StaffRequest staffRequest) throws SmsException {
        Integer number = (Integer) redisUtils.getRedis(Constant.loginstaffKey+staffRequest.getMobilePhone());
        Long id =  getId();
        StaffLoginRecording staffLoginRecording = new StaffLoginRecording();
        staffLoginRecording.setMobilePhone(staffRequest.getMobilePhone());
        staffLoginRecording.setLoginTime(new Date());
        staffLoginRecording.setId(id);
        staffLoginRecording.setLoginType(1);
        staffLoginRecording.setState(1);
        staffLoginRecordingDao.save(staffLoginRecording);
        if(number!=null && number>3){
            staffLoginRecording.setMassage("登录失败次数过多，账号已锁定24小时");
            staffLoginRecordingDao.updateById(staffLoginRecording);
            throw new SmsException(ResponseCode.MSG,"登录失败次数过多，账号已锁定24小时");
        }
        StaffResponse staffResponse = new StaffResponse();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String token = "";
        String password = null;
        String mobilePhone = null;
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone().trim()).trim());
        //如果想再扩大功能，支持一个人同一个手机号码同一个密码，那就将下面的selectOne改为select,再进行多组织的处理
        List<BaseStaff> selects = dao.select(baseStaff);
        if (selects.size() == 0) {
            if(number==null){
                number = 1;
            }else {
                number++;
            }
            staffLoginRecording.setState(1);
            staffLoginRecording.setMassage("账户或者密码不正确");
            staffLoginRecordingDao.updateById(staffLoginRecording);
            redisUtils.setRedis(Constant.loginstaffKey+staffRequest.getMobilePhone(),number,RedisClient.EXPIRE_TIME_ONE_DAY,TimeUnit.SECONDS);
            throw new SmsException(ResponseCode.MSG, "账户或者密码不正确");
        }
        //存在2组织
        if (selects.size() > 1) {
            //if(staffRequest.getPassword()==null){
                String codeKey = getPasscodeKey(staffRequest.getMobilePhone());
                String passCode = staffRequest.getPassCode();
                if (templateRedisClient.get(codeKey)!=null&&passCode.equals(templateRedisClient.get(codeKey).getPassCode())) {//验证
                    List<BaseStore> stores = new ArrayList<>();
                    int i=0;
                    for (BaseStaff select : selects) {
                        BaseStore baseStore = new BaseStore();
                        baseStore.setId(select.getStoreId());
                        BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
                        stores.add(baseStore1);
                        //判断是否是总店，总店的话再查询是否有关联分店
                        if(null == baseStore1.getParentId()){
                            //总店
                            //先返回角色关联的门店
                            if(null == selects.get(i).getRoleId()){
                                throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                            }

                            if(selects.get(i).getRoleNum().equals("root")){
                                //超管
                                StoreRequest storeRequest = new StoreRequest();
                                storeRequest.setId(selects.get(i).getStoreId());
                                List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                                for (BaseStores pagesorganization : pagesorganizations) {
                                    if(pagesorganization.getState()==1&&pagesorganization.getId().hashCode()!=select.getStoreId().hashCode()){
                                        BaseStore baseStore2 = new BaseStore();
                                        BeanUtils.copyProperties(pagesorganization,baseStore2);
                                        stores.add(baseStore2);
                                    }
                                }
                            }else{
                                SysRoleStore sysRoleStore = new SysRoleStore();
                                sysRoleStore.setRoleId(selects.get(i).getRoleId());
                                List<SysRoleStore> select1 = ssmSysRoleStoreService.select(sysRoleStore);
                                for (SysRoleStore roleStore : select1) {
                                    BaseStore baseStore2 = new BaseStore();
                                    baseStore2.setId(roleStore.getStoreId());
                                    BaseStore baseStore3 = ssmBaseStoreService.selectByPrimaryKey(baseStore2.getId());
                                    if(baseStore3.getState()==1&&roleStore.getStoreId().hashCode()!=select.getStoreId().hashCode()){
                                        stores.add(baseStore3);
                                    }

                                }
                            }
                        }
                        i++;
                    }
                    staffResponse.setBaseStores(stores);
                    staffResponse.setStoreType(1);
                }else {
                    throw new SmsException(ResponseCode.MSG, "验证码错误或者已经失效");
                }

           // }


        }
        else {
            BaseStaff select = selects.get(0);
            if (null != select) {
                String codeKey = getPasscodeKey(staffRequest.getMobilePhone());
                String passCode = staffRequest.getPassCode();
                //单条处理 判断是否总店
                BaseStore baseStore = new BaseStore();
                baseStore.setId(select.getStoreId());
                BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
                if (null == baseStore1.getParentId()) {
                    //总店
                    //先返回角色关联的门店
                    if (null == select.getRoleId()) {
                        throw new SmsException(ResponseCode.MSG, "该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                    }
                    if (select.getRoleNum().equals("root")) {
                        //超管
                        StoreRequest storeRequest = new StoreRequest();
                        storeRequest.setId(select.getStoreId());
                        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                        List<BaseStore> stores = new ArrayList<>();
                        for (BaseStores pagesorganization : pagesorganizations) {
                            BaseStore baseStore2 = new BaseStore();
                            BeanUtils.copyProperties(pagesorganization, baseStore2);
                            stores.add(baseStore2);
                        }
                        staffResponse.setBaseStores(stores);
                    }
                    else
                        //if (staffRequest.getPassword()==null){
                        if (templateRedisClient.get(codeKey)!=null&&passCode.equals(templateRedisClient.get(codeKey).getPassCode())) {//验证
                            SysRoleStore sysRoleStore = new SysRoleStore();
                            sysRoleStore.setRoleId(select.getRoleId());
                            List<SysRoleStore> select1 = ssmSysRoleStoreService.select(sysRoleStore);
                            List<BaseStore> stores = new ArrayList<>();
                            for (SysRoleStore roleStore : select1) {
                                BaseStore baseStore2 = new BaseStore();
                                baseStore2.setId(roleStore.getStoreId());
                                BaseStore baseStore3 = ssmBaseStoreService.selectByPrimaryKey(baseStore2.getId());
                                stores.add(baseStore3);
                            }
                            staffResponse.setBaseStores(stores);
                        }else {
                            throw new SmsException(ResponseCode.MSG, "验证码错误或者已经失效");
                        }
                    //}
                    staffResponse.setStoreType(1);
                } else {
                    //分店
                    //校验门店是否有效
                    //从redis查询
                    if (templateRedisClient.hasKey(codeKey)){
                        //if(true){
                        //校验验证码
                        if (passCode.equals(templateRedisClient.get(codeKey).getPassCode())) {
                            //if(true){
                            //存在 将redis数据删除 重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                            if (baseStore1.getState() == 1 || new Date().before(baseStore1.getEndDate())) {
                                //门店没有异常
                                //获取redis key值
                                String key = getKey(staffRequest.getMobilePhone());
                                //从redis查询
                                if (templateRedisClient.hasKey(key)) {
                                    //存在 将redis数据删除
                                    staffResponse = templateRedisClient.get(key);
                                    templateRedisClient.delete(key);
                                } else {
                                    //redis不存在 将数据库查询到的数据返回
                                    BeanUtils.copyProperties(select, staffResponse);
                                }
                                //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                                token = UUID.randomUUID().toString();
                                staffResponse.setToken(token);
                                //查询当前登录员工的菜单权限
                                staffResponse.setStoreNum(baseStore1.getStoreNum());
                                if (null != baseStore1.getParentId()) {
                                    staffResponse.setParentId(baseStore1.getParentId());
                                }
                                if (null == select.getRoleId()) {
                                    throw new SmsException(ResponseCode.MSG, "该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                                }
                                staffResponse = this.getAuthNew(staffResponse);
                                //将登陆用户数据放入redis中
                                templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY,TimeUnit.SECONDS);
                                staffResponse.setStoreType(2);
                            } else {
                                throw new SmsException(ResponseCode.MSG, "该员工的所在门店非有效状态，请检查是否停用或者已经到期");
                            }
                        }else {
                            throw new SmsException(ResponseCode.MSG, "验证码错误或者已经失效");
                        }
                    }else {
                        //redis不存在 验证码已过期
                        throw new SmsException(ResponseCode.SMS_CODE_IS_OVER);
                    }
                }
            } else {
                throw new SmsException(ResponseCode.MSG, "没有找到该员工的有效信息，请检查是否存在或者是否停用");
            }
        }
        List<BaseStore> baseStores = staffResponse.getBaseStores();
        List<String> collect = baseStores.stream().filter(item->item.getStoreNum()!=null).map(BaseStore::getStoreNum).collect(Collectors.toList());
        String [] objects = collect.toArray(new String[collect.size()]);
        Arrays.sort(objects,String.CASE_INSENSITIVE_ORDER);
        HashSet<String> hashSet = new HashSet<>();
        List<BaseStore> baseStores1 = new ArrayList<>();
        for (int i = 0; i < objects.length; i++) {
            if(hashSet.add(objects[i])){
                for (BaseStore baseStore : baseStores) {
                    if(objects[i].equals(baseStore.getStoreNum())){
                        baseStores1.add(baseStore);
                    }
                }
            }
        }
        staffLoginRecording.setState(0);
        staffLoginRecording.setStaffId(selects.get(0).getId());
        staffLoginRecording.setStaffName(selects.get(0).getStaffName());
        staffLoginRecording.setMassage("登录成功");
        staffLoginRecordingDao.updateById(staffLoginRecording);
        staffResponse.setBaseStores(baseStores1);
        return staffResponse;
    }

    public boolean chekeMsg(MemberRequest memberRequest) throws SmsException {
        boolean i=false;
        //原密码修支付密码改验证
        if(!memberRequest.getCashPasswordnew1().trim().equals(memberRequest.getCashPasswordnew2().trim())){
            throw new SmsException(ResponseCode.MSG,"两次密码输入不一致");
        }
        StoreMemberList storeMemberList1 = null;
        if(memberRequest.getCashPassword()!=null){
            String chekPsw="";
            try {

                String phone=AESUtils.encrypt(memberRequest.getMobilePhone());
                StoreMemberList storeMemberList = new StoreMemberList();
                storeMemberList.setId(memberRequest.getId());
                storeMemberList.setMobilePhone(phone);
                memberRequest.setStoreId(memberRequest.getStoreId());
                storeMemberList1=ssmStoreMemberDao.selectOne(storeMemberList);
                 chekPsw=AESUtils.decrypt(storeMemberList1.getCashPassword());
            }catch (Exception e){
                e.printStackTrace();
            }

            if(storeMemberList1.getMemberNum().startsWith("S")){
                StoreParament gifCardPassword = StoreParaUtils.getStorePara(265309505575694336L, "gifCardPassword");
                if(memberRequest.getCashPassword().trim().equals(gifCardPassword.getParamentValue().trim()) || chekPsw.trim().equals(memberRequest.getCashPassword().trim())){
                    StoreMemberList storeMemberList = new StoreMemberList();
                    storeMemberList.setId(memberRequest.getId());
                    storeMemberList.setStoreId(memberRequest.getStoreId());
                    storeMemberList.setCashPassword(AESUtils.encrypt(memberRequest.getCashPasswordnew1()));
                    int b=ssmStoreMemberDao.updateByPrimaryKeySelective(storeMemberList);
                    if (b>0){
                        return true;
                    }
                }else {
                    throw new SmsException(ResponseCode.MSG,"密码错误");
                }
            }
            if(memberRequest.getCashPassword().trim().equals(chekPsw.trim())){
                if(memberRequest.getCashPasswordnew1()!=null&&memberRequest.getCashPasswordnew2()!=null&&!memberRequest.getCashPasswordnew1().trim().equals("")&&!memberRequest.getCashPasswordnew2().trim().equals("")){
                    if(memberRequest.getCashPasswordnew1().trim()==memberRequest.getCashPasswordnew2().trim()||memberRequest.getCashPasswordnew1().trim().equals(memberRequest.getCashPasswordnew2().trim())){
                        StoreMemberList storeMemberList = new StoreMemberList();
                        storeMemberList.setId(memberRequest.getId());
                        storeMemberList.setStoreId(memberRequest.getStoreId());
                        storeMemberList.setCashPassword(AESUtils.encrypt(memberRequest.getCashPasswordnew1()));
                        int b=ssmStoreMemberDao.updateByPrimaryKeySelective(storeMemberList);
                        if(b>0)
                             i=true;
                    }else{
                        throw new SmsException(ResponseCode.MSG,"输入得两次密码不一致");
                    }
                }else{
                    throw new SmsException(ResponseCode.MSG,"输入密码不能为空");
                }
            }else{
                throw new SmsException(ResponseCode.MSG, "输入密码错误");
            }

        }else if(memberRequest.getCodeMsg()!=null){//验证码修支付密码改验证
            //获取redis校验码的key
            String codeKey = getPasscodeKey(memberRequest.getMobilePhone());
            //验证
            if (memberRequest.getCodeMsg().trim().equals(templateRedisClient.get(codeKey).getPassCode().trim())) {

                if(memberRequest.getCashPasswordnew1()!=null&&memberRequest.getCashPasswordnew2()!=null&&!memberRequest.getCashPasswordnew1().trim().equals("")&&!memberRequest.getCashPasswordnew2().trim().equals("")){
                    if(memberRequest.getCashPasswordnew1().trim()==memberRequest.getCashPasswordnew2().trim()||memberRequest.getCashPasswordnew1().trim().equals(memberRequest.getCashPasswordnew2().trim())){
                        StoreMemberList storeMemberList = new StoreMemberList();
                        storeMemberList.setId(memberRequest.getId());
                        storeMemberList.setStoreId(memberRequest.getStoreId());
                        storeMemberList.setCashPassword(AESUtils.encrypt(memberRequest.getCashPasswordnew1()));
                        int b=ssmStoreMemberDao.updateByPrimaryKeySelective(storeMemberList);
                        if(b>0)
                             i=true;
                    }else{
                        throw new SmsException(ResponseCode.MSG,"输入得两次密码不一致");
                    }
                }else{
                    throw new SmsException(ResponseCode.MSG,"输入密码不能为空");
                }


            }else{
                throw new SmsException(ResponseCode.MSG, "验证码错误或者已经失效");
            }
        }else{
            throw new SmsException(ResponseCode.MSG, "验证码不能为空");
        }
        return i;
    }

    @Override
    public StaffResponse phoneLoginNewzz(StaffRequest staffRequest) throws SmsException {
        StaffResponse staffResponse = new StaffResponse();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String token = "";
        String password = null;
        String mobilePhone = null;
        String codeKey = getPasscodeKey(staffRequest.getMobilePhone());
        String passCode = staffRequest.getPassCode();
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone().trim()).trim());
        baseStaff.setStoreId(staffRequest.getStoreId());
        //如果想再扩大功能，支持一个人同一个手机号码同一个密码，那就将下面的selectOne改为select,再进行多组织的处理
        BaseStaff select = dao.selectOne(baseStaff);
        if(null != select){
            //单条处理 判断是否总店
            BaseStore baseStore = new BaseStore();
            baseStore.setId(select.getStoreId());
            BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
            if(null == baseStore1.getParentId()){
                //总店
                //先返回角色关联的门店
                if(null == select.getRoleId()){
                    throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                }
                if(select.getRoleNum().equals("root")){
                    //超管
                    StoreRequest storeRequest = new StoreRequest();
                    storeRequest.setId(select.getStoreId());
                    List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                    List<BaseStore> stores = new ArrayList<>();
                    for (BaseStores pagesorganization : pagesorganizations) {
                        BaseStore baseStore2 = new BaseStore();
                        BeanUtils.copyProperties(pagesorganization,baseStore2);
                        stores.add(baseStore2);
                    }
                    staffResponse.setBaseStores(stores);
                }else{
                    SysRoleStore sysRoleStore = new SysRoleStore();
                    sysRoleStore.setRoleId(select.getRoleId());
                    List<SysRoleStore> select1 = ssmSysRoleStoreService.select(sysRoleStore);
                    List<BaseStore> stores = new ArrayList<>();
                    for (SysRoleStore roleStore : select1) {
                        BaseStore baseStore2 = new BaseStore();
                        baseStore2.setId(roleStore.getStoreId());
                        BaseStore baseStore3 = ssmBaseStoreService.selectByPrimaryKey(baseStore2.getId());
                        stores.add(baseStore3);
                    }
                    staffResponse.setBaseStores(stores);
                }
                staffResponse.setStoreType(1);
            }else{
                if (templateRedisClient.hasKey(codeKey)){
                    //if(true){
                    //校验验证码
                    if (passCode.equals(templateRedisClient.get(codeKey).getPassCode())) {
                        //if(true){
                        //校验门店是否有效
                        if(baseStore1.getState()==1 || new Date().before(baseStore1.getEndDate())) {
                            //门店没有异常
                            //获取redis key值
                            String key = getKey(staffRequest.getMobilePhone());
                            //从redis查询
                            if (templateRedisClient.hasKey(key)){
                                //存在 将redis数据删除
                                staffResponse = templateRedisClient.get(key);
                                templateRedisClient.delete(key);
                            }else {
                                //redis不存在 将数据库查询到的数据返回
                                BeanUtils.copyProperties(select,staffResponse);
                            }
                            //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                            token = UUID.randomUUID().toString();
                            staffResponse.setToken(token);
                            //查询当前登录员工的菜单权限
                            staffResponse.setStoreNum(baseStore1.getStoreNum());
                            if(null != baseStore1.getParentId()){
                                staffResponse.setParentId(baseStore1.getParentId());
                            }
                            if(null == select.getRoleId()){
                                throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                            }
                            staffResponse = this.getAuthNew(staffResponse);
                            //将登陆用户数据放入redis中
                            templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
                            staffResponse.setStoreType(2);
                        }else{
                            throw new SmsException(ResponseCode.MSG,"该员工的所在门店非有效状态，请检查是否停用或者已经到期");
                        }
                    }else {
                        throw new SmsException(ResponseCode.MSG, "验证码错误或者已经失效");
                    }
                }else {
                    //redis不存在 验证码已过期
                    throw new SmsException(ResponseCode.SMS_CODE_IS_OVER);
                }

            }
        }else{
            throw new SmsException(ResponseCode.MSG,"没有找到该员工的有效信息，请检查是否存在或者是否停用");
        }
        return staffResponse;
    }

    @Override
    public StaffResponse phoneLoginNews(StaffRequest staffRequest) throws SmsException {
        StaffResponse staffResponse = new StaffResponse();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String token = "";
        String password = null;
        String mobilePhone = null;
        String codeKey = getPasscodeKey(staffRequest.getMobilePhone());
        String passCode = staffRequest.getPassCode();
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone().trim()).trim());
//        baseStaff.setPassword(AESUtils.encrypt(staffRequest.getPassword().trim()).trim());
        //如果想再扩大功能，支持一个人同一个手机号码同一个密码，那就将下面的selectOne改为select,再进行多组织的处理
        List<BaseStaff> selects = dao.select(baseStaff);
        if(null != selects || selects.size()>0){
            BaseStaff select = new BaseStaff();
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(staffRequest.getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            for (BaseStores pagesorganization : pagesorganizations) {
                for (BaseStaff select1 : selects) {
                    if(select1.getStoreId().equals(pagesorganization.getId())){
                        select=select1;
                        break;
                    }
                }
            }

            //单条处理 判断是否总店
            BaseStore baseStore = new BaseStore();
            baseStore.setId(staffRequest.getStoreId());
//            baseStore.setId(Long.valueOf("227966281507823616"));
            BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
            if (templateRedisClient.hasKey(codeKey)){
                //if(true){
                //校验验证码
                if (passCode.equals(templateRedisClient.get(codeKey).getPassCode())) {
                    //if(true){
                    if(baseStore1.getState()==1 || new Date().before(baseStore1.getEndDate())) {
                        //门店没有异常
                        //获取redis key值
                        String key = getKey(staffRequest.getMobilePhone());
                        //从redis查询
                        if (templateRedisClient.hasKey(key)){
                            //存在 将redis数据删除
                            staffResponse = templateRedisClient.get(key);
                            templateRedisClient.delete(key);
                        }else {
                            //redis不存在 将数据库查询到的数据返回
                            BeanUtils.copyProperties(select,staffResponse);
                        }
                        //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                        token = UUID.randomUUID().toString();
                        staffResponse.setToken(token);
                        //查询当前登录员工的菜单权限
                        staffResponse.setStoreNum(baseStore1.getStoreNum());
                        if(null != baseStore1.getParentId()){
                            staffResponse.setParentId(baseStore1.getParentId());
                        }
                        if(null == select.getRoleId()){
                            throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                        }
                        staffResponse.setStoreId(baseStore1.getId());
                        staffResponse.setStoreNum(baseStore1.getStoreNum());
                        staffResponse.setStoreName(baseStore1.getStoreName());
                        staffResponse = this.getAuthNew(staffResponse);
                        //将登陆用户数据放入redis中
                        templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
                        staffResponse.setStoreType(2);
                    }else{
                        throw new SmsException(ResponseCode.MSG,"该员工的所在门店非有效状态，请检查是否停用或者已经到期");
                    }
                }else {
                    throw new SmsException(ResponseCode.MSG, "验证码错误或者已经失效");
                }
            }else {
                //redis不存在 验证码已过期
                throw new SmsException(ResponseCode.SMS_CODE_IS_OVER);
            }

        }else{
            throw new SmsException(ResponseCode.MSG,"没有找到该员工的有效信息，请检查是否存在或者是否停用");
        }
        return staffResponse;
    }

    @Override
    public StaffResponse unphonePassLoginNew(StaffRequest staffRequest) throws SmsException {
        StaffResponse staffResponse = new StaffResponse();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String token = "";
        String password = null;
        String mobilePhone = null;
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone().trim()).trim());
        baseStaff.setPassword(AESUtils.encrypt(staffRequest.getPassword().trim()).trim());
        //如果想再扩大功能，支持一个人同一个手机号码同一个密码，那就将下面的selectOne改为select,再进行多组织的处理
        List<BaseStaff> selects = dao.select(baseStaff);
        if(selects.size()==0){
            throw new SmsException(ResponseCode.MSG,"没有找到该员工的有效信息，请检查是否存在或者是否停用");
        }
        //存在2组织
        if(selects.size()>1){
            List<BaseStore> stores = new ArrayList<>();
            for (BaseStaff select : selects) {
                BaseStore baseStore = new BaseStore();
                baseStore.setId(select.getStoreId());
                BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
                stores.add(baseStore1);
            }
            staffResponse.setBaseStores(stores);
            staffResponse.setStoreType(0);
        }else{
            BaseStaff select = selects.get(0);
            if(null != select){
                if(select.getPassword().equals(AESUtils.encrypt(staffRequest.getPassword().trim()).trim())){
                    //单条处理 判断是否总店
                    BaseStore baseStore = new BaseStore();
                    baseStore.setId(select.getStoreId());
                    BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
                    if(null == baseStore1.getParentId()){
                        //总店
                        //先返回角色关联的门店
                        if(null == select.getRoleId()){
                            throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                        }
                        if(select.getRoleNum().equals("root")){
                            //超管
                            StoreRequest storeRequest = new StoreRequest();
                            storeRequest.setId(select.getStoreId());
                            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                            List<BaseStore> stores = new ArrayList<>();
                            for (BaseStores pagesorganization : pagesorganizations) {
                                BaseStore baseStore2 = new BaseStore();
                                BeanUtils.copyProperties(pagesorganization,baseStore2);
                                stores.add(baseStore2);
                            }
                            staffResponse.setBaseStores(stores);
                        }else{
                            SysRoleStore sysRoleStore = new SysRoleStore();
                            sysRoleStore.setRoleId(select.getRoleId());
                            List<SysRoleStore> select1 = ssmSysRoleStoreService.select(sysRoleStore);
                            List<BaseStore> stores = new ArrayList<>();
                            for (SysRoleStore roleStore : select1) {
                                BaseStore baseStore2 = new BaseStore();
                                baseStore2.setId(roleStore.getStoreId());
                                BaseStore baseStore3 = ssmBaseStoreService.selectByPrimaryKey(baseStore2.getId());
                                stores.add(baseStore3);
                            }
                            staffResponse.setBaseStores(stores);
                        }


                        staffResponse.setStoreType(1);
                    }else{
                        //分店
                        //校验门店是否有效
                        if(baseStore1.getState()==1 || new Date().before(baseStore1.getEndDate())) {
                            //门店没有异常
                            //获取redis key值
                            String key = getKey(staffRequest.getMobilePhone());
                            //从redis查询
                            if (templateRedisClient.hasKey(key)){
                                //存在 将redis数据删除
                                staffResponse = templateRedisClient.get(key);
                                templateRedisClient.delete(key);
                            }else {
                                //redis不存在 将数据库查询到的数据返回
                                BeanUtils.copyProperties(select,staffResponse);
                            }
                            //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                            token = UUID.randomUUID().toString();
                            staffResponse.setToken(token);
                            //查询当前登录员工的菜单权限
                            staffResponse.setStoreNum(baseStore1.getStoreNum());
                            if(null != baseStore1.getParentId()){
                                staffResponse.setParentId(baseStore1.getParentId());
                            }
                            if(null == select.getRoleId()){
                                throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                            }
                            staffResponse = this.getAuthNew(staffResponse);
                            //将登陆用户数据放入redis中
                            key = key + token;
                            templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
                            staffResponse.setStoreType(2);

                        }else{
                            throw new SmsException(ResponseCode.MSG,"该员工的所在门店非有效状态，请检查是否停用或者已经到期");
                        }
                    }
                }else{
                    throw new SmsException(ResponseCode.MSG,"密码错误");
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"没有找到该员工的有效信息，请检查是否存在或者是否停用");
            }
        }

        return staffResponse;
    }

    @Override
    public StaffResponse unphonePassLoginNews(StaffRequest staffRequest) throws SmsException {
        StaffResponse staffResponse = new StaffResponse();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String token = "";
        String password = null;
        String mobilePhone = null;
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone().trim()).trim());
        baseStaff.setPassword(AESUtils.encrypt(staffRequest.getPassword().trim()).trim());
        //如果想再扩大功能，支持一个人同一个手机号码同一个密码，那就将下面的selectOne改为select,再进行多组织的处理
        List<BaseStaff> selects = dao.select(baseStaff);
        if(null != selects || selects.size()>0){
            BaseStaff select = new BaseStaff();
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(staffRequest.getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            for (BaseStores pagesorganization : pagesorganizations) {
                for (BaseStaff select1 : selects) {
                    if(select1.getStoreId().equals(pagesorganization.getId())){
                        select=select1;
                        break;
                    }
                }
            }

            //单条处理 判断是否总店
            BaseStore baseStore = new BaseStore();
            baseStore.setId(staffRequest.getStoreId());
//            baseStore.setId(Long.valueOf("227966281507823616"));
            BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
            if(baseStore1.getState()==1 || new Date().before(baseStore1.getEndDate())) {
                //门店没有异常
                //获取redis key值
                String key = getKey(staffRequest.getMobilePhone());
                //从redis查询
                if (templateRedisClient.hasKey(key)){
                    //存在 将redis数据删除
                    staffResponse = templateRedisClient.get(key);
                    templateRedisClient.delete(key);
                }else {
                    //redis不存在 将数据库查询到的数据返回
                    BeanUtils.copyProperties(select,staffResponse);
                }
                //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                token = UUID.randomUUID().toString();
                staffResponse.setToken(token);
                //查询当前登录员工的菜单权限
                staffResponse.setStoreNum(baseStore1.getStoreNum());
                if(null != baseStore1.getParentId()){
                    staffResponse.setParentId(baseStore1.getParentId());
                }
                if(null == select.getRoleId()){
                    throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                }
                staffResponse.setStoreId(baseStore1.getId());
                staffResponse.setStoreNum(baseStore1.getStoreNum());
                staffResponse.setStoreName(baseStore1.getStoreName());
                staffResponse = this.getAuthNew(staffResponse);
                //将登陆用户数据放入redis中
                key = key + token;
                templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
                staffResponse.setStoreType(2);
            }else{
                throw new SmsException(ResponseCode.MSG,"该员工的所在门店非有效状态，请检查是否停用或者已经到期");
            }
        }else{
            throw new SmsException(ResponseCode.MSG,"没有找到该员工的有效信息，请检查是否存在或者是否停用");
        }
        return staffResponse;
    }

    @Override
    public StaffResponse unphonePassLogindzz(StaffRequest staffRequest) throws SmsException {
        StaffResponse staffResponse = new StaffResponse();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String token = "";
        String password = null;
        String mobilePhone = null;
        BaseStaff baseStaff = new BaseStaff();
        baseStaff.setState(1);
        baseStaff.setMobilePhone(AESUtils.encrypt(staffRequest.getMobilePhone().trim()).trim());
        baseStaff.setPassword(AESUtils.encrypt(staffRequest.getPassword().trim()).trim());
        baseStaff.setStoreId(staffRequest.getStoreId());
        //如果想再扩大功能，支持一个人同一个手机号码同一个密码，那就将下面的selectOne改为select,再进行多组织的处理
        BaseStaff select = dao.selectOne(baseStaff);
        if(null != select){
            if(select.getPassword().equals(AESUtils.encrypt(staffRequest.getPassword().trim()).trim())){
                //单条处理 判断是否总店
                BaseStore baseStore = new BaseStore();
                baseStore.setId(select.getStoreId());
                BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
                if(null == baseStore1.getParentId()){
                    //总店
                    //先返回角色关联的门店
                    if(null == select.getRoleId()){
                        throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                    }
                    if(select.getRoleNum().equals("root")){
                        //超管
                        StoreRequest storeRequest = new StoreRequest();
                        storeRequest.setId(select.getStoreId());
                        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                        List<BaseStore> stores = new ArrayList<>();
                        for (BaseStores pagesorganization : pagesorganizations) {
                            BaseStore baseStore2 = new BaseStore();
                            BeanUtils.copyProperties(pagesorganization,baseStore2);
                            stores.add(baseStore2);
                        }
                        staffResponse.setBaseStores(stores);
                    }else{
                        SysRoleStore sysRoleStore = new SysRoleStore();
                        sysRoleStore.setRoleId(select.getRoleId());
                        List<SysRoleStore> select1 = ssmSysRoleStoreService.select(sysRoleStore);
                        List<BaseStore> stores = new ArrayList<>();
                        for (SysRoleStore roleStore : select1) {
                            BaseStore baseStore2 = new BaseStore();
                            baseStore2.setId(roleStore.getStoreId());
                            BaseStore baseStore3 = ssmBaseStoreService.selectByPrimaryKey(baseStore2.getId());
                            stores.add(baseStore3);
                        }
                        staffResponse.setBaseStores(stores);
                    }
                    staffResponse.setStoreType(1);
                }else{
                    //分店
                    //校验门店是否有效
                    if(baseStore1.getState()==1 || new Date().before(baseStore1.getEndDate())) {
                        //门店没有异常
                        //获取redis key值
                        String key = getKey(staffRequest.getMobilePhone());
                        //从redis查询
                        if (templateRedisClient.hasKey(key)){
                            //存在 将redis数据删除
                            staffResponse = templateRedisClient.get(key);
                            templateRedisClient.delete(key);
                        }else {
                            //redis不存在 将数据库查询到的数据返回
                            BeanUtils.copyProperties(select,staffResponse);
                        }
                        //重新生成新的token 将数据放入redis中（二次登陆 把之前的挤掉）
                        token = UUID.randomUUID().toString();
                        staffResponse.setToken(token);
                        //查询当前登录员工的菜单权限
                        staffResponse.setStoreNum(baseStore1.getStoreNum());
                        if(null != baseStore1.getParentId()){
                            staffResponse.setParentId(baseStore1.getParentId());
                        }
                        if(null == select.getRoleId()){
                            throw new SmsException(ResponseCode.MSG,"该用户未关联任何角色，请联系相关人员对你账户进行分配角色");
                        }
                        staffResponse = this.getAuthNew(staffResponse);
                        //将登陆用户数据放入redis中
                        key = key + token;
                        templateRedisClient.set(key, staffResponse, RedisClient.EXPIRE_TIME_ONE_DAY);
                        staffResponse.setStoreType(2);
                    }else{
                        throw new SmsException(ResponseCode.MSG,"该员工的所在门店非有效状态，请检查是否停用或者已经到期");
                    }
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"密码错误");
            }
        }else{
            throw new SmsException(ResponseCode.MSG,"没有找到该员工的有效信息，请检查是否存在或者是否停用");
        }
        return staffResponse;
    }
    public Long getId(){
        return new SnowflakeUtil(new Random().nextInt(1023)).nextId();
    }
}
