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

import cn.hanghui.outapi.platform.common.entity.rest.RestCode;
import cn.hanghui.outapi.platform.common.entity.rest.RestResponse;
import cn.hanghui.outapi.platform.common.entity.rest.RestResult;
import cn.hanghui.outapi.platform.common.exception.BusinessException;
import cn.hanghui.outapi.platform.common.utils.ClassUtil;
import cn.hanghui.outapi.platform.common.utils.Preconditions;
import cn.hanghui.outapi.platform.tenant.entity.common.DeviceTemplateCommonParams;
import cn.hanghui.outapi.platform.tenant.entity.config.fkj.device.template.FkjDeviceDto;
import cn.hanghui.outapi.platform.tenant.entity.config.fkj.device.template.FkjDeviceSearch;
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.FkjDeviceVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofDeviceDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofDeviceMiniDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofDeviceSearch;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofDeviceUpdateMiniDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofDeviceVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofNoticeDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofNoticeLessVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofNoticeSearch;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofNoticeVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofTemplateDto;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofTemplateLessVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofTemplateSearch;
import cn.hanghui.outapi.platform.tenant.entity.dto.proof.ProvisionalIdentityProofTemplateVo;
import cn.hanghui.outapi.platform.tenant.entity.enums.SystemTypeEnum;
import cn.hanghui.outapi.platform.tenant.entity.po.ApplicationType;
import cn.hanghui.outapi.platform.tenant.entity.po.DeviceModel;
import cn.hanghui.outapi.platform.tenant.entity.po.FkjDevice;
import cn.hanghui.outapi.platform.tenant.entity.po.FkjDeviceTemplate;
import cn.hanghui.outapi.platform.tenant.entity.po.ProvisionalIdentityProofDevice;
import cn.hanghui.outapi.platform.tenant.entity.po.ProvisionalIdentityProofNotice;
import cn.hanghui.outapi.platform.tenant.entity.po.ProvisionalIdentityProofTemplate;
import cn.hanghui.outapi.platform.tenant.entity.po.Purchaser;
import cn.hanghui.outapi.platform.tenant.mapper.ApplicationTypeMapper;
import cn.hanghui.outapi.platform.tenant.mapper.DeviceModelMapper;
import cn.hanghui.outapi.platform.tenant.mapper.ProvisionalIdentityProofDeviceMapper;
import cn.hanghui.outapi.platform.tenant.mapper.ProvisionalIdentityProofNoticeMapper;
import cn.hanghui.outapi.platform.tenant.mapper.ProvisionalIdentityProofTemplateMapper;
import cn.hanghui.outapi.platform.tenant.mapper.PurchaserMapper;
import cn.hanghui.outapi.platform.tenant.service.ProvisionalProofService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
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.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Wrapper;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.tenant.service.impl
 * @class ProvisionalProofServiceImpl
 * @date 2024/5/13 上午11:03
 * @description 临时身份证明
 */
@Slf4j
@Service
public class ProvisionalProofServiceImpl implements ProvisionalProofService {

    @Resource
    private ProvisionalIdentityProofNoticeMapper provisionalIdentityProofNoticeMapper;

    @Resource
    private ProvisionalIdentityProofTemplateMapper provisionalIdentityProofTemplateMapper;

    @Resource
    private ProvisionalIdentityProofDeviceMapper provisionalIdentityProofDeviceMapper;

    @Resource
    private ApplicationTypeMapper applicationTypeMapper;

    @Resource
    private PurchaserMapper purchaserMapper;

    @Resource
    private DeviceModelMapper deviceModelMapper;

    @Resource
    private CommonImpl commonImpl;

    @Override
    public Boolean noticeEdit(ProvisionalIdentityProofNoticeDto dto) {
        if (Preconditions.isBlank(dto.getId())) {
            addNotice(dto);
        } else {
            updateNotice(dto);
        }
        return Boolean.TRUE;
    }

