package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TFacility;
import com.ruoyi.system.domain.TServiceManage;
import com.ruoyi.system.domain.TUserProfile;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.mapper.TFacilityMapper;
import com.ruoyi.system.mapper.TUserProfileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TDeviceListMapper;
import com.ruoyi.system.domain.TDeviceList;
import com.ruoyi.system.service.ITDeviceListService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备列Service业务层处理
 *
 * @author zhengjie
 * @date 2023-08-30
 */
@Service
public class TDeviceListServiceImpl implements ITDeviceListService {
    @Autowired
    private TDeviceListMapper tDeviceListMapper;
    @Autowired
    private TUserProfileMapper tUserProfileMapper;
    @Autowired
    private TFacilityMapper tFacilityMapper;

    /**
     * 查询设备列
     *
     * @param id 设备列主键
     * @return 设备列
     */
    @Override
    public TDeviceList selectTDeviceListById(Integer id) {
        return tDeviceListMapper.selectTDeviceListById(id);
    }

    /**
     * 查询设备列列表
     *
     * @param tDeviceList 设备列
     * @return 设备列
     */
    @Override
    public List<TDeviceList> selectTDeviceListList(TDeviceList tDeviceList) {
        return tDeviceListMapper.selectTDeviceListList(tDeviceList);
    }

    @Override
    public List<RateDto> selectTDeviceByDeviceId(String device_id_code) {
        return tDeviceListMapper.selectTDeviceByDeviceId(device_id_code);
    }

    @Override
    public List<RateDto> selectTDeviceByBlood(String device_id_code) {
        return tDeviceListMapper.selectTDeviceByBlood(device_id_code);
    }

    @Override
    public List<RateDto> selectTDeviceByOxygen(String device_id_code) {
        return tDeviceListMapper.selectTDeviceByOxygen(device_id_code);
    }

    @Override
    public List<RateDto> selectTDeviceByTemp(String device_id_code) {
        return tDeviceListMapper.selectTDeviceByTemp(device_id_code);
    }

    @Override
    public List<RateDto> selectTDeviceByStep(String device_id_code) {
        return tDeviceListMapper.selectTDeviceByStep(device_id_code);
    }

    @Override
    public List<MessageDto> selectTDeviceByMessage(String device_id_code) {
        return tDeviceListMapper.selectTDeviceByMessage(device_id_code);
    }

    @Override
    public List<MessageLogDto> selectTDeviceByMessageLog(MessageLogDto messageLogDto) {
        return tDeviceListMapper.selectTDeviceByMessageLog(messageLogDto);
    }

