package cn.hanghui.outapi.platform.tenant.service.impl;

import cn.hanghui.outapi.platform.common.entity.po.Account;
import cn.hanghui.outapi.platform.common.entity.po.AccountAuthConfig;
import cn.hanghui.outapi.platform.common.entity.rest.RestCode;
import cn.hanghui.outapi.platform.common.entity.rest.RestResult;
import cn.hanghui.outapi.platform.common.exception.BusinessException;
import cn.hanghui.outapi.platform.common.mapper.AccountAuthConfigMapper;
import cn.hanghui.outapi.platform.common.utils.ClassUtil;
import cn.hanghui.outapi.platform.common.utils.Preconditions;
import cn.hanghui.outapi.platform.tenant.entity.config.fkj.device.template.FkjDeviceDto;
import cn.hanghui.outapi.platform.tenant.entity.config.fkj.device.template.FkjDeviceMiniDto;
import cn.hanghui.outapi.platform.tenant.entity.config.fkj.device.template.FkjDeviceSearch;
import cn.hanghui.outapi.platform.tenant.entity.config.fkj.device.template.FkjDeviceTemplateDto;
import cn.hanghui.outapi.platform.tenant.entity.config.fkj.device.template.FkjDeviceTemplateLessVo;
import cn.hanghui.outapi.platform.tenant.entity.config.fkj.device.template.FkjDeviceTemplateSearch;
import cn.hanghui.outapi.platform.tenant.entity.config.fkj.device.template.FkjDeviceTemplateVo;
import cn.hanghui.outapi.platform.tenant.entity.config.fkj.device.template.FkjDeviceUpdateMiniDto;
import cn.hanghui.outapi.platform.tenant.entity.config.fkj.device.template.FkjDeviceVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.auth.fkj.FkjAuthDeviceDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.auth.fkj.FkjAuthDeviceSearch;
import cn.hanghui.outapi.platform.tenant.entity.enums.SystemTypeEnum;
import cn.hanghui.outapi.platform.tenant.entity.po.*;
import cn.hanghui.outapi.platform.tenant.mapper.ApplicationTypeMapper;
import cn.hanghui.outapi.platform.tenant.mapper.DeviceModelMapper;
import cn.hanghui.outapi.platform.tenant.mapper.FkjDeviceMapper;
import cn.hanghui.outapi.platform.tenant.mapper.FkjDeviceTemplateMapper;
import cn.hanghui.outapi.platform.tenant.mapper.PurchaserMapper;
import cn.hanghui.outapi.platform.tenant.service.FkjDeviceService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModelProperty;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.tenant.service.impl
 * @class FkjDeviceServiceImpl
 * @date 2024/3/5 下午2:13
 * @description
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @__(@Autowired))
public class FkjDeviceServiceImpl implements FkjDeviceService {

    @Resource
    private FkjDeviceTemplateMapper fkjDeviceTemplateMapper;

    @Resource
    private FkjDeviceMapper fkjDeviceMapper;

    @Resource
    private DeviceModelMapper deviceModelMapper;

    @Resource
    private CommonImpl commonImpl;

    @Resource
    private ApplicationTypeMapper applicationTypeMapper;

    @Resource
    private PurchaserMapper purchaserMapper;
    private final AccountAuthConfigMapper accountAuthConfigMapper;

    @Override
    public Boolean templateEdit(FkjDeviceTemplateDto dto) {
        checkTemplateDto(dto);
        Long templateId = dto.getId();
        if (templateId == null) {
            FkjDeviceTemplate template = BeanUtil.copyProperties(dto, FkjDeviceTemplate.class);
            fkjDeviceTemplateMapper.insert(template);
        } else {
            FkjDeviceTemplate base = fkjDeviceTemplateMapper.selectById(templateId);
            ClassUtil.throwBusinessException(ObjectUtil.isNull(base), RestCode.FAIL.getCode(), "模版不存在");
            BeanUtil.copyProperties(dto, base);
            fkjDeviceTemplateMapper.updateById(base);
        }
        return true;
    }