    private void updateNotice(ProvisionalIdentityProofNoticeDto dto) {
        ProvisionalIdentityProofNotice idNotice = provisionalIdentityProofNoticeMapper.selectById(dto.getId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(idNotice), RestCode.FAIL.getCode(), "数据不存在或已删除");
        ProvisionalIdentityProofNotice dbNotice = provisionalIdentityProofNoticeMapper.selectOne(Wrappers.lambdaQuery(ProvisionalIdentityProofNotice.class)
                .eq(ProvisionalIdentityProofNotice::getIsDeleted, Boolean.FALSE)
                .eq(ProvisionalIdentityProofNotice::getName, dto.getName()));
        ClassUtil.throwBusinessException(Preconditions.isNotBlank(dbNotice) && dbNotice.getId().longValue() != dto.getId().longValue(), RestCode.FAIL.getCode(), "配置名称已存在");
        BeanUtil.copyProperties(dto, idNotice);
        provisionalIdentityProofNoticeMapper.updateById(idNotice);
    }

    private void addNotice(ProvisionalIdentityProofNoticeDto dto) {
        ProvisionalIdentityProofNotice dbNotice = provisionalIdentityProofNoticeMapper.selectOne(Wrappers.lambdaQuery(ProvisionalIdentityProofNotice.class)
                .eq(ProvisionalIdentityProofNotice::getIsDeleted, Boolean.FALSE)
                .eq(ProvisionalIdentityProofNotice::getName, dto.getName()));
        ClassUtil.throwBusinessException(Preconditions.isNotBlank(dbNotice), RestCode.FAIL.getCode(), "配置名称已存在");
        ProvisionalIdentityProofNotice notice = BeanUtil.copyProperties(dto, ProvisionalIdentityProofNotice.class);
        provisionalIdentityProofNoticeMapper.insert(notice);
    }

    @Override
    public List<ProvisionalIdentityProofNoticeLessVo> noticeList() {
        LambdaQueryWrapper<ProvisionalIdentityProofNotice> wrapper = getNoticeWrapper(new ProvisionalIdentityProofNoticeSearch());
        List<ProvisionalIdentityProofNotice> notices = provisionalIdentityProofNoticeMapper.selectList(wrapper);
        List<ProvisionalIdentityProofNoticeLessVo> lessVos = BeanUtil.copyToList(notices, ProvisionalIdentityProofNoticeLessVo.class);
        return Preconditions.isNotBlank(lessVos) ? lessVos : Collections.emptyList();
    }

    @Override
    public IPage<ProvisionalIdentityProofNoticeVo> noticePage(ProvisionalIdentityProofNoticeSearch dto) {
        Page<ProvisionalIdentityProofNotice> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        LambdaQueryWrapper<ProvisionalIdentityProofNotice> wrapper = getNoticeWrapper(dto);
        IPage<ProvisionalIdentityProofNotice> iPage = provisionalIdentityProofNoticeMapper.selectPage(page, wrapper);
        return iPage.convert(t -> {
            ProvisionalIdentityProofNoticeVo vo = BeanUtil.copyProperties(t, ProvisionalIdentityProofNoticeVo.class);
            return vo;
        });
    }

