package com.jeequan.jeepay.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.utils.InviteCodeUtil;
import com.jeequan.jeepay.core.utils.google.GoogleAuthUtil;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.service.mapper.AgentInfoMapper;
import com.jeequan.jeepay.service.mapper.MchInfoMapper;
import com.jeequan.jeepay.service.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 系统操作员表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2020-06-13
 */
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUserEntity> {

    @Autowired
    private SysUserAuthService sysUserAuthService;
    @Autowired
    private SysUserRoleRelaService sysUserRoleRelaService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private MchInfoMapper mchInfoMapper;
    @Autowired
    private AgentInfoMapper agentInfoMapper;
    @Autowired
    private SysUserMchStoreRelaService mchStoreRelaService;
    @Autowired
    private MchInfoService mchInfoService;
    @Autowired
    private SysUserEntruleRelaService entruleRelaService;
    @Autowired
    private MchStoreDeviceService mchStoreDeviceService;

    /**
     * 添加系统用户
     **/
    @Transactional
    public void addSysUser(SysUserEntity sysUserEntity, String sysType, String loginPassword) {

        //判断获取到选择的角色集合
//        String roleIdListStr = sysUser.extv().getString("roleIdListStr");
//        if(StringKit.isEmpty(roleIdListStr)) throw new BizException("请选择角色信息！");
//
//        List<String> roleIdList = JSONArray.parseArray(roleIdListStr, String.class);
//        if(roleIdList.isEmpty()) throw new BizException("请选择角色信息！");

        // 判断数据来源
        if (StringUtils.isEmpty(sysUserEntity.getLoginUsername())) {
            throw new BizException("登录用户名不能为空！");
        }
        if (StringUtils.isEmpty(sysUserEntity.getRealname())) {
            throw new BizException("姓名不能为空！");
        }
        if (sysUserEntity.getRealname().length() > 12) {
            throw new BizException("姓名不得超过12个字符");
        }
        if (StringUtils.isEmpty(sysUserEntity.getTelphone())) {
            throw new BizException("手机号不能为空！");
        }
        if (sysUserEntity.getSex() == null) {
            throw new BizException("性别不能为空！");
        }

        //登录用户名不可重复
        if (count(SysUserEntity.gw().eq(SysUserEntity::getSysType, sysType).eq(SysUserEntity::getLoginUsername, sysUserEntity.getLoginUsername())) > 0) {
            throw new BizException("登录用户名已存在！");
        }
        //手机号不可重复
        if (count(SysUserEntity.gw().eq(SysUserEntity::getSysType, sysType).eq(SysUserEntity::getTelphone, sysUserEntity.getTelphone())) > 0) {
            throw new BizException("手机号已存在！");
        }
        //员工号不可重复
        if (count(SysUserEntity.gw().eq(SysUserEntity::getSysType, sysType).eq(SysUserEntity::getBelongInfoId, sysUserEntity.getBelongInfoId()).eq(SysUserEntity::getUserNo, sysUserEntity.getUserNo())) > 0) {
            throw new BizException("员工号已存在！");
        }

        //女  默认头像
        if (sysUserEntity.getSex() != null && CS.SEX_FEMALE == sysUserEntity.getSex()) {
            sysUserEntity.setAvatarUrl("https://jeequan.oss-cn-beijing.aliyuncs.com/jeepay/img/defava_f.png");
        } else {
            sysUserEntity.setAvatarUrl("https://jeequan.oss-cn-beijing.aliyuncs.com/jeepay/img/defava_m.png");
        }

        // 商户拓展员类型 且是队长
        if (sysUserEntity.getUserType() == com.jeequan.jeepay.core.entity.SysUser.UEST_TYPE_EXPAND && sysUserEntity.getIsTeamLeader() == CS.YES) {
            LambdaUpdateWrapper<SysUserEntity> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(SysUserEntity::getTeamId, sysUserEntity.getTeamId());
            wrapper.set(SysUserEntity::getIsTeamLeader, CS.NO);
            this.update(wrapper);
        }

        resetSysUserPwdTime(sysUserEntity, loginPassword);

        //1. 插入用户主表
        sysUserEntity.setSysType(sysType); // 系统类型
        this.save(sysUserEntity);

        Long sysUserId = sysUserEntity.getSysUserId();

        // 添加邀请码， 邀请码不可重复
        String inviteCode = InviteCodeUtil.idToCode(sysUserId);
        if (count(SysUserEntity.gw().eq(SysUserEntity::getInviteCode, inviteCode)) > 0) {
            throw new BizException("邀请码重复，请联系平台管理员！");
        }
        SysUserEntity updateRecord = new SysUserEntity();
        updateRecord.setSysUserId(sysUserId);
        updateRecord.setInviteCode(inviteCode);
        this.updateById(updateRecord);

        sysUserAuthService.addUserAuthDefault(sysUserId, sysUserEntity.getLoginUsername(), sysUserEntity.getTelphone(), loginPassword, sysType);

    }

    // password为空，代表是默认密码
    public void resetSysUserPwdTime(SysUserEntity sysUserEntity, String password) {

        // 过期天数
        Integer expireDay = sysConfigService.getDBSecurityConfig().getPasswordExpireDay();
        if (StringUtils.isBlank(password) || expireDay == null) {
            expireDay = 0;
        }

        Date date = new Date();
        sysUserEntity.setLastResetPwdTime(date);
        sysUserEntity.setPwdExpiredTime(expireDay == 0 ? date : DateUtil.offsetDay(date, expireDay));

    }

    //修改用户信息
    // resetAuthInfo: 当更改操作员信息功能时需要更新  true
    // 重置商户信息，服务商信息时，不需要更新。 因为会与密码同时更新，避免多余的update操作。
    @Transactional
    public void updateSysUser(SysUserEntity sysUserEntity, boolean resetAuthInfo) {

        Long sysUserId = sysUserEntity.getSysUserId();
        SysUserEntity dbRecord = getById(sysUserId);

        if (dbRecord == null) {
            throw new BizException("该用户不存在");
        }

        // 商户拓展员类型 且是队长
        if (sysUserEntity.getUserType() != null && sysUserEntity.getIsTeamLeader() != null
                && sysUserEntity.getUserType() == com.jeequan.jeepay.core.entity.SysUser.UEST_TYPE_EXPAND && sysUserEntity.getIsTeamLeader() == CS.YES) {
            LambdaUpdateWrapper<SysUserEntity> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(SysUserEntity::getTeamId, sysUserEntity.getTeamId());
            wrapper.set(SysUserEntity::getIsTeamLeader, CS.NO);
            this.update(wrapper);
        }

        // 避免更新空串
        if (StringUtils.isEmpty(sysUserEntity.getTelphone())) {
            sysUserEntity.setTelphone(null);
        }

        //修改了手机号， 需要修改auth表信息
        if (StringUtils.isNotEmpty(sysUserEntity.getTelphone()) && !dbRecord.getTelphone().equals(sysUserEntity.getTelphone())) {

            if (count(SysUserEntity.gw().eq(SysUserEntity::getSysType, dbRecord.getSysType()).eq(SysUserEntity::getTelphone, sysUserEntity.getTelphone())) > 0) {
                throw new BizException("该手机号已关联其他用户！");
            }

            if (resetAuthInfo) {
                sysUserAuthService.resetAuthInfo(sysUserId, null, sysUserEntity.getTelphone(), false, null, dbRecord.getSysType());
            }

        }


        // 避免更新空串
        if (StringUtils.isEmpty(sysUserEntity.getLoginUsername())) {
            sysUserEntity.setLoginUsername(null);
        }
        //修改了登录名， 需要修改auth表信息
        if (StringUtils.isNotEmpty(sysUserEntity.getLoginUsername()) && !dbRecord.getLoginUsername().equals(sysUserEntity.getLoginUsername())) {

            if (count(SysUserEntity.gw().eq(SysUserEntity::getSysType, dbRecord.getSysType()).eq(SysUserEntity::getLoginUsername, sysUserEntity.getLoginUsername())) > 0) {
                throw new BizException("该登录用户名已关联其他用户！");
            }

            if (resetAuthInfo) {
                sysUserAuthService.resetAuthInfo(sysUserId, sysUserEntity.getLoginUsername(), null, false, null, dbRecord.getSysType());
            }
        }

        //修改用户主表
        baseMapper.updateById(sysUserEntity);
    }


    /**
     * 分配用户角色
     **/
    @Transactional
    public void saveUserRole(Long userId, List<String> roleIdList) {

        //删除用户之前的 角色信息
        sysUserRoleRelaService.remove(SysUserRoleRela.gw().eq(SysUserRoleRela::getUserId, userId));
        for (String roleId : roleIdList) {
            SysUserRoleRela addRecord = new SysUserRoleRela();
            addRecord.setUserId(userId);
            addRecord.setRoleId(roleId);
            sysUserRoleRelaService.save(addRecord);
        }
    }

    /**
     * 删除用户
     **/
    @Transactional
    public void removeUser(SysUserEntity sysUserEntity, String sysType) {
        // 1.删除用户登录信息
        sysUserAuthService.remove(SysUserAuth.gw()
                .eq(SysUserAuth::getSysType, sysType)
                .in(SysUserAuth::getUserId, sysUserEntity.getSysUserId())
        );
        // 2.删除用户角色信息
        sysUserRoleRelaService.removeById(sysUserEntity.getSysUserId());
        // 3.删除用户信息
        removeById(sysUserEntity.getSysUserId());
        // 4.删除绑定门店信息
        mchStoreRelaService.remove(SysUserMchStoreRela.gw()
                .eq(SysUserMchStoreRela::getSysUserId, sysUserEntity.getSysUserId())
        );
        // 删除用户权限关联表
        entruleRelaService.removeById(sysUserEntity.getSysUserId());
    }


    /**
     * 获取到商户的超管用户ID
     **/
    public Long findMchAdminUserId(String mchNo) {
        return mchInfoMapper.selectById(mchNo).getInitUserId();
    }

    /**
     * 获取到服务商的超管用户ID
     **/
    public Long findAgentAdminUserId(String agentNo) {
        return agentInfoMapper.selectById(agentNo).getInitUserId();
    }

    /**
     * 查询用户列表
     **/
    public List<JSONObject> selectList(IPage iPage, SysUserEntity queryObject) {

        Map<String, Object> params = genQueryParams(queryObject);
        params.put("limit", iPage.getSize());
        params.put("offset", iPage.offset());

        return baseMapper.selectUserPage(params);
    }

    /**
     * 查询用户总数
     **/
    public long queryCount(SysUserEntity queryObject) {
        return baseMapper.selectUserCount(genQueryParams(queryObject));
    }

    public Map<String, Object> genQueryParams(SysUserEntity queryObject) {

        Map<String, Object> params = new HashMap<>();

        if (StringUtils.isNotBlank(queryObject.getSysType())) {
            params.put("sysType", queryObject.getSysType());
        }
        if (StringUtils.isNotBlank(queryObject.getBelongInfoId())) {
            params.put("belongInfoId", queryObject.getBelongInfoId());
        }
        if (queryObject.getSysUserId() != null) {
            params.put("sysUserId", queryObject.getSysUserId());
        }
        if (StringUtils.isNotBlank(queryObject.getRealname())) {
            params.put("realname", queryObject.getRealname());
        }
        if (StringUtils.isNotBlank(queryObject.getTelphone())) {
            params.put("telphone", queryObject.getTelphone());
        }
        if (queryObject.getState() != null) {
            params.put("state", queryObject.getState());
        }
        if (queryObject.getTeamId() != null) {
            params.put("teamId", queryObject.getTeamId());
        }
        if (queryObject.getIsTeamLeader() != null) {
            params.put("isTeamLeader", queryObject.getIsTeamLeader());
        }
        if (queryObject.getUserType() != null) {
            params.put("userType", queryObject.getUserType());
        }

        return params;
    }


    /**
     * 重置密码,  如果 resetPassword = true && newPwd = null 那么使用的系统默认密码。
     */
    @Transactional
    public void resetUserAndAuthInfo(Long resetUserId, String authLoginUserName, String telphone, boolean resetPassword, String newPwd, String sysType) {

        // 有更新基础信息
        if (StringUtils.isNotEmpty(authLoginUserName) || StringUtils.isNotEmpty(telphone)) {
            SysUserEntity sysUserEntity = new SysUserEntity();
            sysUserEntity.setSysUserId(resetUserId).setLoginUsername(authLoginUserName).setTelphone(telphone);
            this.updateSysUser(sysUserEntity, false);
        }

        // 更新认证信息
        sysUserAuthService.resetAuthInfo(resetUserId, authLoginUserName, telphone, resetPassword, newPwd, sysType);

    }


    @Transactional
    public void updateMFASecret(Long userId, String secretKey, Byte bindState) {
        SysUserEntity updateInfo = new SysUserEntity();
        updateInfo.setSysUserId(userId);
        if (StringUtils.isNotEmpty(secretKey)) {
            updateInfo.setMfaSecretKey(secretKey);
        }
        if (bindState != null) {
            updateInfo.setMfaBindState(bindState);
        }
        updateById(updateInfo);
    }

    /**
     * MFA验证
     **/
    public void checkMFACode(Long userId, String verCode) {
        SysUserEntity dbUser = getById(userId);
        if (dbUser == null || StringUtils.isEmpty(dbUser.getMfaSecretKey())) {
            throw new BizException("用户未绑定MFA验证！");
        }
        Boolean result = GoogleAuthUtil.checkByCode(verCode, dbUser.getMfaSecretKey());
        if (!result) {
            throw new BizException("MFA验证失败！");
        }
    }

    /**
     * 绑定MFA验证
     **/
    public void bindMFA(Long userId) {
        SysUserEntity dbUser = getById(userId);
        if (dbUser == null) {
            throw new BizException("用户不存在");
        }
        if (dbUser.getMfaBindState() == CS.YES) {
            throw new BizException("当前用户已绑定MFA验证");
        }
        // 修改绑定信息
        SysUserEntity updateInfo = new SysUserEntity();
        updateInfo.setSysUserId(dbUser.getSysUserId());
        updateInfo.setMfaBindState(CS.YES);
        boolean result = updateById(updateInfo);
        if (!result) {
            throw new BizException("绑定MFA验证失败");
        }
    }

    /**
     * 解除MFA验证
     **/
    @Transactional
    public void relieveMFA(Long userId, String sysType) {
        SysUserEntity dbUser = getOne(SysUserEntity.gw().eq(SysUserEntity::getSysUserId, userId).eq(StringUtils.isNotEmpty(sysType), SysUserEntity::getSysType, sysType));
        if (dbUser == null) {
            throw new BizException("用户不存在");
        }
        if (dbUser.getMfaBindState() == CS.NO) {
            throw new BizException("用户未绑定MFA验证");
        }

        SysUserEntity updateInfo = new SysUserEntity();
        updateInfo.setMfaBindState(CS.NO);
        updateInfo.setMfaSecretKey("");
        // 修改绑定信息
        boolean result = update(updateInfo,
                SysUserEntity.gw()
                        .eq(SysUserEntity::getSysUserId, dbUser.getSysUserId())
                        .eq(SysUserEntity::getMfaBindState, CS.YES)
        );
        if (!result) {
            throw new BizException("解除MFA验证失败");
        }
    }

    /**
     * 解除操作员MFA验证
     **/
    public void relieveOperatorMFA(Long currentUserId, Long operatorId) {
        // 当前用户是否为超管
        SysUserEntity currentUser = getById(currentUserId);
        if (currentUser.getUserType() != SysUser.UEST_TYPE_ADMIN) {
            throw new BizException("用户权限不足");
        }
        String sysType = currentUser.getSysType();
        if (CS.SYS_ROLE_TYPE.PLATFORM.equals(sysType)) {
            sysType = null;
        }
        // 解除MFA验证
        relieveMFA(operatorId, sysType);
    }


    /**
     * 更新上次登录时间
     */
    public void updateLastLoginTime(Long sysUserId) {

        if (sysUserId == null) {
            return;
        }

        SysUserEntity updateRecord = new SysUserEntity();
        updateRecord.setSysUserId(sysUserId);
        updateRecord.setLastLoginTime(new Date());
        updateById(updateRecord);
    }

    /**
     * @author: xiaoyu
     * @date: 2022/10/11 15:11
     * @describe: 绑定信息修改
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserBindStore(SysUserEntity sysUserEntity, Byte dbUserType) {

        if (sysUserEntity.getUserType() != null) {

            if (SysUser.UEST_TYPE_DIRECTOR == sysUserEntity.getUserType() || SysUser.UEST_TYPE_CASHIER == sysUserEntity.getUserType()) {

                MchInfo mchInfo = mchInfoService.getById(sysUserEntity.getBelongInfoId());
                if (mchInfo == null) {
                    throw new BizException("商户不存在");
                }

                // 判断当前商户类型是否为M1商户
                if (!MchInfo.MCH_LEVEL_M1.equals(mchInfo.getMchLevel())) {
                    throw new BizException("请先修改为M1商户");
                }
            }

            // 如果用户类型更改 判断是否为店长与操作员类型修改
            if ((SysUser.UEST_TYPE_DIRECTOR == dbUserType || SysUser.UEST_TYPE_CASHIER == dbUserType) && !dbUserType.equals(sysUserEntity.getUserType())) {
                // 清空当前用户已绑定的门店信息
                mchStoreRelaService.remove(SysUserMchStoreRela.gw().eq(SysUserMchStoreRela::getSysUserId, sysUserEntity.getSysUserId()));

                // 删除用户权限关联
                entruleRelaService.removeById(sysUserEntity.getSysUserId());
            }
        }
    }

    /**
     * 功能描述: 更新用户， 保证事务， 避免ctrl出现事务不回滚的问题。
     *
     * @param sysUserEntity       更新的用户信息数据
     * @param recordId      更新的用户信息ID
     * @param currentUserId 当前登录用户ID
     * @Return: boolean  是否清空redis用户缓存
     * @Author: terrfly
     * @Date: 2022/10/14 10:29
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserOnTx(SysUserEntity sysUserEntity, Long recordId, Long currentUserId) {

        //判断是否自己禁用自己
        if (recordId.equals(currentUserId) && sysUserEntity.getState() != null && sysUserEntity.getState() == CS.PUB_DISABLE) {
            throw new BizException("系统不允许禁用当前登陆用户！");
        }

        Boolean isResetPass = sysUserEntity.extv().getBoolean("resetPass"); // 是否重置密码
        Boolean isDefaultPass = sysUserEntity.extv().getBoolean("defaultPass"); // 是否重置为默认密码
        String confirmNewPwd = sysUserEntity.extv().getString("confirmPwd"); // 重置密码 && 自定义密码 时的密码原始数据
        Boolean isSetInviteCode = sysUserEntity.extv().getBoolean("setInviteCode"); // 是否重置邀请码

        boolean delAuthenticationFlag = false;

        //如果用户被禁用，需要更新redis数据
        if (sysUserEntity.getState() != null && sysUserEntity.getState() == CS.PUB_DISABLE) {
            delAuthenticationFlag = true;
        }

        // 查询所属用户的系统类型（ 不一定是运营平台用户 ）
        SysUserEntity dbUserInfo = this.getById(recordId);

        // 绑定门店信息修改
        this.updateUserBindStore(sysUserEntity, dbUserInfo.getUserType());

        //判断是否重置密码
        if (isResetPass != null && isResetPass) {
            String updatePwd = isDefaultPass == false ? Base64.decodeStr(confirmNewPwd) : null;

            sysUserAuthService.resetAuthInfo(recordId, null, null, true, updatePwd, dbUserInfo.getSysType());

            // 需要删除用户redis缓存信息
            delAuthenticationFlag = true;
        }

        // 是否重置邀请码
        if (isSetInviteCode != null && isSetInviteCode) {
            sysUserEntity.setInviteCode(InviteCodeUtil.idToCode(recordId));
        }

        this.updateSysUser(sysUserEntity, true);

        return delAuthenticationFlag;
    }

    /**
     * 商户编辑用户方法重写
     *
     * @param sysUserEntity
     * @param recordId
     * @param currentUserId
     * @param storeIdList
     * @param rulesList
     * @param userType
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserOnTx2(SysUserEntity sysUserEntity, Long recordId, Long currentUserId, String storeIdList, String rulesList, byte userType) {
        boolean updateUserOnTx = this.updateUserOnTx(sysUserEntity, recordId, currentUserId);

        if (sysUserEntity.getUserType() != null) {
            // 修改用户为店长、店员
            if (SysUser.UEST_TYPE_DIRECTOR == sysUserEntity.getUserType() || SysUser.UEST_TYPE_CASHIER == sysUserEntity.getUserType()) {
                // 如果修改用户为店长、修改店长门店 跳过该操作
                if (SysUser.UEST_TYPE_DIRECTOR == sysUserEntity.getUserType() && SysUser.UEST_TYPE_DIRECTOR == userType) {

                } else {
                    // 绑定门店
                    mchStoreRelaService.bindStore(sysUserEntity, storeIdList);

                    // APP无需传入此数据。
                    if (StringUtils.isEmpty(rulesList) && SysUser.UEST_TYPE_DIRECTOR == sysUserEntity.getUserType()) {
                        rulesList = JSON.toJSONString(Collections.singletonList("USER_TYPE_11_INIT"));
                    }

                    if (StringUtils.isEmpty(rulesList) && SysUser.UEST_TYPE_CASHIER == sysUserEntity.getUserType()) {
                        rulesList = JSON.toJSONString(Collections.singletonList("USER_TYPE_12_INIT"));
                    }

                    // 关联用户权限
                    entruleRelaService.userRela(sysUserEntity, rulesList);
                }
            } else {
                // 删除绑定门店信息
                mchStoreRelaService.remove(SysUserMchStoreRela.gw()
                        .eq(SysUserMchStoreRela::getSysUserId, sysUserEntity.getSysUserId())
                );
                // 删除用户权限关联
                entruleRelaService.removeById(recordId);
            }
        }

        return updateUserOnTx;
    }

    /**
     * 添加系统用户
     **/
    @Transactional
    public void addSysUser2(SysUserEntity sysUserEntity, String sysType, String loginPassword, String storeIdList, String rulesList) {

        this.addSysUser(sysUserEntity, sysType, loginPassword);

        // 如果当前用户为店长、店员
        if (SysUser.UEST_TYPE_DIRECTOR == sysUserEntity.getUserType() || SysUser.UEST_TYPE_CASHIER == sysUserEntity.getUserType()) {

            // 绑定门店
            mchStoreRelaService.bindStore(sysUserEntity, storeIdList);

            // APP无需传入此数据。
            if (StringUtils.isEmpty(rulesList) && SysUser.UEST_TYPE_DIRECTOR == sysUserEntity.getUserType()) {
                rulesList = JSONArray.toJSONString(Arrays.asList("USER_TYPE_11_INIT"));
            }

            if (StringUtils.isEmpty(rulesList) && SysUser.UEST_TYPE_CASHIER == sysUserEntity.getUserType()) {
                rulesList = JSONArray.toJSONString(Arrays.asList("USER_TYPE_12_INIT"));
            }

            entruleRelaService.userRela(sysUserEntity, rulesList);
        }
    }

    /**
     * 验证刷脸设备是否允许当前用户登录
     **/
    public MchStoreDevice checkFaceApp(com.jeequan.jeepay.core.entity.SysUser sysUser, String faceDevice) {
        if (StringUtils.isBlank(faceDevice)) {
            throw new BizException("设备参数不能为空");
        }
        if (sysUser.getUserType() != SysUser.UEST_TYPE_ADMIN && sysUser.getUserType() != SysUser.UEST_TYPE_DIRECTOR && sysUser.getUserType() != SysUser.UEST_TYPE_CASHIER) {
            throw new BizException("仅支持超管、店长、店员登录");
        }

        MchStoreDevice info = JSON.parseObject(faceDevice, MchStoreDevice.class);
        if (StringUtils.isAnyBlank(info.getDeviceNo(), info.getProvider())) {
            throw new BizException("设备参数不能为空");
        }

        MchStoreDevice mchStoreDevice = mchStoreDeviceService.getOne(MchStoreDevice.gw()
                .eq(MchStoreDevice::getDeviceNo, info.getDeviceNo())
                .eq(MchStoreDevice::getDeviceType, MchStoreDevice.DEVICE_TYPE_FACE_APP)
                .eq(MchStoreDevice::getProvider, info.getProvider())
                .eq(MchStoreDevice::getMchNo, sysUser.getBelongInfoId())
                .eq(MchStoreDevice::getBindState, CS.YES)
        );
        if (mchStoreDevice == null) {
            throw new BizException("请联系平台绑定设备或前往商户平台-设备管理-新建刷脸设备");
        }
        if (mchStoreDevice.getState() != CS.YES) {
            throw new BizException("当前设备已禁用");
        }
        if (sysUser.getUserType() == SysUser.UEST_TYPE_DIRECTOR || sysUser.getUserType() == SysUser.UEST_TYPE_CASHIER) {
            List<SysUserMchStoreRela> storeRelaList = mchStoreRelaService.list(SysUserMchStoreRela.gw().eq(SysUserMchStoreRela::getSysUserId, sysUser.getSysUserId()));
            if (CollUtil.isEmpty(storeRelaList)) {
                throw new BizException("当前用户未绑定门店，请先联系商户绑定门店");
            }
            if (storeRelaList.stream().noneMatch(i -> i.getStoreId().equals(mchStoreDevice.getStoreId()))) {
                throw new BizException("当前账号绑定门店与设备绑定门店不匹配");
            }
        }
        return mchStoreDevice;
    }
}
