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

import cn.hanghui.outapi.platform.common.entity.rest.RestCode;
import cn.hanghui.outapi.platform.common.utils.ClassUtil;
import cn.hanghui.outapi.platform.common.utils.Preconditions;
import cn.hanghui.outapi.platform.tenant.entity.config.iot.template.IotDeviceConfigTemplateDto;
import cn.hanghui.outapi.platform.tenant.entity.config.iot.template.IotDeviceConfigTemplateLessVo;
import cn.hanghui.outapi.platform.tenant.entity.config.iot.template.IotDeviceConfigTemplateSearch;
import cn.hanghui.outapi.platform.tenant.entity.config.iot.template.IotDeviceConfigTemplateVo;
import cn.hanghui.outapi.platform.tenant.entity.enums.CameraBrandEnum;
import cn.hanghui.outapi.platform.tenant.entity.enums.CameraTypeEnum;
import cn.hanghui.outapi.platform.tenant.entity.enums.IdCardReaderBrandEnum;
import cn.hanghui.outapi.platform.tenant.entity.enums.ModeEnum;
import cn.hanghui.outapi.platform.tenant.entity.enums.SystemTypeEnum;
import cn.hanghui.outapi.platform.tenant.entity.po.*;
import cn.hanghui.outapi.platform.tenant.mapper.*;
import cn.hanghui.outapi.platform.tenant.service.IotDeviceConfigTemplateService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @ClassName IotDeviceConfigTemplateServiceImpl
 * @Author WXG
 * @Date 2023/12/29 9:13
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class IotDeviceConfigTemplateServiceImpl implements IotDeviceConfigTemplateService {

    private final IotDeviceConfigTemplateMapper iotDeviceConfigTemplateMapper;
    private final ApplicationTypeMapper applicationTypeMapper;
    private final DeviceModelMapper deviceModelMapper;
    private final AmpeMapper ampeMapper;
    private final TenantMapper tenantMapper;
    private final UserLibMapper userLibMapper;
    private final SceneMapper sceneMapper;
    private final CommonImpl commonImpl;

    @Override
    public Boolean edit(IotDeviceConfigTemplateDto dto) {
        this.checkDto(dto);
        Long iotDeviceConfigTemplateId = dto.getIotDeviceConfigTemplateId();
        if(iotDeviceConfigTemplateId == null){
            IotDeviceConfigTemplate iotDeviceConfigTemplate = BeanUtil.copyProperties(dto, IotDeviceConfigTemplate.class);
            iotDeviceConfigTemplateMapper.insert(iotDeviceConfigTemplate);
        }else {
            IotDeviceConfigTemplate base = iotDeviceConfigTemplateMapper.selectById(iotDeviceConfigTemplateId);
            ClassUtil.throwBusinessException(ObjectUtil.isNull(base),"iot模版不存在");
            BeanUtil.copyProperties(dto,base);
            iotDeviceConfigTemplateMapper.updateById(base);
        }
        return true;
    }
    private void checkDto(IotDeviceConfigTemplateDto dto) {
        //应用类型
        ApplicationType applicationType = applicationTypeMapper.selectById(dto.getApplicationTypeId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType),"应用类型不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(applicationType.getIsDeleted()),"购买方已删除");
        //设备类型（硬件）
        DeviceModel deviceModelHardware = deviceModelMapper.selectById(dto.getDeviceModelHardwareId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware),"设备类型（硬件）不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelHardware.getIsDeleted()),"设备类型（硬件）已删除");
        //设备类型（环境）
        DeviceModel deviceModelEnvironment = deviceModelMapper.selectById(dto.getDeviceModelEnvironmentId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment),"设备类型（环境）不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(deviceModelEnvironment.getIsDeleted()),"设备类型（环境）已删除");
        //ampe平台
        Ampe ampe = ampeMapper.selectById(dto.getAmpeId());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(ampe),"ampe平台不存在");
        ClassUtil.throwBusinessException(ObjectUtil.isNull(ampe.getIsDeleted()),"ampe平台已删除");
        //服务商平台
        if(ObjectUtil.isNotNull(dto.getTenantId())){
            Tenant tenant = tenantMapper.selectById(dto.getTenantId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(tenant), "服务商平台不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(tenant.getIsDeleted()), "服务商平台已删除");
        }
        //用户库
        if(ObjectUtil.isNotNull(dto.getUserLibId())){
            UserLib userLib = userLibMapper.selectById(dto.getUserLibId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(userLib), "用户库不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(userLib.getIsDeleted()), "用户库已删除");
        }
        //场景
        if(ObjectUtil.isNotNull(dto.getSceneId())){
            Scene scene = sceneMapper.selectById(dto.getSceneId());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(scene), "场景不存在");
            ClassUtil.throwBusinessException(ObjectUtil.isNull(scene.getIsDeleted()), "场景已删除");
        }
        //模式
        if(ObjectUtil.isNotNull(dto.getMode())){
            ModeEnum modeEnum = ModeEnum.getEnumByCode(dto.getMode());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(modeEnum), "模式不存在");
        }
        //系统类型
        SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(dto.getSystemTypeCode());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(systemTypeEnum),"系统类型不存在");
        //摄像头类型
        CameraTypeEnum cameraTypeEnum = CameraTypeEnum.getEnumByCode(dto.getCameraType());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(cameraTypeEnum),"摄像头类型不存在");
        //摄像头品牌
        CameraBrandEnum cameraBrandEnum = CameraBrandEnum.getEnumByCode(dto.getCameraBrand());
        ClassUtil.throwBusinessException(ObjectUtil.isNull(cameraBrandEnum),"摄像品牌不存在");
        //身份证阅读器品牌
        if (Preconditions.isNotBlank(dto.getIdCardReaderBrand())) {
            IdCardReaderBrandEnum idCardReaderBrandEnum = IdCardReaderBrandEnum.queryEnumByCode(dto.getIdCardReaderBrand());
            ClassUtil.throwBusinessException(ObjectUtil.isNull(idCardReaderBrandEnum), RestCode.FAIL.getCode(),"身份证阅读器品牌不存在");
        }
    }
    @Override
    public List<IotDeviceConfigTemplateLessVo> iotDeviceConfigTemplateList() {
        LambdaQueryWrapper<IotDeviceConfigTemplate> wrapper = new LambdaQueryWrapper<>();
        //查询的基础条件
        wrapper.eq(IotDeviceConfigTemplate::getIsDeleted,Boolean.FALSE);
        wrapper.orderByDesc(IotDeviceConfigTemplate::getId);
        List<IotDeviceConfigTemplate> iotDeviceConfigTemplateList = iotDeviceConfigTemplateMapper.selectList(wrapper);

        return iotDeviceConfigTemplateList.stream().map(p-> new IotDeviceConfigTemplateLessVo()
                .setIotDeviceConfigTemplateId(p.getId())
                .setTemplateName(p.getTemplateName())).collect(Collectors.toList());
    }

    @Override
    public IPage<IotDeviceConfigTemplateVo> iotDeviceConfigTemplatePage(IotDeviceConfigTemplateSearch dto) {
        Page<IotDeviceConfigTemplate> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        LambdaQueryWrapper<IotDeviceConfigTemplate> wrapper = this.getWrapper(dto);
        IPage<IotDeviceConfigTemplate> iPage = iotDeviceConfigTemplateMapper.selectPage(page, wrapper);

        Map<Long, ApplicationType> applicationTypeMap = commonImpl.getApplicationTypeMap(iPage, IotDeviceConfigTemplate::getApplicationTypeId);
        Map<Long, DeviceModel> deviceModelHardwareMap = commonImpl.getDeviceModelMap(iPage, IotDeviceConfigTemplate::getDeviceModelHardwareId);
        Map<Long, DeviceModel> deviceModelEnvironmentMap = commonImpl.getDeviceModelMap(iPage, IotDeviceConfigTemplate::getDeviceModelEnvironmentId);
        Map<Long, Ampe> ampeMap = commonImpl.getAmpeMap(iPage, IotDeviceConfigTemplate::getAmpeId);
        Map<Long, Tenant> tenantMap = commonImpl.getTenantMap(iPage, IotDeviceConfigTemplate::getTenantId);
        Map<Long, UserLib> userLibMap = commonImpl.getUserLibMap(iPage, IotDeviceConfigTemplate::getUserLibId);
        Map<Long, Scene> sceneMap = commonImpl.getSceneMap(iPage, IotDeviceConfigTemplate::getSceneId);

        return iPage.convert(t -> {
            IotDeviceConfigTemplateVo item = BeanUtil.copyProperties(t, IotDeviceConfigTemplateVo.class);
            item.setIotDeviceConfigTemplateId(t.getId());
            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(ampeMap.containsKey(t.getAmpeId())){
                item.setAmpeName(ampeMap.get(t.getAmpeId()).getAmpeName());
            }
            if(tenantMap.containsKey(t.getTenantId())){
                item.setTenantName(tenantMap.get(t.getTenantId()).getName());
            }
            if(userLibMap.containsKey(t.getUserLibId())){
                item.setUserLibName(userLibMap.get(t.getUserLibId()).getUserLibName());
            }
            if(sceneMap.containsKey(t.getSceneId())){
                item.setSceneName(sceneMap.get(t.getSceneId()).getSceneName());
            }
            SystemTypeEnum systemTypeEnum = SystemTypeEnum.getEnumByCode(t.getSystemTypeCode());
            if(ObjectUtil.isNotNull(systemTypeEnum)){
                item.setSystemType(systemTypeEnum.getDesc());
            }

            return item;
        });
    }
    private LambdaQueryWrapper<IotDeviceConfigTemplate> getWrapper(IotDeviceConfigTemplateSearch dto) {
        LambdaQueryWrapper<IotDeviceConfigTemplate> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.eq(ObjectUtil.isNotNull(dto.getIotDeviceConfigTemplateId()), IotDeviceConfigTemplate::getId,dto.getIotDeviceConfigTemplateId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getApplicationTypeId()), IotDeviceConfigTemplate::getApplicationTypeId,dto.getApplicationTypeId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelHardwareId()), IotDeviceConfigTemplate::getDeviceModelHardwareId,dto.getDeviceModelHardwareId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getDeviceModelEnvironmentId()), IotDeviceConfigTemplate::getDeviceModelEnvironmentId,dto.getDeviceModelEnvironmentId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getSystemTypeCode()), IotDeviceConfigTemplate::getSystemTypeCode,dto.getSystemTypeCode());
        wrapper.eq(ObjectUtil.isNotNull(dto.getAmpeId()), IotDeviceConfigTemplate::getAmpeId,dto.getAmpeId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getTenantId()), IotDeviceConfigTemplate::getTenantId,dto.getTenantId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getUserLibId()), IotDeviceConfigTemplate::getUserLibId,dto.getUserLibId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getSceneId()), IotDeviceConfigTemplate::getSceneId,dto.getSceneId());
        wrapper.eq(ObjectUtil.isNotNull(dto.getMode()), IotDeviceConfigTemplate::getMode,dto.getMode());
        //查询的基础条件
        wrapper.eq(IotDeviceConfigTemplate::getIsDeleted,Boolean.FALSE);
        wrapper.orderByDesc(IotDeviceConfigTemplate::getId);
        return wrapper;
    }
    @Override
    public Boolean iotDeviceConfigTemplateDelete(Long iotDeviceConfigTemplateId) {
        IotDeviceConfigTemplate iotDeviceConfigTemplate = iotDeviceConfigTemplateMapper.selectById(iotDeviceConfigTemplateId);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(iotDeviceConfigTemplate),"iot模版不存在");
        ClassUtil.throwBusinessException(iotDeviceConfigTemplate.getIsDeleted(),"iot模版已删除");
        iotDeviceConfigTemplateMapper.deleteById(iotDeviceConfigTemplateId);
        return Boolean.TRUE;
    }
    @Override
    public IotDeviceConfigTemplateVo templateDetail(Long iotDeviceConfigTemplateId) {
        IotDeviceConfigTemplate iotDeviceConfigTemplate = iotDeviceConfigTemplateMapper.selectById(iotDeviceConfigTemplateId);
        ClassUtil.throwBusinessException(ObjectUtil.isNull(iotDeviceConfigTemplate),"iot模版不存在");
        ClassUtil.throwBusinessException(iotDeviceConfigTemplate.getIsDeleted(),"iot模版已删除");
        return BeanUtil.copyProperties(iotDeviceConfigTemplate,IotDeviceConfigTemplateVo.class);
    }
}