    private LambdaQueryWrapper<ProvisionalIdentityProofNotice> getNoticeWrapper(ProvisionalIdentityProofNoticeSearch dto) {
        LambdaQueryWrapper<ProvisionalIdentityProofNotice> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.eq(Preconditions.isNotBlank(dto.getId()), ProvisionalIdentityProofNotice::getId, dto.getId());
        wrapper.like(Preconditions.isNotBlank(dto.getName()), ProvisionalIdentityProofNotice::getName, dto.getName());
        wrapper.like(Preconditions.isNotBlank(dto.getTitle()), ProvisionalIdentityProofNotice::getTitle, dto.getTitle());
        //查询的基础条件
        wrapper.eq(ProvisionalIdentityProofNotice::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(ProvisionalIdentityProofNotice::getId);
        return wrapper;
    }


    @Override
    public Boolean noticeDelete(Long noticeId) {
        ProvisionalIdentityProofNotice notice = provisionalIdentityProofNoticeMapper.selectById(noticeId);
        if (Preconditions.isBlank(notice) || notice.getIsDeleted()) {
            throw new BusinessException(RestCode.DATA_NOT_EXIST);
        }
        provisionalIdentityProofNoticeMapper.deleteById(notice);
        return Boolean.TRUE;
    }

    @Override
    public ProvisionalIdentityProofNoticeVo noticeDetail(Long noticeId) {
        ProvisionalIdentityProofNotice notice = provisionalIdentityProofNoticeMapper.selectById(noticeId);
        if (Preconditions.isBlank(notice) || notice.getIsDeleted()) {
            throw new BusinessException(RestCode.DATA_NOT_EXIST);
        }
        ProvisionalIdentityProofNoticeVo vo = BeanUtil.copyProperties(notice, ProvisionalIdentityProofNoticeVo.class);
        return vo;
    }

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

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

    @Override
    public IPage<ProvisionalIdentityProofTemplateVo> templatePage(ProvisionalIdentityProofTemplateSearch dto) {
        Page<ProvisionalIdentityProofTemplate> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        LambdaQueryWrapper<ProvisionalIdentityProofTemplate> wrapper = getTemplateWrapper(dto);
        IPage<ProvisionalIdentityProofTemplate> iPage = provisionalIdentityProofTemplateMapper.selectPage(page, wrapper);

        List<Long> noticeIds = null;
        if (Preconditions.isNotBlank(iPage.getRecords())) {
            noticeIds = iPage.getRecords().stream().map(ProvisionalIdentityProofTemplate::getProvisionalProofNoticeId).collect(Collectors.toList());
        }
        Map<Long, ProvisionalIdentityProofNotice> noticeMap = getNoticeMap(noticeIds);
        Map<Long, ApplicationType> applicationTypeMap = commonImpl.getApplicationTypeMap(iPage, ProvisionalIdentityProofTemplate::getApplicationTypeId);
        Map<Long, DeviceModel> deviceModelHardwareMap = commonImpl.getDeviceModelMap(iPage, ProvisionalIdentityProofTemplate::getDeviceModelHardwareId);
        Map<Long, DeviceModel> deviceModelEnvironmentMap = commonImpl.getDeviceModelMap(iPage, ProvisionalIdentityProofTemplate::getDeviceModelEnvironmentId);
        return iPage.convert(t -> {
            ProvisionalIdentityProofTemplateVo item = BeanUtil.copyProperties(t, ProvisionalIdentityProofTemplateVo.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());
            }
            if (noticeMap.containsKey(t.getProvisionalProofNoticeId())) {
                item.setProvisionalProofNoticeName(noticeMap.get(t.getProvisionalProofNoticeId()).getName());
            }
            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(t.getSystemTypeCode());
            if (ObjectUtil.isNotNull(systemTypeEnum)) {
                item.setSystemType(systemTypeEnum.getDesc());
            }
            return item;
        });
    }

    private Map<Long, ProvisionalIdentityProofNotice> getNoticeMap(List<Long> noticeIds) {
        if (Preconditions.isBlank(noticeIds)) {
            return new HashMap<>();
        }
        List<ProvisionalIdentityProofNotice> notices = provisionalIdentityProofNoticeMapper.selectBatchIds(noticeIds);
        return notices.stream().collect(Collectors.toMap(ProvisionalIdentityProofNotice::getId, Function.identity()));
    }