    /**
     * 新增设备列
     *
     * @param tDeviceList 设备列
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTDeviceList(TDeviceList tDeviceList) {
        /**
         * TODO 后期在bean中校验字段是否为空
         */
        //新增设备
        if (tDeviceList == null) {
            throw new ServiceException("新增设备数据不能为空！");
        }
        //设备是否绑定用户
        if (tDeviceList.getUserid() == null) {
            throw new ServiceException("新增设备未绑定用户！");
        }
        //工厂
        if (tDeviceList.getFactory() == null) {
            throw new ServiceException("新增设备未选择工厂！");
        }
        //设备型号
        if (tDeviceList.getDeviceModel() == null) {
            throw new ServiceException("新增设备未选择设备型号！");
        }
        //设备标识ID
        if (tDeviceList.getDeviceId() == null || StringUtils.isEmpty(tDeviceList.getDeviceId())) {
            throw new ServiceException("新增设备未填写设备标识ID！");
        }
        //发放方式
        if (tDeviceList.getGrantType() == null) {
            throw new ServiceException("新增设备未选择发放方式！");
        }
        //如果是购买方式
        if (tDeviceList.getGrantType() == 1) {
            //设备标识ID
            if (tDeviceList.getPrice() == null || StringUtils.isEmpty(tDeviceList.getPrice())) {
                throw new ServiceException("新增设备未填写销售价格！");
            }
//            //服务费用
//            if (tDeviceList.getCost() == null || StringUtils.isEmpty(tDeviceList.getCost())) {
//                throw new ServiceException("新增设备未填写服务费用！");
//            }
            //支付方式
            if (tDeviceList.getPayment() == null) {
                throw new ServiceException("新增设备未选择支付方式！");
            }
        }
        //根据设备表示ID查询数据库中的设备信息
        List<TDeviceList> rateDtoList = tDeviceListMapper.selectTDeviceByDeviceIdCode(tDeviceList.getDeviceId());
        if (rateDtoList != null && !rateDtoList.isEmpty()) {
            //如果表中有该设备则提示
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("新增设备信息已存在");
            //如果有设备标识ID，则提示
            if (!StringUtils.isEmpty(tDeviceList.getDeviceId())) {
                stringBuilder.append(", 设备标识ID：" + tDeviceList.getDeviceId());
            }
            stringBuilder.append("!");
            throw new ServiceException(stringBuilder.toString());
        }
        //新增时间
        tDeviceList.setCreateTime(DateUtils.getNowDate());
        int rows = tDeviceListMapper.insertTDeviceList(tDeviceList);
        TFacility tFacility = new TFacility();
        //设备编号
        if (tDeviceList.getDeviceId() != null && !StringUtils.isEmpty(tDeviceList.getDeviceId())) {
            tFacility.setCode(tDeviceList.getDeviceId());
        }
        //设备SIM卡号
        if (tDeviceList.getSimCode() != null && !StringUtils.isEmpty(tDeviceList.getSimCode())) {
            tFacility.setTelno(tDeviceList.getSimCode());
        }
        //设备序列号
        if (tDeviceList.getSerialNumber() != null && !StringUtils.isEmpty(tDeviceList.getSerialNumber())) {
            tFacility.setIccid(tDeviceList.getSerialNumber());
        }
        tFacilityMapper.insertTFacility(tFacility);
        return rows;
    }

    /**
     * 修改设备列
     *
     * @param tDeviceList 设备列
     * @return 结果
     */
    @Override
    public int updateTDeviceList(TDeviceList tDeviceList) {
        /**
         * TODO 后期在bean中校验字段是否为空
         */
        //修改设备
        if (tDeviceList == null) {
            throw new ServiceException("修改设备数据不能为空！");
        }
        //设备是否绑定用户
        if (tDeviceList.getUserid() == null) {
            throw new ServiceException("修改设备未绑定用户！");
        }
        //工厂
        if (tDeviceList.getFactory() == null) {
            throw new ServiceException("修改设备未选择工厂！");
        }
        //设备型号
        if (tDeviceList.getDeviceModel() == null) {
            throw new ServiceException("修改设备未选择设备型号！");
        }
        //设备标识ID
        if (tDeviceList.getDeviceId() == null || StringUtils.isEmpty(tDeviceList.getDeviceId())) {
            throw new ServiceException("修改设备未填写设备标识ID！");
        }
        //发放方式
        if (tDeviceList.getGrantType() == null) {
            throw new ServiceException("修改设备未选择发放方式！");
        }
        //如果是购买方式
        if (tDeviceList.getGrantType() == 1) {
            //设备标识ID
            if (tDeviceList.getPrice() == null || StringUtils.isEmpty(tDeviceList.getPrice())) {
                throw new ServiceException("修改设备未填写销售价格！");
            }
//            //服务费用
//            if (tDeviceList.getCost() == null || StringUtils.isEmpty(tDeviceList.getCost())) {
//                throw new ServiceException("修改设备未填写服务费用！");
//            }
            //支付方式
            if (tDeviceList.getPayment() == null) {
                throw new ServiceException("修改设备未选择支付方式！");
            }
        }

        //根据设备表示ID查询数据库中的设备信息
        TDeviceList deviceListBean = tDeviceListMapper.selectTDeviceListById(tDeviceList.getId());
        if (deviceListBean == null) {
            //如果表中没有该设备则提示
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("修改设备信息不存在!");
            throw new ServiceException(stringBuilder.toString());
        }
        //判断用户是否修改设备标识ID
        if (!StringUtils.equals(deviceListBean.getDeviceId(), tDeviceList.getDeviceId())) {
            throw new ServiceException("修改设备信息禁止修改设备标识ID！");
        }
        //修改时间
        tDeviceList.setUpdateTime(DateUtils.getNowDate());
        int rows = tDeviceListMapper.updateTDeviceList(tDeviceList);
        TFacility tFacility = new TFacility();
        //设备编号
        if (tDeviceList.getDeviceId() != null && !StringUtils.isEmpty(tDeviceList.getDeviceId())) {
            tFacility.setCode(tDeviceList.getDeviceId());
        }
        //设备SIM卡号
        if (tDeviceList.getSimCode() != null && !StringUtils.isEmpty(tDeviceList.getSimCode())) {
            tFacility.setTelno(tDeviceList.getSimCode());
        }
        //设备序列号
        if (tDeviceList.getSerialNumber() != null && !StringUtils.isEmpty(tDeviceList.getSerialNumber())) {
            tFacility.setIccid(tDeviceList.getSerialNumber());
        }
        tFacilityMapper.deleteTFacilityByCode(tFacility.getCode());
        tFacilityMapper.insertTFacility(tFacility);
        return rows;
    }

    /**
     * 批量删除设备列
     *
     * @param ids 需要删除的设备列主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTDeviceListByIds(Integer[] ids) {
        if (ids == null) {
            return 0;
        }
        for (Integer id : ids) {
            TDeviceList deviceList = tDeviceListMapper.selectTDeviceListById(id);
            if (deviceList != null && deviceList.getDeviceId() != null && !StringUtils.isEmpty(deviceList.getDeviceId())) {
                tFacilityMapper.deleteTFacilityByCode(deviceList.getDeviceId());
            }
        }
        return tDeviceListMapper.deleteTDeviceListByIds(ids);
    }

    /**
     * 删除设备列信息
     *
     * @param id 设备列主键
     * @return 结果
     */
    @Override
    public int deleteTDeviceListById(Integer id) {
        TDeviceList tDevice = this.selectTDeviceListById(id);
        TFacility tFacility = tFacilityMapper.selectTFacilityByCode(tDevice.getDeviceId());
        if (StringUtils.isNotNull(tFacility)) {
            tFacilityMapper.deleteTFacilityById(tFacility.getId());
        }
        return tDeviceListMapper.deleteTDeviceListById(id);
    }

    @Override
    public String importTDeviceList(List<TDeviceList> tDeviceLists) {

        if (StringUtils.isNull(tDeviceLists) || tDeviceLists.size() == 0) {
            throw new ServiceException("导入设备列表信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TDeviceList tDeviceList : tDeviceLists) {
            try {
                TUserProfile user = tUserProfileMapper.selectTUserProfileBySfzId(tDeviceList.getSfzid());
                TDeviceList device = tDeviceListMapper.selectTDeviceListListByDeviceId(tDeviceList.getDeviceId());
                if (StringUtils.isNotNull(user) && StringUtils.isNull(device)) {
                    tDeviceList.setUserid(user.getId());
                    tDeviceList.setSfzid(user.getSfzid());
                    tDeviceList.setTelno(user.getTelOne());
                    this.insertTDeviceList(tDeviceList);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "设备列表信息" + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "设备列表信息" + " 信息不完整");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "设备列表信息" + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }

    @Transactional
    @Override
    public String importTDeviceListV2(List<TDeviceList> tDeviceLists) {
        if (tDeviceLists == null || tDeviceLists.isEmpty()) {
            throw new ServiceException("导入设备列表信息数据不能为空！");
        }
        //批量导入设备数据
        for (TDeviceList deviceListEntity : tDeviceLists) {
            //判断提交数据格式是否正确
            if (deviceListEntity.getSfzid() == null || deviceListEntity.getSfzid().isEmpty()) {
                throw new ServiceException("导入设备数信息身份证号格式异常！");
            }
            //根据身份证号查询数据库中的用户信息
            TUserProfile user = tUserProfileMapper.selectTUserProfileBySfzId(deviceListEntity.getSfzid());
            if (user == null) {
                //如果表中有该用户则提示
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("导入设备数信息未匹配到用户");
                //如果有设备标识ID，则提示
                if (!StringUtils.isEmpty(deviceListEntity.getDeviceId())) {
                    stringBuilder.append(", 设备标识ID：" + deviceListEntity.getDeviceId());
                }
                //如果有设备标识ID，则提示
                if (!StringUtils.isEmpty(deviceListEntity.getName())) {
                    stringBuilder.append(", 用户名：" + deviceListEntity.getName());
                }
                //如果有身份证号，则提示
                if (!StringUtils.isEmpty(deviceListEntity.getSfzid())) {
                    stringBuilder.append(", 身份证号：" + deviceListEntity.getSfzid());
                }
                stringBuilder.append("!");
                throw new ServiceException(stringBuilder.toString());
            }
            //根据设备ID查询数据库中的设备信息
            List<TFacility> facilityList = tFacilityMapper.selectTDeviceListListByDeviceId(deviceListEntity.getDeviceId());
            if (facilityList != null && !facilityList.isEmpty()) {
                //如果表中有该用户则提示
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("导入设备信息已存在");
                //如果有设备标识ID，则提示
                if (!StringUtils.isEmpty(deviceListEntity.getDeviceId())) {
                    stringBuilder.append(", 设备标识ID：" + deviceListEntity.getDeviceId());
                }
                //如果有设备标识ID，则提示
                if (!StringUtils.isEmpty(deviceListEntity.getName())) {
                    stringBuilder.append(", 用户名：" + deviceListEntity.getName());
                }
                //如果有身份证号，则提示
                if (!StringUtils.isEmpty(deviceListEntity.getSfzid())) {
                    stringBuilder.append(", 身份证号：" + deviceListEntity.getSfzid());
                }
                stringBuilder.append("!");
                throw new ServiceException(stringBuilder.toString());
            }
            //根据设备ID查询数据库中的设备信息
            TDeviceList device = tDeviceListMapper.selectTDeviceListListByDeviceId(deviceListEntity.getDeviceId());
            if (device != null) {
                //如果表中有该用户则提示
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("导入设备信息已存在");
                //如果有设备标识ID，则提示
                if (!StringUtils.isEmpty(deviceListEntity.getDeviceId())) {
                    stringBuilder.append(", 设备标识ID：" + deviceListEntity.getDeviceId());
                }
                //如果有设备标识ID，则提示
                if (!StringUtils.isEmpty(deviceListEntity.getName())) {
                    stringBuilder.append(", 用户名：" + deviceListEntity.getName());
                }
                //如果有身份证号，则提示
                if (!StringUtils.isEmpty(deviceListEntity.getSfzid())) {
                    stringBuilder.append(", 身份证号：" + deviceListEntity.getSfzid());
                }
                stringBuilder.append("!");
                throw new ServiceException(stringBuilder.toString());
            }
            deviceListEntity.setUserid(user.getId());
            deviceListEntity.setSfzid(user.getSfzid());
            deviceListEntity.setTelno(user.getTelOne());
            this.insertTDeviceList(deviceListEntity);
        }
        StringBuilder successMsg = new StringBuilder();
        successMsg.append("恭喜您，数据已全部导入成功！共 " + tDeviceLists.size() + " 条，数据如下：");
        return successMsg.toString();
    }

    /**
     * 判断报警信息
     *
     * @param alarm_type 报警类型
     * @return 结果
     */
    @Override
    public String checkMessage(Integer alarm_type) {
        switch (alarm_type) {
            case 16:
                return "SOS报警";
            case 17:
                return "低电报警";
            case 20:
                return "手环拆除报警";
            case 21:
                return "跌倒报警";
            case 22:
                return "心率异常报警";
            case 23:
                return "血压异常报警";
            case 24:
                return "体温异常报警";
            case 25:
                return "血氧异常报警";
            default:
                return "无效";
        }
    }

    @Override
    public int deviceValue(CallPoliceDto callPoliceDto) {
        if (StringUtils.isNotNull(callPoliceDto)) {
            if (StringUtils.isNotNull(callPoliceDto.getShouhuan_blood_high_max())) {
                tDeviceListMapper.updateTSettingshouhuan_blood_high_max(callPoliceDto.getShouhuan_blood_high_max());
            }
            if (StringUtils.isNotNull(callPoliceDto.getShouhuan_blood_high_min())) {
                tDeviceListMapper.updateTSettingshouhuan_blood_high_min(callPoliceDto.getShouhuan_blood_high_min());
            }
            if (StringUtils.isNotNull(callPoliceDto.getShouhuan_blood_low_max())) {
                tDeviceListMapper.updateTSettingshouhuan_blood_low_max(callPoliceDto.getShouhuan_blood_low_max());
            }
            if (StringUtils.isNotNull(callPoliceDto.getShouhuan_blood_low_min())) {
                tDeviceListMapper.updateTSettingshouhuan_blood_low_min(callPoliceDto.getShouhuan_blood_low_min());
            }
            if (StringUtils.isNotNull(callPoliceDto.getShouhuan_body_max())) {
                tDeviceListMapper.updateTSettingshouhuan_body_max(callPoliceDto.getShouhuan_body_max());
            }
            if (StringUtils.isNotNull(callPoliceDto.getShouhuan_body_min())) {
                tDeviceListMapper.updateTSettingshouhuan_body_min(callPoliceDto.getShouhuan_body_min());
            }
            if (StringUtils.isNotNull(callPoliceDto.getShouhuan_oxygen_max())) {
                tDeviceListMapper.updateTSettingshouhuan_oxygen_max(callPoliceDto.getShouhuan_oxygen_max());
            }
            if (StringUtils.isNotNull(callPoliceDto.getShouhuan_oxygen_min())) {
                tDeviceListMapper.updateTSettingshouhuan_oxygen_min(callPoliceDto.getShouhuan_oxygen_min());
            }
            if (StringUtils.isNotNull(callPoliceDto.getShouhuan_heart_max())) {
                tDeviceListMapper.updateTSettingshouhuan_heart_max(callPoliceDto.getShouhuan_heart_max());
            }
            if (StringUtils.isNotNull(callPoliceDto.getShouhuan_heart_min())) {
                tDeviceListMapper.updateTSettingshouhuan_heart_min(callPoliceDto.getShouhuan_heart_min());
            }
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public List<DeviceTypeDto> selectDeviceListDto() {
        return tDeviceListMapper.selectDeviceListDto();
    }

    @Override
    public Integer selectDeviceListCount() {
        return tDeviceListMapper.selectDeviceListCount();
    }

    @Override
    public List<AddDeviceDto> selectAddDevice() {
        return tDeviceListMapper.selectAddDevice();
    }

    @Override
    public Integer selectTDeviceListBandUser() {
        return tDeviceListMapper.selectTDeviceListBandUser();
    }
}
