package com.ssm.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.ChuangLanBeanSmsUtil;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.BaseDao;
import com.ssm.manage.dao.SsmBaseStoreDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.mapper.BaseStoreMapper;
import com.ssm.manage.query.StaffRequest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.UserResponse;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.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 org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class SsmBaseStoreServiceImpl extends BaseServiceImpl<BaseStore> implements SsmBaseStoreService {
    @Autowired
    private SsmBaseStoreDao dao;
    @Autowired
    private ChuangLanBeanSmsUtil chuangLanBeanSmsUtil;
    @Autowired
    private RedisClient<UserResponse> redisClient;

    @Autowired
    private RedisClient<UserResponse> templateRedisClient;

    @Autowired
    private SsmBaseStaffService ssmBaseStaffService;

    @Autowired
    private SsmSysRoleService ssmSysRoleService;

    @Autowired
    private SsmStoreParaService ssmStoreParaService;
    @Autowired
    private SsmSysStoreRoleService ssmSysStoreRoleService;

    @Override
    public BaseDao<BaseStore> getDao() {
        return dao;
    }

    @Override
    public int addStore(StoreRequest storeRequest, String userNum) throws SmsException {
//        //校验注册人手机 服务电话是否已存在  //多门店允许开分店 手机号校验拿掉
//        getStore(storeRequest.getRegistrantMobilePhone(),null);
//        //校验门店服务电话是否已存在
//        if (StringUtils.isNotBlank(storeRequest.getTelephone())) {
//            getStore(null, storeRequest.getTelephone());
//        }
        // TODO 短信暂时拿掉
        //校验手机验证码
        //获取redis codeKey值
        try{
            if(null != storeRequest.getStoreNum()){
                BaseStore baseStore1 = new BaseStore();
                BaseStore select=new BaseStore();
                baseStore1.setStoreNum(storeRequest.getStoreNum());
                if(storeRequest.getParentId()!=null){//开通分店，按照编码和上级门店ID查询出是否已存在
                    BaseStore check = dao.selectByPrimaryKey(storeRequest.getParentId());
                    if(check!=null&&check.getParentId()==null){
                        if(check.getStoreNum().hashCode()==storeRequest.getStoreNum().hashCode()){
                            throw new SmsException(ResponseCode.MSG,"不能跟总店编码一致");
                        }
                    }
                    baseStore1.setParentId(storeRequest.getParentId());
                }
                select = dao.selectOne(baseStore1);
                if(null != select){
                    throw new SmsException(ResponseCode.MSG,"门店编码重复");
                }
            }
        }catch (Exception e){
            throw new SmsException(ResponseCode.MSG,"门店编码重复");
        }

        String codeKey = getPasscodeKey(storeRequest.getRegistrantMobilePhone());
        String passCode = storeRequest.getPassCode();
        //从redis查询
        if (templateRedisClient.hasKey(codeKey)){
            //校验验证码
            if (!passCode.equals(templateRedisClient.get(codeKey).getPassCode())) {
                throw new SmsException(ResponseCode.SMS_CODE_IS_ERR);
            }
        }
        BaseStore baseStore = new BaseStore();
        baseStore.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
//        baseStore.setProvinceId(storeRequest.getProvinceId());
        baseStore.setProvince(storeRequest.getProvince());
//        baseStore.setCityId(storeRequest.getCityId());
        baseStore.setCity(storeRequest.getCity());
//        baseStore.setCountyId(storeRequest.getCountyId());
        baseStore.setCounty(storeRequest.getCounty());
        baseStore.setState(0);
        baseStore.setStoreAddress(storeRequest.getStoreAddress());
        baseStore.setRegistrant(storeRequest.getRegistrant());
        baseStore.setRegistrantMobilePhone(storeRequest.getRegistrantMobilePhone());
        baseStore.setRegistrantIdentity(storeRequest.getRegistrantIdentity());
        baseStore.setRegistrantSex(storeRequest.getRegistrantSex());
        if(null == storeRequest.getPresupposePassword()){
            storeRequest.setPresupposePassword(String.valueOf((int)((Math.random()*9+1)*100000)));
        }
        baseStore.setPresupposePassword(AESUtils.encrypt(storeRequest.getPresupposePassword()));
        baseStore.setLocationLatitude(storeRequest.getLocationLatitude());
        baseStore.setLocationLongitude(storeRequest.getLocationLongitude());
        baseStore.setTelephone(storeRequest.getTelephone());
        baseStore.setDescription(storeRequest.getDescription());
        baseStore.setStoreName(storeRequest.getStoreName());
        baseStore.setIndustry(storeRequest.getIndustry());
        baseStore.setParentId(storeRequest.getParentId());
        //设置创建人信息
        if (redisClient.hasKey(getKey(userNum))){
            UserResponse userResponse  = redisClient.get(getKey(userNum));
            baseStore.setFunderId(userResponse.getId());
            baseStore.setFunderName(userResponse.getUserName());
        }
        baseStore.setFunderDate(new Date());

        //查询数据库门店编码最新的一个
        String ymDate = DateUtils.YMFormat(new Date());
        Example example = new Example(BaseStore.class);
        Example.Criteria criteria = example.createCriteria();
        //按门店编码降序排列
        example.setOrderByClause("store_num desc");
        //通过时间模糊查询
//        criteria.andLike("storeNum",ymDate + "%");
        List<BaseStore> storeList = dao.selectByExample(example);
        String storeNum;
        String num;
        int mm = 0;
        if (storeList != null && storeList.size() > 0) {
            BaseStore store = storeList.get(0);
            boolean numeric = isNumeric(store.getStoreNum());
            if(numeric){
                mm = Integer.parseInt(store.getStoreNum()) + 1;
                if (mm < 10){
                    num = "00" + mm;
                }else if (mm < 100){
                    num = "0" + mm;
                }else {
                    num = String.valueOf(mm);
                }
            }else{
                String regEx="[^0-9]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(store.getStoreNum());
                String substring = m.replaceAll("").trim();
                mm = Integer.parseInt(substring) + 1;
                if (mm < 10){
                    num = "00" + mm;
                }else if (mm < 100){
                    num = "0" + mm;
                }else {
                    num = String.valueOf(mm);
                }
            }

//            storeNum = ymDate + num;

        }else {
            num = "001" ;
//            storeNum = ymDate + num;
        }
//        baseStore.setStoreNum(storeNum);
        if(StringUtils.isNotBlank(storeRequest.getStoreNum())){
            baseStore.setStoreNum(storeRequest.getStoreNum());
        }else{
            baseStore.setStoreNum(num);
        }

        int i = dao.saveNotNull(baseStore);
//        if(i>0){
//            try {
//                chuangLanBeanSmsUtil.sendAddStore(baseStore);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        return i;
    }

    public static boolean isNumeric(String str){
            for (int i = str.length();--i>=0;){
                   if (!Character.isDigit(str.charAt(i))){
                           return false;
                   }
            }
            return true;
    }

    @Override
    public PageInfo<StoreRequest> selectPage(StoreRequest storeRequest) {
        PageInfo<BaseStore> baseStorePageInfo = dao.selectPage(storeRequest);
        List<BaseStore> list = baseStorePageInfo.getList();
        List<StoreRequest> list2=new ArrayList<>();
        for (BaseStore baseStore : list) {
            try {
                if(baseStore.getPaymentCode()!=null)
                baseStore.setPaymentCode(AESUtils.decrypt(baseStore.getPaymentCode()).trim());
            } catch (Exception e) {
                e.printStackTrace();
            }
            //查询上级门店名称
            StoreRequest storeRequest1=new StoreRequest();
            BeanUtils.copyProperties(baseStore,storeRequest1);
            if(baseStore.getParentId()!=null){
                BaseStore baseStores=dao.selectByPrimaryKey(baseStore.getParentId());
                storeRequest1.setParentIdName(baseStores.getStoreName());
            }
                list2.add(storeRequest1);
        }
        PageInfo<StoreRequest> b=new PageInfo<StoreRequest>(list2);
        b.setTotal(baseStorePageInfo.getTotal());
        return b;
    }

    @Override
    public PageInfo<BaseStores> selectPages(StoreRequest storeRequest) {
        return dao.selectPages(storeRequest);
    }

    @Override
    public PageInfo<BaseStores> pagesparent(StoreRequest storeRequest) {
        return dao.selectPagesparent(storeRequest);
    }

    @Override
    public List<BaseStores> pagesorganization(StoreRequest storeRequest) {
        return dao.pagesorganization(storeRequest);
    }

    @Override
    public List<BaseStores> pagesorganizationim(StoreRequest storeRequest) {
        return dao.pagesorganizationim(storeRequest);
    }

    @Override
    public List<BaseStores> pagesorganizationimZONDDIAN(StoreRequest storeRequest) {
        return dao.pagesorganizationimZONDDIAN(storeRequest);
    }

    @Override
    public List<BaseStores> pagesorganizations(StoreRequest storeRequest) {
        return dao.pagesorganizations(storeRequest);
    }

    @Override
    public BaseStores pagesorganizationone(StoreRequest storeRequest) {
        return dao.pagesorganizationone(storeRequest);
    }

    @Override
    public BaseStore selectOne(StoreRequest storeRequest) {
        BaseStore baseStore = new BaseStore();
        baseStore.setId(storeRequest.getId());
        return dao.selectOne(baseStore);
    }

    @Override
    public int updateStore(StoreRequest storeRequest, String userNum) throws SmsException {
        //多门店允许开分店 手机号校验拿掉
//        if (StringUtils.isNotBlank(storeRequest.getRegistrantMobilePhone())){
//            getStore(storeRequest.getRegistrantMobilePhone(),null);
//        }
//        if (StringUtils.isNotBlank(storeRequest.getTelephone())){
//            getStore(null,storeRequest.getTelephone());
//        }
        BaseStore baseStore = new BaseStore();
        baseStore.setId(storeRequest.getId());
        baseStore.setProvince(storeRequest.getProvince());
        baseStore.setCity(storeRequest.getCity());
        baseStore.setCounty(storeRequest.getCounty());
        baseStore.setStoreAddress(storeRequest.getStoreAddress());
        baseStore.setRegistrant(storeRequest.getRegistrant());
        baseStore.setRegistrantMobilePhone(storeRequest.getRegistrantMobilePhone());
        baseStore.setLocationLatitude(storeRequest.getLocationLatitude());
        baseStore.setLocationLongitude(storeRequest.getLocationLongitude());
        baseStore.setTelephone(storeRequest.getTelephone());
        baseStore.setDescription(storeRequest.getDescription());
        baseStore.setStoreName(storeRequest.getStoreName());
        baseStore.setStoreNum(storeRequest.getStoreNum());
        baseStore.setIndustry(storeRequest.getIndustry());
        baseStore.setEndDate(storeRequest.getEndDate());
        baseStore.setDynamicCheckPsw(storeRequest.getDynamicCheckPsw());
        baseStore.setDynamicPswPhone(storeRequest.getDynamicPswPhone());
        baseStore.setDynamicGetMsm(storeRequest.getDynamicGetMsm());
        baseStore.setState(storeRequest.getState());
        //设置修改人信息
        if (redisClient.hasKey(getKey(userNum))){
            UserResponse userResponse  = redisClient.get(getKey(userNum));
            baseStore.setUpdatedId(userResponse.getId());
            baseStore.setUpdatedName(userResponse.getUserName());
        }
        if(StringUtils.isNotBlank(storeRequest.getPaymentCode())){
            String encrypt = AESUtils.encrypt(storeRequest.getPaymentCode());
            baseStore.setPaymentCode(encrypt);
        }
        baseStore.setUpdatedDate(new Date());

        int i = dao.updateByPrimaryKeySelective(baseStore);

        if(i>0 && storeRequest.getPaymentCode()!= null){
            try {
                chuangLanBeanSmsUtil.sendStoreInitPwdpayment(baseStore, storeRequest.getPaymentCode());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int auditStore(StoreRequest storeRequest, String userNum) throws Exception {
        int i = 0;
        //查询门店员工是否有值 有则不作添加
        BaseStore baseStore = dao.selectByPrimaryKey(storeRequest.getId());
//        //多门店允许开分店 手机号校验拿掉
//        //校验注册人手机  是否已存在
//        getStore(baseStore.getRegistrantMobilePhone(),null);
        String code = ObjectUtils.toString((int) ((Math.random() * 9 + 1) * 1000));//生成初始密码
        if(!"".equals(baseStore.getPresupposePassword().trim())){
            if(baseStore.getPresupposePassword().length()>20){
                code = AESUtils.decrypt(baseStore.getPresupposePassword());
            }else{
                if(baseStore.getPresupposePassword().trim().length()!=0){
                    code = baseStore.getPresupposePassword();
                }
            }
        }

        baseStore.setState(1);
        //String presupposePassword = baseStore.getPresupposePassword();
        baseStore.setPresupposePassword(AESUtils.encrypt(code));
        UserResponse userResponse = new UserResponse();
        if (redisClient.hasKey(getKey(userNum))){
            userResponse = redisClient.get(getKey(userNum));
            baseStore.setReviewer(userResponse.getUserName());
        }
        Date date = new Date();
        baseStore.setReviewerDatetime(date);
        //设置门店开通时间和结束时间
        baseStore.setOpeningDate(date);
        baseStore.setOpeningYear(storeRequest.getOpeningYear());
        baseStore.setEndDate(DateUtils.diffMonth(date, 12*storeRequest.getOpeningYear()));
        i = dao.updateByPrimaryKeySelective(baseStore);
        String encryptMobile = AESUtils.encrypt(baseStore.getRegistrantMobilePhone());

        Map<String,Object> formMap = new HashMap<>();
        if(i>0){
            if(null == baseStore.getParentId()){
                //总店
                formMap.put("superPasswd","123");
                SysStoreRole sysStoreRole = new SysStoreRole();
                sysStoreRole.setStoreId(baseStore.getId());
                sysStoreRole.setStoreNum(baseStore.getStoreNum());
                sysStoreRole.setStoreName(baseStore.getStoreName());
                sysStoreRole.setState(1);
                sysStoreRole.setRoleNum("root");
                sysStoreRole.setRoleName("超级管理员");
                int save = ssmSysStoreRoleService.save(sysStoreRole);

                SysStoreRole sysStoreRole1 = new SysStoreRole();
                sysStoreRole1.setStoreId(baseStore.getId());
                sysStoreRole1.setRoleNum("root");
                sysStoreRole1.setRoleName("超级管理员");
                SysStoreRole sysStoreRole2 = ssmSysStoreRoleService.selectOne(sysStoreRole1);

                BaseStaff baseStaff = new BaseStaff();
                baseStaff.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                baseStaff.setStoreId(baseStore.getId());
                baseStaff.setStoreName(baseStore.getStoreName());
                baseStaff.setMobilePhone(encryptMobile);
                baseStaff.setStaffName(baseStore.getRegistrant());
                baseStaff.setRoleId(sysStoreRole2.getId());
                baseStaff.setRoleNum(sysStoreRole2.getRoleNum());
                baseStaff.setRoleName(sysStoreRole2.getRoleName());
                baseStaff.setState(1);
                baseStaff.setUserState(1);
                baseStaff.setPassword(baseStore.getPresupposePassword());
                baseStaff.setIdentityCard(baseStore.getRegistrantIdentity());
                baseStaff.setSex(baseStore.getRegistrantSex());
                baseStaff.setJoinedDate(new Date());
                baseStaff.setGrade(1);
                baseStaff.setType(0);
                baseStaff.setBaseSalary(new BigDecimal("0"));
                Integer v = Integer.valueOf((int) ((Math.random() * 9) + 1)* 100000) ;
                baseStaff.setBrandNumber(String.valueOf(v));
                try {
                    ssmBaseStaffService.addStaff(baseStaff);
                }catch (Exception e){
                    log.error("SsmBaseStoreServiceImpl.auditStore:",e);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                }
            }else{
                Boolean is=true;
                //总店ID
                Long storeId=baseStore.getParentId();

                BaseStaff baseStaff1 = new BaseStaff();
                baseStaff1.setStoreId(baseStore.getId());
                baseStaff1.setMobilePhone(encryptMobile);
                List<StaffRequest> check1 = ssmBaseStaffService.selectCheck(baseStaff1);
                if(check1.size()>0){
                    is= false;
                }

                //分店
                /*StoreRequest storeRequest1 = new StoreRequest();
                storeRequest1.setId(baseStore.getId());
                List<BaseStores> pagesorganizations = dao.pagesorganizations(storeRequest1);
                for (BaseStores pagesorganization : pagesorganizations) {
                    if(null == pagesorganization.getParentId()){
                        storeId=pagesorganization.getId();
                    }
                    BaseStaff baseStaff = new BaseStaff();
                    baseStaff.setStoreId(pagesorganization.getId());
                    baseStaff.setMobilePhone(encryptMobile);
                    List<BaseStaff> select = ssmBaseStaffService.select(baseStaff);
                    if(select.size()>0){
                        is= false;
                    }
                }*/

                if(is){
                    SysStoreRole sysStoreRole = new SysStoreRole();
                    sysStoreRole.setStoreId(storeId);
                    sysStoreRole.setRoleNum("root");
                    sysStoreRole.setRoleName("超级管理员");
                    SysStoreRole sysStoreRole1 = ssmSysStoreRoleService.selectOne(sysStoreRole);
                    BaseStaff baseStaff = new BaseStaff();
                    baseStaff.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    baseStaff.setStoreId(baseStore.getId());
                    baseStaff.setStoreName(baseStore.getStoreName());
                    baseStaff.setMobilePhone(encryptMobile);
                    baseStaff.setStaffName(baseStore.getRegistrant());
                    baseStaff.setRoleId(sysStoreRole1.getId());
                    baseStaff.setRoleNum(sysStoreRole1.getRoleNum());
                    baseStaff.setRoleName(sysStoreRole1.getRoleName());
                    baseStaff.setState(1);
                    baseStaff.setUserState(1);
                    baseStaff.setPassword(baseStore.getPresupposePassword());
                    baseStaff.setIdentityCard(baseStore.getRegistrantIdentity());
                    baseStaff.setSex(baseStore.getRegistrantSex());
                    baseStaff.setJoinedDate(new Date());
                    baseStaff.setGrade(1);
                    baseStaff.setType(0);
                    baseStaff.setBaseSalary(new BigDecimal("0"));
                    Integer v = Integer.valueOf((int) ((Math.random() * 9) + 1)* 100000) ;
                    baseStaff.setBrandNumber(String.valueOf(v));
                    try {
                        ssmBaseStaffService.addStaff(baseStaff);
                    }catch (Exception e){
                        log.error("SsmBaseStoreServiceImpl.auditStore:",e);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                    }
                }

            }


            formMap.put("proAchiCommVerify","0");
            formMap.put("refundCourse","0");
            formMap.put("guide","0");
            formMap.put("memberIntegral","0");
            formMap.put("buycourse","0");
            formMap.put("cashier","0");
            formMap.put("allowdebt","0");
            formMap.put("refunSpan","0");
            formMap.put("recDebt","0");
            formMap.put("minimum","0");
            formMap.put("refillCard","0");
            formMap.put("refundCard","0");
            formMap.put("serviceTicke","7");
            formMap.put("refundDay","7");
            formMap.put("allowValid","0");
            formMap.put("memberPay","0");
            formMap.put("balance","0.05");
            formMap.put("exceed","90");
            formMap.put("payroll","1");
            formMap.put("memberUsing","0");
            formMap.put("useRecharge","1");
            formMap.put("editOrderNum","7");
            formMap.put("withinBalance","0.1");
            formMap.put("refundCourseNum","0");
            formMap.put("promotion","0");
            formMap.put("Employees_SMS","0");
            formMap.put("maximumAmount","0");
            formMap.put("employeesSMS","1");
            formMap.put("refundRechargeType","0");
            formMap.put("cardCangeListDebt","1");
            ssmStoreParaService.addStoreParas(formMap,baseStore.getId(),baseStore.getStoreName());
//            chuangLanBeanSmsUtil.sendStoreInitPwdSms(baseStore, code);

        }
        return i;
    }

    //发送短信详细
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int again(StoreRequest storeRequest) throws Exception {
        int i =0;

        BaseStaff baseStaff1 = new BaseStaff();
        baseStaff1.setStoreId(storeRequest.getId());
        baseStaff1.setMobilePhone(AESUtils.encrypt(storeRequest.getRegistrantMobilePhone()));
        baseStaff1.setRoleId(Long.valueOf(4));
        List<StaffRequest> check1 = ssmBaseStaffService.selectCheck(baseStaff1);
        if(check1.size()==1){
            i=1;
            BaseStore baseStore=new BaseStore();
            BeanUtils.copyProperties(storeRequest, baseStore);
            String psw=null;
            for(StaffRequest staffRequest:check1){
                psw=AESUtils.decrypt(staffRequest.getPassword());
            }
            chuangLanBeanSmsUtil.sendStoreInitPwdSms(baseStore, psw);
        }
        return i;
    }

    @Override
    public int unauditStore(StoreRequest storeRequest, String userNum) throws SmsException {
        BaseStore store = dao.selectByPrimaryKey(storeRequest.getId());
        store.setState(0);
        UserResponse userResponse = new UserResponse();
        if (redisClient.hasKey(getKey(userNum))){
            userResponse = redisClient.get(getKey(userNum));
            store.setReviewer(userResponse.getUserName());
        }
        store.setReviewerDatetime(new Date());
        int i = dao.updateByPrimaryKeySelective(store);
        //将审核时加入的员工删除
        if (i > 0){
            BaseStaff staff = new BaseStaff();
            staff.setMobilePhone(AESUtils.encrypt(store.getRegistrantMobilePhone()));
            staff.setStoreId(store.getId());
            staff.setState(1);
            try {
                i = ssmBaseStaffService.delete(staff);
            }catch (Exception e){
                log.error("SsmBaseStoreServiceImpl.unauditStore:",e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }

            //删除添加的默认门店参数
            StoreParament storeParament = new StoreParament();
            storeParament.setStoreId(store.getId());
            try {
                i = ssmStoreParaService.delete(storeParament);
            } catch (Exception e){
                log.error("SsmStoreParaServiceImpl.unauditStore",e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }

            if(null == store.getParentId()){
                SysStoreRole sysStoreRole = new SysStoreRole();
                sysStoreRole.setStoreId(store.getId());
                try {
                    i = ssmSysStoreRoleService.delete(sysStoreRole);
                } catch (Exception e){
                    log.error("SsmStoreParaServiceImpl.unauditStore",e);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                }
            }

        }
        return i;
    }


    //判断门店注册人手机号码和服务电话
    private void getStore(String mobilePhone, String telephone) throws SmsException {

        if (mobilePhone != null) {
            BaseStore baseStore = new BaseStore();
            baseStore.setState(1);
            baseStore.setRegistrantMobilePhone(mobilePhone);
            baseStore = selectOne(baseStore);
            if (baseStore != null){
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"注册人手机号码");
            }
        }
        else if (telephone != null) {
            BaseStore baseStore = new BaseStore();
            baseStore.setState(1);
            baseStore.setTelephone(telephone);
            baseStore = selectOne(baseStore);
            if (baseStore != null){
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"服务电话");
            }
        }
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int start(StoreRequest storeRequest, String userNum) throws SmsException {
        BaseStore store = dao.selectByPrimaryKey(storeRequest.getId());
        store.setState(1);
        UserResponse userResponse = new UserResponse();
        if (redisClient.hasKey(getKey(userNum))){
            userResponse = redisClient.get(getKey(userNum));
            store.setUpdatedId(userResponse.getId());
            store.setUpdatedName(userResponse.getUserName());
            store.setUpdatedDate(new Date());
        }
        int i = dao.updateByPrimaryKeySelective(store);
        //启用时只启用门店注册人员工信息
        if (i > 0){
//            //校验门店注册人员工手机号(防止手机号在门店员工中已存在使用者 启用后照成数据查询报错)
//            try {
//                getStaff(AESUtils.encrypt(store.getRegistrantMobilePhone()));
//            } catch (SmsException e) {
//                log.error("SsmBaseStoreServiceImpl.start:", e);
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                throw e;
//            }
            //查询注册人员工
            BaseStaff staff = new BaseStaff();
            //员工手机号进行了加密
            staff.setMobilePhone(AESUtils.encrypt(store.getRegistrantMobilePhone()));
            staff.setStoreId(store.getId());
            staff.setState(2);

            try {
                staff = ssmBaseStaffService.selectOne(staff);
                //修改为启用状态
                staff.setState(1);
                i = ssmBaseStaffService.updateNotNull(staff);
            }catch (Exception e){
                log.error("SsmBaseStoreServiceImpl.start:",e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }

        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int stop(StoreRequest storeRequest, String userNum) throws SmsException {
        BaseStore store = dao.selectByPrimaryKey(storeRequest.getId());
        store.setState(2);
        UserResponse userResponse = new UserResponse();
        if (redisClient.hasKey(getKey(userNum))){
            userResponse = redisClient.get(getKey(userNum));
            store.setUpdatedId(userResponse.getId());
            store.setUpdatedName(userResponse.getUserName());
            store.setUpdatedDate(new Date());
        }
        int i = dao.updateByPrimaryKeySelective(store);
        //停用时停用全部门店员工
        if (i > 0){
            //查询注册人员工
            BaseStaff staff = new BaseStaff();
            staff.setStoreId(store.getId());
            staff.setState(1);
            List<BaseStaff> staffList = ssmBaseStaffService.select(staff);
            try {
                for (BaseStaff baseStaff : staffList) {
                    //修改为停用状态状态
                    baseStaff.setState(2);
                    i = ssmBaseStaffService.updateNotNull(baseStaff);
                }
            }catch (Exception e){
                log.error("SsmBaseStoreServiceImpl.start:",e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }

        }
        return i;
    }

    @Override
    public int addSms(StoreRequest storeRequest) throws SmsException {
        BaseStore baseStore = new BaseStore();
        BeanUtils.copyProperties(storeRequest, baseStore);
        baseStore.setSmsAccount(storeRequest.getSmsAccount().trim());
        baseStore.setSmsPassword(storeRequest.getSmsPassword().trim());
        baseStore.setSmsUrl(storeRequest.getSmsUrl().trim());
        baseStore.setSignId(storeRequest.getSignId().trim());
        return dao.updateByPrimaryKeySelective(baseStore);
    }


    @Override
    public int auditFiled(StoreRequest storeRequest, String userNum) {
        BaseStore baseStore = new BaseStore();
        BeanUtils.copyProperties(storeRequest, baseStore);
        UserResponse userResponse = new UserResponse();
        if (redisClient.hasKey(getKey(userNum))){
            userResponse = redisClient.get(getKey(userNum));
            baseStore.setReviewer(userResponse.getUserName());
        }
        baseStore.setReviewerDatetime(new Date());
        return dao.updateByPrimaryKeySelective(baseStore);
    }

    @Override
    public List<BaseStore> selects(BaseStore baseStore) {
        return dao.selects(baseStore);
    }

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

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

    private void getStaff(String mobilePhone) throws SmsException {

        if (mobilePhone != null) {
            BaseStaff baseStaff = new BaseStaff();
            baseStaff.setState(1);
            baseStaff.setMobilePhone(mobilePhone);
            baseStaff = ssmBaseStaffService.selectOne(baseStaff);
            if (baseStaff != null) {
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "员工手机号码");
            }
        }
    }


    @Override
    public int updateName(String memberName) {

        return dao.uodateName(memberName);
    }

    @Override
    public List<BaseStores> getBaseStoresByChildAndParent(Long storeId) {
        List<BaseStore> baseStores = dao.selectAll();
        List<BaseStores> cccc = new ArrayList<>();
        for (BaseStore baseStore : baseStores) {
            if(baseStore.getId().equals(storeId)){
                List<BaseStores> collect = baseStores.stream().filter(item -> item.getState()==1 && storeId.equals(item.getParentId()==null?0:item.getParentId())).map(item -> {
                    BaseStores stores = new BaseStores();
                    BeanUtils.copyProperties(item, stores);
                    stores.setChildren(getChildStore(baseStores, stores.getId()));
                    stores.setParent(getParentStore(baseStores, stores.getParentId()));
                    return stores;
                }).collect(Collectors.toList());
                BaseStores baseStores1 = new BaseStores();
                BeanUtils.copyProperties(baseStore,baseStores1);
                baseStores1.setParent(getParentStore(baseStores,baseStores1.getParentId()));
                baseStores1.setChildren(collect);
                cccc.addAll(collect);
                cccc.add(baseStores1);
            }
        }

        return cccc;
    }

    @Override
    public List<BaseStores> selectByStore(StoreRequest storeRequest) {
        Example example = new Example(StoreMemberList.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(storeRequest.getStoreNum())) {
            criteria.andLike("storeNum",storeRequest.getStoreNum()).orLike("storeName",storeRequest.getStoreNum());
        }
        //criteria.andEqualTo("storeId", memberRequest.getStoreIdl());
        List<BaseStore> baseStores = dao.selectByExample(example);
        List<BaseStores> collect = baseStores.stream().map(item -> {
            BaseStores baseStores1 = new BaseStores();
            BeanUtils.copyProperties(item, baseStores1);
            return baseStores1;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<BaseStore> selectChildren(Long storeId) {
        return dao.selectChildren(storeId);
    }

    @Override
    public List<BaseStores> selectStoreS(List<Long> storeIds) {
        return dao.selectStoreS(storeIds);
    }

    @Autowired
    BaseStoreMapper baseStoreMapper;
    @Override
    public List<String> selectDescription() {
        return baseStoreMapper.selectDescription();
    }

    @Override
    public List<String> selectGroup() {
        return baseStoreMapper.selectGroup();
    }

    @Override
    public List<BaseStore> selectByIds(List<Long> storeIds) {
        return dao.selectByIds(storeIds);
    }

    @Override
    public PageInfo<BaseStore> PageResponse(StoreRequest storeRequest) {
        BaseStore baseStore = new BaseStore();
        BeanUtils.copyProperties(storeRequest,baseStore);
        PageHelper.startPage(storeRequest.getPageNum(),storeRequest.getPageSize());
        List<BaseStore> select = baseStoreMapper.select(baseStore);
        PageInfo<BaseStore> pageInfo = new PageInfo<>(select);
        return pageInfo;
    }

    private List<BaseStores> getChildStore(List<BaseStore> baseStores,Long parentId){
        List<BaseStores> collect = baseStores.stream().filter(item ->  parentId.equals(item.getParentId()==null?0:item.getParentId())).map(x -> {
            BaseStores stores = new BaseStores();
            BeanUtils.copyProperties(x, stores);
            return stores;
        }).collect(Collectors.toList());
        return collect;
    }
    private List<BaseStores> getParentStore(List<BaseStore> baseStores, Long parentId){
        if(parentId!=null){
            List<BaseStores> collect = baseStores.stream().filter(item -> item.getId().equals(parentId) ).map(x -> {
                BaseStores baseStores1 = new BaseStores();
                BeanUtils.copyProperties(x, baseStores1);
                return baseStores1;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}