    private LambdaQueryWrapper<ProvisionalIdentityProofTemplate> getTemplateWrapper(ProvisionalIdentityProofTemplateSearch dto) {
        LambdaQueryWrapper<ProvisionalIdentityProofTemplate> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.eq(ObjectUtil.isNotNull(dto.getId()), ProvisionalIdentityProofTemplate::getId, dto.getId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getApplicationTypeId()), ProvisionalIdentityProofTemplate::getApplicationTypeId, dto.getApplicationTypeId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelHardwareId()), ProvisionalIdentityProofTemplate::getDeviceModelHardwareId, dto.getDeviceModelHardwareId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelEnvironmentId()), ProvisionalIdentityProofTemplate::getDeviceModelEnvironmentId, dto.getDeviceModelEnvironmentId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getSystemTypeCode()), ProvisionalIdentityProofTemplate::getSystemTypeCode, dto.getSystemTypeCode());

        //查询的基础条件
        wrapper.eq(ProvisionalIdentityProofTemplate::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(ProvisionalIdentityProofTemplate::getId);
        return wrapper;
    }


    @Override
    public Boolean templateDelete(Long templateId) {
        ProvisionalIdentityProofTemplate template = provisionalIdentityProofTemplateMapper.selectById(templateId);
        if (Preconditions.isBlank(template) || template.getIsDeleted()) {
            throw new BusinessException(RestCode.DATA_NOT_EXIST);
        }
        provisionalIdentityProofTemplateMapper.deleteById(template);
        return Boolean.TRUE;
    }

    @Override
    public ProvisionalIdentityProofTemplateVo templateDetail(Long templateId) {
        ProvisionalIdentityProofTemplate template = provisionalIdentityProofTemplateMapper.selectById(templateId);
        if (Preconditions.isBlank(template) || template.getIsDeleted()) {
            throw new BusinessException(RestCode.DATA_NOT_EXIST);
        }
        ProvisionalIdentityProofTemplateVo vo = BeanUtil.copyProperties(template, ProvisionalIdentityProofTemplateVo.class);
        return vo;
    }

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

    @Override
    public RestResult<IPage<ProvisionalIdentityProofDeviceVo>> devicePage(ProvisionalIdentityProofDeviceSearch dto) {
        LambdaQueryWrapper<ProvisionalIdentityProofDevice> wrapper = getDeviceWrapper(dto);
        Page<ProvisionalIdentityProofDevice> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        IPage<ProvisionalIdentityProofDevice> iPage = provisionalIdentityProofDeviceMapper.selectPage(page, wrapper);
        List<Long> noticeIds = null;
        if (Preconditions.isNotBlank(iPage.getRecords())) {
            noticeIds = iPage.getRecords().stream().map(ProvisionalIdentityProofDevice::getProvisionalProofNoticeId).collect(Collectors.toList());
        }
        Map<Long, ProvisionalIdentityProofNotice> noticeMap = getNoticeMap(noticeIds);
        Map<Long, Purchaser> purchaserMap = commonImpl.getPurchaserMap(iPage, ProvisionalIdentityProofDevice::getPurchaserId);
        Map<Long, ApplicationType> applicationTypeMap = commonImpl.getApplicationTypeMap(iPage, ProvisionalIdentityProofDevice::getApplicationTypeId);
        Map<Long, DeviceModel> deviceModelHardwareMap = commonImpl.getDeviceModelMap(iPage, ProvisionalIdentityProofDevice::getDeviceModelHardwareId);
        Map<Long, DeviceModel> deviceModelEnvironmentMap = commonImpl.getDeviceModelMap(iPage, ProvisionalIdentityProofDevice::getDeviceModelEnvironmentId);

        IPage<ProvisionalIdentityProofDeviceVo> convert = iPage.convert(t -> {
            ProvisionalIdentityProofDeviceVo item = BeanUtil.copyProperties(t, ProvisionalIdentityProofDeviceVo.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());
            }
            if (noticeMap.containsKey(t.getProvisionalProofNoticeId())) {
                item.setProvisionalProofNoticeName(noticeMap.get(t.getProvisionalProofNoticeId()).getName());
            }
            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(t.getSystemTypeCode());
            if (ObjectUtil.isNotNull(systemTypeEnum)) {
                item.setSystemType(systemTypeEnum.getDesc());
            }
            return item;
        });
        return RestResult.ok(convert);
    }

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

    @Override
    public RestResult<Boolean> deviceEnable(Long deviceId) {
        ProvisionalIdentityProofDevice device = provisionalIdentityProofDeviceMapper.selectById(deviceId);
        if (Preconditions.isBlank(device) || device.getIsDeleted()) {
            throw new BusinessException(RestCode.DATA_NOT_EXIST);
        }
        device.setStatus(Boolean.TRUE);
        provisionalIdentityProofDeviceMapper.updateById(device);
        return RestResponse.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<Boolean> deviceDel(Long deviceId) {
        ProvisionalIdentityProofDevice device = provisionalIdentityProofDeviceMapper.selectById(deviceId);
        if (Preconditions.isBlank(device) || device.getIsDeleted()) {
            throw new BusinessException(RestCode.DATA_NOT_EXIST);
        }
        provisionalIdentityProofDeviceMapper.deleteById(device);
        return RestResponse.ok(Boolean.TRUE);
    }

    @Override
    public RestResult<Boolean> deviceDisable(Long deviceId) {
        ProvisionalIdentityProofDevice device = provisionalIdentityProofDeviceMapper.selectById(deviceId);
        if (Preconditions.isBlank(device) || device.getIsDeleted()) {
            throw new BusinessException(RestCode.DATA_NOT_EXIST);
        }
        device.setStatus(Boolean.FALSE);
        provisionalIdentityProofDeviceMapper.updateById(device);
        return RestResponse.ok(Boolean.TRUE);
    }

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

    private void completeDevice(ProvisionalIdentityProofDeviceVo vo, ProvisionalIdentityProofDevice 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());
            }
        }
        //小程序授权配置名称
        if (Preconditions.isNotBlank(device.getProvisionalProofNoticeId())) {
            ProvisionalIdentityProofNotice notice = provisionalIdentityProofNoticeMapper.selectById(device.getProvisionalProofNoticeId());
            if (Preconditions.isNotBlank(notice)) {
                vo.setProvisionalProofNoticeName(notice.getName());
                vo.setProvisionalProofNoticeTitle(notice.getTitle());
                vo.setProvisionalProofNoticeDesc(notice.getNotice());
                vo.setProvisionalProofNoticeOfficialSeal(notice.getOfficialSeal());
            }
        }
        //系统类型
        SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(device.getSystemTypeCode());
        if (ObjectUtil.isNotNull(systemTypeEnum)) {
            vo.setSystemType(systemTypeEnum.getDesc());
        }
    }

    @Override
    public void updateConfig(ProvisionalIdentityProofDeviceUpdateMiniDto dto) {
        ClassUtil.throwBusinessException(ObjectUtil.isNull(dto.getModifyType()), RestCode.FAIL.getCode(), "请传入所修改内容的类型");
        LambdaQueryWrapper<ProvisionalIdentityProofDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProvisionalIdentityProofDevice::getSn, dto.getSn()).eq(ProvisionalIdentityProofDevice::getIsDeleted, Boolean.FALSE);
        ProvisionalIdentityProofDevice device = provisionalIdentityProofDeviceMapper.selectOne(wrapper);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(device), RestCode.FAIL.getCode(), "数据不存在或已删除");
        ClassUtil.throwBusinessException(!device.getStatus(), RestCode.FAIL.getCode(), "设备商户平台未授权");
        int modifyType = dto.getModifyType().intValue();
        //所修改内容的类型 0：采集配置 1：查询地址设置 2：推送地址设置 3：功能设置 4：超时时长设置 5：语音设置 6：系统设置
        switch (modifyType) {
            case 0:
                handleCollectData(device, dto);
                break;
            case 1:
                handleRecordUrl(device, dto);
                break;
            case 2:
                handleRecordRecordPushUrl(device, dto);
                break;
            case 3:
                handleFunctionData(device, dto);
                break;
            case 4:
                handleTimeoutData(device, dto);
                break;
            case 5:
                handleVoiceData(device, dto);
                break;
            case 6:
                handleSystemConfData(device, dto);
                break;
            default:
                //不做处理
        }
    }

    @Override
    public List<ProvisionalIdentityProofDeviceVo> snsConfigsForProof(ProvisionalIdentityProofDeviceMiniDto dto) {
        LambdaQueryWrapper<ProvisionalIdentityProofDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ProvisionalIdentityProofDevice::getSn, dto.getSns()).eq(ProvisionalIdentityProofDevice::getIsDeleted, Boolean.FALSE).eq(ProvisionalIdentityProofDevice::getStatus, Boolean.TRUE);
        List<ProvisionalIdentityProofDevice> devices = provisionalIdentityProofDeviceMapper.selectList(wrapper);
        if (Preconditions.isBlank(devices)) {
            return Collections.EMPTY_LIST;
        }
        List<Long> noticeIds = null;
        if (Preconditions.isNotBlank(devices)) {
            noticeIds = devices.stream().map(ProvisionalIdentityProofDevice::getProvisionalProofNoticeId).collect(Collectors.toList());
        }
        Map<Long, ProvisionalIdentityProofNotice> noticeMap = getNoticeMap(noticeIds);
        List<ProvisionalIdentityProofDeviceVo> vos = BeanUtil.copyToList(devices, ProvisionalIdentityProofDeviceVo.class);
        vos.stream().forEach(item -> {
            ProvisionalIdentityProofNotice notice = noticeMap.get(item.getProvisionalProofNoticeId());
            if (noticeMap.containsKey(item.getProvisionalProofNoticeId())) {
                item.setProvisionalProofNoticeName(notice.getName());
                item.setProvisionalProofNoticeName(notice.getName());
                item.setProvisionalProofNoticeTitle(notice.getTitle());
                item.setProvisionalProofNoticeDesc(notice.getNotice());
                item.setProvisionalProofNoticeOfficialSeal(notice.getOfficialSeal());
            }
        });
        return vos;
    }

    private void handleSystemConfData(ProvisionalIdentityProofDevice device, ProvisionalIdentityProofDeviceUpdateMiniDto dto) {
        if (Preconditions.isNotBlank(dto.getMpassword())) {
            device.setMpassword(dto.getMpassword());
        }
        if (Preconditions.isNotBlank(dto.getVoiceVolume())) {
            device.setVoiceVolume(dto.getVoiceVolume());
        }
        provisionalIdentityProofDeviceMapper.updateById(device);
    }

    private void handleVoiceData(ProvisionalIdentityProofDevice device, ProvisionalIdentityProofDeviceUpdateMiniDto dto) {
        if (Preconditions.isNotBlank(dto.getFaceSuccessVoice())) {
            device.setFaceSuccessVoice(dto.getFaceSuccessVoice());
        }
        if (Preconditions.isNotBlank(dto.getFaceFailVoice())) {
            device.setFaceFailVoice(dto.getFaceFailVoice());
        }
        if (Preconditions.isNotBlank(dto.getIdentityProofSuccessVoice())) {
            device.setIdentityProofSuccessVoice(dto.getIdentityProofSuccessVoice());
        }
        if (Preconditions.isNotBlank(dto.getPrintIdentityProofVoice())) {
            device.setPrintIdentityProofVoice(dto.getPrintIdentityProofVoice());
        }
        if (Preconditions.isNotBlank(dto.getInputIdcardVoice())) {
            device.setInputIdcardVoice(dto.getInputIdcardVoice());
        }
        if (Preconditions.isNotBlank(dto.getInputPhoneVoice())) {
            device.setInputPhoneVoice(dto.getInputPhoneVoice());
        }
        if (Preconditions.isNotBlank(dto.getConnectSearchVoice())) {
            device.setConnectSearchVoice(dto.getConnectSearchVoice());
        }
        provisionalIdentityProofDeviceMapper.updateById(device);
    }

    private void handleTimeoutData(ProvisionalIdentityProofDevice device, ProvisionalIdentityProofDeviceUpdateMiniDto dto) {
        if (Preconditions.isNotBlank(dto.getCommonFailedResultPageTimeout())) {
            device.setCommonFailedResultPageTimeout(dto.getCommonFailedResultPageTimeout());
        }
        if (Preconditions.isNotBlank(dto.getRiskFailedResultPageTimeout())) {
            device.setRiskFailedResultPageTimeout(dto.getRiskFailedResultPageTimeout());
        }
        if (Preconditions.isNotBlank(dto.getUserinfoFailedResultPageTimeout())) {
            device.setUserinfoFailedResultPageTimeout(dto.getUserinfoFailedResultPageTimeout());
        }
        if (Preconditions.isNotBlank(dto.getPrintSuccessResultPageTimeout())) {
            device.setPrintSuccessResultPageTimeout(dto.getPrintSuccessResultPageTimeout());
        }
        if (Preconditions.isNotBlank(dto.getCommonSuccessResultPageTimeout())) {
            device.setCommonSuccessResultPageTimeout(dto.getCommonSuccessResultPageTimeout());
        }
        if (Preconditions.isNotBlank(dto.getInputPhoneTimeout())) {
            device.setInputPhoneTimeout(dto.getInputPhoneTimeout());
        }
        if (Preconditions.isNotBlank(dto.getInputIdcardTimeout())) {
            device.setInputIdcardTimeout(dto.getInputIdcardTimeout());
        }
        if (Preconditions.isNotBlank(dto.getAuthQrcodeTimeout())) {
            device.setAuthQrcodeTimeout(dto.getAuthQrcodeTimeout());
        }
        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());
        }
        provisionalIdentityProofDeviceMapper.updateById(device);
    }

    private void handleFunctionData(ProvisionalIdentityProofDevice device, ProvisionalIdentityProofDeviceUpdateMiniDto dto) {
        if (Preconditions.isNotBlank(dto.getRiskCheck())) {
            device.setRiskCheck(dto.getRiskCheck());
        }
        if (Preconditions.isNotBlank(dto.getPrintIdentityProof())) {
            device.setPrintIdentityProof(dto.getPrintIdentityProof());
        }
        provisionalIdentityProofDeviceMapper.updateById(device);
    }

    private void handleRecordRecordPushUrl(ProvisionalIdentityProofDevice device, ProvisionalIdentityProofDeviceUpdateMiniDto dto) {

        if (Preconditions.isNotBlank(dto.getIdentityProofRecordPushUrl())) {
            device.setIdentityProofRecordPushUrl(dto.getIdentityProofRecordPushUrl());
        }
        provisionalIdentityProofDeviceMapper.updateById(device);

    }

    private void handleRecordUrl(ProvisionalIdentityProofDevice device, ProvisionalIdentityProofDeviceUpdateMiniDto dto) {
        if (Preconditions.isNotBlank(dto.getIdentityProofRecordUrl())) {
            device.setIdentityProofRecordUrl(dto.getIdentityProofRecordUrl());
        }
        provisionalIdentityProofDeviceMapper.updateById(device);
    }

    private void handleCollectData(ProvisionalIdentityProofDevice device, ProvisionalIdentityProofDeviceUpdateMiniDto dto) {
        if (Preconditions.isNotBlank(dto.getNoIdcardInputPhone())) {
            device.setNoIdcardInputPhone(dto.getNoIdcardInputPhone());
        }
        if (Preconditions.isNotBlank(dto.getNoIdcardRegister())) {
            device.setNoIdcardRegister(dto.getNoIdcardRegister());
        }
        if (Preconditions.isNotBlank(dto.getUseAlipayFace())) {
            device.setUseAlipayFace(dto.getUseAlipayFace());
        }
        provisionalIdentityProofDeviceMapper.updateById(device);

    }
}