    private void checkTemplateDto(FkjDeviceTemplateDto dto) {
        //应用类型
        ApplicationType applicationType = applicationTypeMapper.selectById(dto.getApplicationTypeId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType), RestCode.FAIL.getCode(), "应用类型不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType.getIsDeleted()), RestCode.FAIL.getCode(), "应用类型已删除");
        //设备类型（硬件）
        DeviceModel deviceModelHardware = deviceModelMapper.selectById(dto.getDeviceModelHardwareId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware), RestCode.FAIL.getCode(), "设备类型（硬件）不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware.getIsDeleted()), RestCode.FAIL.getCode(), "设备类型（硬件）已删除");
        //设备类型（环境）
        DeviceModel deviceModelEnvironment = deviceModelMapper.selectById(dto.getDeviceModelEnvironmentId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment), RestCode.FAIL.getCode(), "设备类型（环境）不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment.getIsDeleted()), RestCode.FAIL.getCode(), "设备类型（环境）已删除");
        //系统类型
        SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(dto.getSystemTypeCode());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(systemTypeEnum), RestCode.FAIL.getCode(), "系统类型不存在");
    }

    @Override
    public List<FkjDeviceTemplateLessVo> templateList() {
        LambdaQueryWrapper<FkjDeviceTemplate> wrapper = new LambdaQueryWrapper<>();
        //查询的基础条件
        wrapper.eq(FkjDeviceTemplate::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(FkjDeviceTemplate::getId);
        List<FkjDeviceTemplate> templates = fkjDeviceTemplateMapper.selectList(wrapper);
        return templates.stream().map(p -> new FkjDeviceTemplateLessVo()
                .setId(p.getId())
                .setTemplateName(p.getTemplateName())).collect(Collectors.toList());
    }

    @Override
    public IPage<FkjDeviceTemplateVo> templatePage(FkjDeviceTemplateSearch dto) {
        Page<FkjDeviceTemplate> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        LambdaQueryWrapper<FkjDeviceTemplate> wrapper = getTemplateWrapper(dto);
        IPage<FkjDeviceTemplate> iPage = fkjDeviceTemplateMapper.selectPage(page, wrapper);
        Map<Long, ApplicationType> applicationTypeMap = commonImpl.getApplicationTypeMap(iPage, FkjDeviceTemplate::getApplicationTypeId);
        Map<Long, DeviceModel> deviceModelHardwareMap = commonImpl.getDeviceModelMap(iPage, FkjDeviceTemplate::getDeviceModelHardwareId);
        Map<Long, DeviceModel> deviceModelEnvironmentMap = commonImpl.getDeviceModelMap(iPage, FkjDeviceTemplate::getDeviceModelEnvironmentId);
        return iPage.convert(t -> {
            FkjDeviceTemplateVo item = BeanUtil.copyProperties(t, FkjDeviceTemplateVo.class);
            if (applicationTypeMap.containsKey(t.getApplicationTypeId())) {
                item.setApplicationType(applicationTypeMap.get(t.getApplicationTypeId()).getApplicationType());
            }
            if (deviceModelHardwareMap.containsKey(t.getDeviceModelHardwareId())) {
                item.setDeviceModelHardware(deviceModelHardwareMap.get(t.getDeviceModelHardwareId()).getDeviceModel());
            }
            if (deviceModelEnvironmentMap.containsKey(t.getDeviceModelEnvironmentId())) {
                item.setDeviceModelEnvironment(deviceModelEnvironmentMap.get(t.getDeviceModelEnvironmentId()).getDeviceModel());
            }
            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(t.getSystemTypeCode());
            if (ObjectUtil.isNotNull(systemTypeEnum)) {
                item.setSystemType(systemTypeEnum.getDesc());
            }
            return item;
        });
    }

    private LambdaQueryWrapper<FkjDeviceTemplate> getTemplateWrapper(FkjDeviceTemplateSearch dto) {
        LambdaQueryWrapper<FkjDeviceTemplate> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.eq(ObjectUtil.isNotNull(dto.getId()), FkjDeviceTemplate::getId, dto.getId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getApplicationTypeId()), FkjDeviceTemplate::getApplicationTypeId, dto.getApplicationTypeId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelHardwareId()), FkjDeviceTemplate::getDeviceModelHardwareId, dto.getDeviceModelHardwareId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelEnvironmentId()), FkjDeviceTemplate::getDeviceModelEnvironmentId, dto.getDeviceModelEnvironmentId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getSystemTypeCode()), FkjDeviceTemplate::getSystemTypeCode, dto.getSystemTypeCode());
        //查询的基础条件
        wrapper.eq(FkjDeviceTemplate::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(FkjDeviceTemplate::getId);
        return wrapper;
    }

    @Override
    public Boolean templateDelete(Long id) {
        FkjDeviceTemplate template = fkjDeviceTemplateMapper.selectById(id);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(template), RestCode.FAIL.getCode(), "模版不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(template.getIsDeleted()), RestCode.FAIL.getCode(), "模版已删除");
        fkjDeviceTemplateMapper.deleteById(id);
        return Boolean.TRUE;
    }

    @Override
    public FkjDeviceTemplateVo templateDetail(Long id) {
        FkjDeviceTemplate template = fkjDeviceTemplateMapper.selectById(id);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(template), RestCode.FAIL.getCode(), "模版不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(template.getIsDeleted()), RestCode.FAIL.getCode(), "模版已删除");
        return BeanUtil.copyProperties(template, FkjDeviceTemplateVo.class);
    }

    @Override
    public RestResult<Boolean> add(FkjDeviceDto dto) {
        checkDeviceDto(dto);
        LambdaQueryWrapper<FkjDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FkjDevice::getSn, dto.getSn()).eq(FkjDevice::getIsDeleted, Boolean.FALSE);
        FkjDevice snDevice = fkjDeviceMapper.selectOne(wrapper);
        if (dto.getId() == null) {
            ClassUtil.throwBusinessException(ObjectUtil.isNotNull(snDevice), RestCode.FAIL.getCode(), "设备号已存在");
            FkjDevice device = BeanUtil.copyProperties(dto, FkjDevice.class);
            fkjDeviceMapper.insert(device);
        } else {
            FkjDevice device = fkjDeviceMapper.selectById(dto.getId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(device), RestCode.FAIL.getCode(), "数据不存在");
            ClassUtil.throwBusinessException(!device.getId().equals(snDevice.getId()), RestCode.FAIL.getCode(), "设备号已存在");
            BeanUtil.copyProperties(dto, device);
            fkjDeviceMapper.updateById(device);
        }
        return RestResult.ok(true);
    }

    private void checkDeviceDto(FkjDeviceDto dto) {
        //购买方
        Purchaser purchaser = purchaserMapper.selectById(dto.getPurchaserId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(purchaser), RestCode.FAIL.getCode(), "购买方不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(purchaser.getIsDeleted()), RestCode.FAIL.getCode(), "购买方已删除");
        //应用类型
        ApplicationType applicationType = applicationTypeMapper.selectById(dto.getApplicationTypeId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType), RestCode.FAIL.getCode(), "应用类型不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType.getIsDeleted()), RestCode.FAIL.getCode(), "应用类型已删除");
        //设备类型（硬件）
        DeviceModel deviceModelHardware = deviceModelMapper.selectById(dto.getDeviceModelHardwareId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware), RestCode.FAIL.getCode(), "设备类型（硬件）不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware.getIsDeleted()), RestCode.FAIL.getCode(), "设备类型（硬件）已删除");
        //设备类型（环境）
        DeviceModel deviceModelEnvironment = deviceModelMapper.selectById(dto.getDeviceModelEnvironmentId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment), RestCode.FAIL.getCode(), "设备类型（环境）不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment.getIsDeleted()), RestCode.FAIL.getCode(), "设备类型（环境）已删除");
        //系统类型
        SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(dto.getSystemTypeCode());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(systemTypeEnum), RestCode.FAIL.getCode(), "系统类型不存在");
    }

    @Override
    public RestResult<IPage<FkjDeviceVo>> page(FkjDeviceSearch dto) {
        LambdaQueryWrapper<FkjDevice> wrapper = getDeviceWrapper(dto);
        Page<FkjDevice> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        IPage<FkjDevice> iPage = fkjDeviceMapper.selectPage(page, wrapper);
        Map<Long, Purchaser> purchaserMap = commonImpl.getPurchaserMap(iPage, FkjDevice::getPurchaserId);
        Map<Long, ApplicationType> applicationTypeMap = commonImpl.getApplicationTypeMap(iPage, FkjDevice::getApplicationTypeId);
        Map<Long, DeviceModel> deviceModelHardwareMap = commonImpl.getDeviceModelMap(iPage, FkjDevice::getDeviceModelHardwareId);
        Map<Long, DeviceModel> deviceModelEnvironmentMap = commonImpl.getDeviceModelMap(iPage, FkjDevice::getDeviceModelEnvironmentId);

        IPage<FkjDeviceVo> convert = iPage.convert(t -> {
            FkjDeviceVo item = BeanUtil.copyProperties(t, FkjDeviceVo.class);
            if (purchaserMap.containsKey(t.getPurchaserId())) {
                item.setCompanyName(purchaserMap.get(t.getPurchaserId()).getCompanyName());
            }
            if (applicationTypeMap.containsKey(t.getApplicationTypeId())) {
                item.setApplicationType(applicationTypeMap.get(t.getApplicationTypeId()).getApplicationType());
            }
            if (deviceModelHardwareMap.containsKey(t.getDeviceModelHardwareId())) {
                item.setDeviceModelHardware(deviceModelHardwareMap.get(t.getDeviceModelHardwareId()).getDeviceModel());
            }
            if (deviceModelEnvironmentMap.containsKey(t.getDeviceModelEnvironmentId())) {
                item.setDeviceModelEnvironment(deviceModelEnvironmentMap.get(t.getDeviceModelEnvironmentId()).getDeviceModel());
            }
            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(t.getSystemTypeCode());
            if (ObjectUtil.isNotNull(systemTypeEnum)) {
                item.setSystemType(systemTypeEnum.getDesc());
            }
            return item;
        });
        return RestResult.ok(convert);
    }

    private LambdaQueryWrapper<FkjDevice> getDeviceWrapper(FkjDeviceSearch dto) {
        LambdaQueryWrapper<FkjDevice> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.like(StrUtil.isNotBlank(dto.getSn()), FkjDevice::getSn, dto.getSn());
        wrapper.eq(ObjectUtil.isNotNull(dto.getPurchaserId()), FkjDevice::getPurchaserId, dto.getPurchaserId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getApplicationTypeId()), FkjDevice::getApplicationTypeId, dto.getApplicationTypeId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelHardwareId()), FkjDevice::getDeviceModelHardwareId, dto.getDeviceModelHardwareId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelEnvironmentId()), FkjDevice::getDeviceModelEnvironmentId, dto.getDeviceModelEnvironmentId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getSystemTypeCode()), FkjDevice::getSystemTypeCode, dto.getSystemTypeCode());
        wrapper.eq(ObjectUtil.isNotNull(dto.getStatus()), FkjDevice::getStatus, dto.getStatus());
        //基础条件
        wrapper.eq(FkjDevice::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(FkjDevice::getId);
        return wrapper;
    }

    @Override
    public RestResult<Boolean> del(Long id) {
        FkjDevice device = fkjDeviceMapper.selectById(id);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(device), RestCode.FAIL.getCode(), "数据不存在或已删除");
        fkjDeviceMapper.deleteById(device);
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<Boolean> enable(Long id) {
        FkjDevice device = fkjDeviceMapper.selectById(id);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(device), RestCode.FAIL.getCode(), "数据不存在或已删除");
        device.setStatus(Boolean.TRUE);
        fkjDeviceMapper.updateById(device);
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<Boolean> disable(Long id) {
        FkjDevice device = fkjDeviceMapper.selectById(id);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(device), RestCode.FAIL.getCode(), "数据不存在或已删除");
        device.setStatus(Boolean.FALSE);
        fkjDeviceMapper.updateById(device);
        return RestResult.ok(Boolean.TRUE);
    }

    @Override
    public FkjDeviceVo snConfig(FkjDeviceMiniDto dto) {
        LambdaQueryWrapper<FkjDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FkjDevice::getSn, dto.getSn()).eq(FkjDevice::getIsDeleted, Boolean.FALSE);
        FkjDevice device = fkjDeviceMapper.selectOne(wrapper);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(device), RestCode.FAIL.getCode(), "数据不存在或已删除");
        ClassUtil.throwBusinessException(!device.getStatus(), RestCode.FAIL.getCode(), "设备商户平台未授权");
        FkjDeviceVo vo = BeanUtil.copyProperties(device, FkjDeviceVo.class);
        completeDevice(vo, device);
        return vo;
    }

    private void completeDevice(FkjDeviceVo vo, FkjDevice device) {
        //购买方
        if (ObjectUtil.isNotNull(device.getPurchaserId())) {
            Purchaser purchaser = purchaserMapper.selectById(device.getPurchaserId());
            if (ObjectUtil.isNotNull(purchaser)) {
                vo.setCompanyName(purchaser.getCompanyName());
            }
        }
        //应用类型
        if (ObjectUtil.isNotNull(device.getApplicationTypeId())) {
            ApplicationType applicationType = applicationTypeMapper.selectById(device.getApplicationTypeId());
            if (ObjectUtil.isNotNull(applicationType)) {
                vo.setApplicationType(applicationType.getApplicationType());
            }
        }
        //设备类型（硬件）
        if (ObjectUtil.isNotNull(device.getDeviceModelHardwareId())) {
            DeviceModel deviceModelHardware = deviceModelMapper.selectById(device.getDeviceModelHardwareId());
            if (ObjectUtil.isNotNull(deviceModelHardware)) {
                vo.setDeviceModelHardware(deviceModelHardware.getDeviceModel());
            }
        }
        //设备类型（环境）
        if (ObjectUtil.isNotNull(device.getDeviceModelEnvironmentId())) {
            DeviceModel deviceModelEnvironment = deviceModelMapper.selectById(device.getDeviceModelEnvironmentId());
            if (ObjectUtil.isNotNull(deviceModelEnvironment)) {
                vo.setDeviceModelEnvironment(deviceModelEnvironment.getDeviceModel());
            }
        }
        //系统类型
        SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(device.getSystemTypeCode());
        if (ObjectUtil.isNotNull(systemTypeEnum)) {
            vo.setSystemType(systemTypeEnum.getDesc());
        }
    }

    @Override
    public void updateConfig(FkjDeviceUpdateMiniDto dto) {

        ClassUtil.throwBusinessException(ObjectUtil.isNull(dto.getModifyType()), RestCode.FAIL.getCode(), "请传入所修改内容的类型");

        LambdaQueryWrapper<FkjDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FkjDevice::getSn, dto.getSn()).eq(FkjDevice::getIsDeleted, Boolean.FALSE);
        FkjDevice device = fkjDeviceMapper.selectOne(wrapper);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(device), RestCode.FAIL.getCode(), "数据不存在或已删除");
        ClassUtil.throwBusinessException(!device.getStatus(), RestCode.FAIL.getCode(), "设备商户平台未授权");
        if (dto.getModifyType().intValue() == 0) {
            //基本设置
            deviceBaseConfig(dto, device);
            return;
        }
        if (dto.getModifyType().intValue() == 1) {
            //高级设置
            deviceAdvancedConfig(dto, device);
            return;
        }
        if (dto.getModifyType().intValue() == 2) {
            //超时时长设置
            deviceTimeoutConfig(dto, device);
            return;
        }
        if (dto.getModifyType().intValue() == 3) {
            //语音设置
            deviceVoiceConfig(dto, device);
            return;
        }
        if (dto.getModifyType().intValue() == 4) {
            //密码设置
            device.setMpassword(dto.getMpassword());
            fkjDeviceMapper.updateById(device);
        }
    }


    private void deviceVoiceConfig(FkjDeviceUpdateMiniDto dto, FkjDevice device) {
        device.setSuccessVoice(dto.getSuccessVoice());
        device.setFailVoice(dto.getFailVoice());
        device.setRegisterSuccessVoice(dto.getRegisterSuccessVoice());
        device.setReadIdcardVoice(dto.getReadIdcardVoice());
        device.setReadIdcardVoice(dto.getReadIdcardVoice());
        device.setInputIdcardVoice(dto.getInputIdcardVoice());
        device.setInputPhoneVoice(dto.getInputPhoneVoice());
        device.setConnectSearchVoice(dto.getConnectSearchVoice());
        device.setSingOutVoice(dto.getSingOutVoice());
        fkjDeviceMapper.updateById(device);
    }

    private void deviceTimeoutConfig(FkjDeviceUpdateMiniDto dto, FkjDevice device) {
        if (Preconditions.isNotBlank(dto.getChooseVisiteeTimeout())) {
            device.setChooseVisiteeTimeout(dto.getChooseVisiteeTimeout());
        }
        if (Preconditions.isNotBlank(dto.getReadIdcardTimeout())) {
            device.setReadIdcardTimeout(dto.getReadIdcardTimeout());
        }
        if (Preconditions.isNotBlank(dto.getInputIdcardTimeout())) {
            device.setInputIdcardTimeout(dto.getInputIdcardTimeout());
        }
        if (Preconditions.isNotBlank(dto.getInputPhoneTimeout())) {
            device.setInputPhoneTimeout(dto.getInputPhoneTimeout());
        }
        if (Preconditions.isNotBlank(dto.getSingOutTimeout())) {
            device.setSingOutTimeout(dto.getSingOutTimeout());
        }
        if (Preconditions.isNotBlank(dto.getResultPageTimeout())) {
            device.setResultPageTimeout(dto.getResultPageTimeout());
        }
        if (Preconditions.isNotBlank(dto.getFaceTimeout())) {
            device.setFaceTimeout(dto.getFaceTimeout());
        }
        if (Preconditions.isNotBlank(dto.getOneToOneTimeout())) {
            device.setOneToOneTimeout(dto.getOneToOneTimeout());
        }
        if (Preconditions.isNotBlank(dto.getConnectSearchTimeout())) {
            device.setConnectSearchTimeout(dto.getConnectSearchTimeout());
        }
        fkjDeviceMapper.updateById(device);
    }

    private void deviceAdvancedConfig(FkjDeviceUpdateMiniDto dto, FkjDevice device) {
        device.setTransitPushUrl(dto.getTransitPushUrl());
        device.setAreaUrl(dto.getAreaUrl());
        device.setVisiteeUrl(dto.getVisiteeUrl());
        device.setZfbQrcodeUrl(dto.getZfbQrcodeUrl());
        device.setZfbScanRegister(dto.getZfbScanRegister());
        device.setWxQrcodeUrl(dto.getWxQrcodeUrl());
        device.setWxScanRegister(dto.getWxScanRegister());
        device.setNoIdcardInputPhone(dto.getNoIdcardInputPhone());
        device.setNoIdcardRegister(dto.getNoIdcardRegister());
        device.setUsePersonCard(dto.getUsePersonCard());
        device.setUseIdcard(dto.getUseIdcard());
        device.setUseAlipayFace(dto.getUseAlipayFace());
        fkjDeviceMapper.updateById(device);
    }

    private void deviceBaseConfig(FkjDeviceUpdateMiniDto dto, FkjDevice device) {
        device.setGateGrcodeUrl(dto.getGateGrcodeUrl());
        device.setGateQrcodeTitle(dto.getGateQrcodeTitle());
        device.setGateQrcode(dto.getGateQrcode());
        device.setEthQrcodeUrl(dto.getEthQrcodeUrl());
        device.setEthQrcodeTitle(dto.getEthQrcodeTitle());
        device.setEthQrcode(dto.getEthQrcode());
        device.setGeneralQrcodeTitle(dto.getGeneralQrcodeTitle());
        device.setGeneralQrcode(dto.getGeneralQrcode());
        device.setHiddenButton(dto.getHiddenButton());
        device.setRiskCheck(dto.getRiskCheck());
        device.setSignOut(dto.getSignOut());
        device.setPrintVisitorList(dto.getPrintVisitorList());
        device.setReminderAuth(dto.getReminderAuth());
        device.setNotDesensitizedColumn(dto.getNotDesensitizedColumn());
        device.setRegisterNotDesensitizedColumn(dto.getRegisterNotDesensitizedColumn());
        device.setConfirmCountdownSwitch(dto.getConfirmCountdownSwitch());
        device.setConfirmCountdownTime(dto.getConfirmCountdownTime());
        fkjDeviceMapper.updateById(device);
    }
    @Override
    public RestResult<IPage<FkjDeviceVo>> authPage(FkjAuthDeviceSearch dto, Account account) {
        LambdaQueryWrapper<AccountAuthConfig> awrapper = new LambdaQueryWrapper<>();
        awrapper.eq(AccountAuthConfig::getAccountId, account.getId()).eq(AccountAuthConfig::getIsDeleted, Boolean.FALSE);
        AccountAuthConfig config = accountAuthConfigMapper.selectOne(awrapper);
        if (Preconditions.isBlank(config) || Preconditions.isBlank(config.getFkjSwitch()) || !config.getFkjSwitch() || Preconditions.isBlank(config.getPurchaserId())) {
            throw new BusinessException("禁止访问该资源");
        }
        LambdaQueryWrapper<FkjDevice> wrapper = getWrapper(dto,config);
        Page<FkjDevice> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        IPage<FkjDevice> iPage = fkjDeviceMapper.selectPage(page, wrapper);
        Map<Long, Purchaser> purchaserMap = commonImpl.getPurchaserMap(iPage, FkjDevice::getPurchaserId);
        Map<Long, ApplicationType> applicationTypeMap = commonImpl.getApplicationTypeMap(iPage, FkjDevice::getApplicationTypeId);
        Map<Long, DeviceModel> deviceModelHardwareMap = commonImpl.getDeviceModelMap(iPage, FkjDevice::getDeviceModelHardwareId);
        Map<Long, DeviceModel> deviceModelEnvironmentMap = commonImpl.getDeviceModelMap(iPage, FkjDevice::getDeviceModelEnvironmentId);

        IPage<FkjDeviceVo> convert = iPage.convert(t -> {
            FkjDeviceVo item = BeanUtil.copyProperties(t, FkjDeviceVo.class);
            if (purchaserMap.containsKey(t.getPurchaserId())) {
                item.setCompanyName(purchaserMap.get(t.getPurchaserId()).getCompanyName());
            }
            if (applicationTypeMap.containsKey(t.getApplicationTypeId())) {
                item.setApplicationType(applicationTypeMap.get(t.getApplicationTypeId()).getApplicationType());
            }
            if (deviceModelHardwareMap.containsKey(t.getDeviceModelHardwareId())) {
                item.setDeviceModelHardware(deviceModelHardwareMap.get(t.getDeviceModelHardwareId()).getDeviceModel());
            }
            if (deviceModelEnvironmentMap.containsKey(t.getDeviceModelEnvironmentId())) {
                item.setDeviceModelEnvironment(deviceModelEnvironmentMap.get(t.getDeviceModelEnvironmentId()).getDeviceModel());
            }
            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(t.getSystemTypeCode());
            if (ObjectUtil.isNotNull(systemTypeEnum)) {
                item.setSystemType(systemTypeEnum.getDesc());
            }
            return item;
        });
        return RestResult.ok(convert);
    }

    private LambdaQueryWrapper<FkjDevice> getWrapper(FkjAuthDeviceSearch dto,AccountAuthConfig config) {
        LambdaQueryWrapper<FkjDevice> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.like(StrUtil.isNotBlank(dto.getSn()), FkjDevice::getSn, dto.getSn());
        wrapper.eq(ObjectUtil.isNotNull(dto.getStatus()), FkjDevice::getStatus, dto.getStatus());
        //基础条件
        wrapper.eq(FkjDevice::getIsDeleted, Boolean.FALSE);
        wrapper.eq(FkjDevice::getPurchaserId, config.getPurchaserId());
        wrapper.orderByDesc(FkjDevice::getId);
        return wrapper;
    }

    @Override
    public RestResult<Boolean> update(FkjAuthDeviceDto dto, Account account) {
        if (Preconditions.isBlank(dto.getId())) {
            throw new BusinessException("参数有误");
        }
        LambdaQueryWrapper<AccountAuthConfig> awrapper = new LambdaQueryWrapper<>();
        awrapper.eq(AccountAuthConfig::getAccountId, account.getId()).eq(AccountAuthConfig::getIsDeleted, Boolean.FALSE);
        AccountAuthConfig authConfig = accountAuthConfigMapper.selectOne(awrapper);
        if (Preconditions.isBlank(authConfig)
                || Preconditions.isBlank(authConfig.getFkjSwitch())
                || !authConfig.getFkjSwitch()) {
            throw new BusinessException("禁止修改该资源");
        }

        FkjDevice device = fkjDeviceMapper.selectById(dto.getId());
        if (device == null || device.getIsDeleted() == null || device.getIsDeleted()) {
            return RestResult.error("数据不存在或已删除");
        }
        BeanUtil.copyProperties(dto, device, "id");
        fkjDeviceMapper.updateById(device);
        return RestResult.ok(Boolean.TRUE);
    }



}
