package com.usky.alarm.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.dyvmsapi.model.v20170525.SingleCallByTtsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.alarm.domain.*;
import com.usky.alarm.mapper.BaseAlarmMapper;
import com.usky.alarm.mapper.BaseAlarmNoticeResultMapper;
import com.usky.alarm.mapper.SysUserMapper;
import com.usky.alarm.service.*;
import com.usky.alarm.service.config.smsmessage.SmsMessage;
import com.usky.alarm.service.config.voice.VoiceNotice;
import com.usky.alarm.service.config.websocket.WebSocket;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.mybatis.core.AbstractCrudService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 统一告警表 服务实现类
 * </p>
 *
 * @author han
 * @since 2023-09-22
 */
@Slf4j
@Service
public class BaseAlarmServiceImpl extends AbstractCrudService<BaseAlarmMapper, BaseAlarm> implements BaseAlarmService {

    @Autowired
    private DmpProductService dmpProductService;

    @Autowired
    private DmpDeviceService dmpDeviceInfoService;

    @Autowired
    private BaseFacilityDeviceService baseFacilityDeviceService;

    @Autowired
    private BaseAlarmNoticeService baseAlarmNoticeService;

    @Autowired
    private BaseAlarmNoticeResultService baseAlarmNoticeResultService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private WebSocket webSocket;

    @Autowired
    private VoiceNotice voiceNotice;

    @Autowired
    private BaseAlarmNoticeResultMapper baseAlarmNoticeResultMapper;

    @Override
    public boolean add(BaseAlarm baseAlarm) throws ClientException {
        baseAlarm.setHandleStatus(0);
        if (StringUtils.isNotBlank(baseAlarm.getProductCode()) && StringUtils.isNotBlank(baseAlarm.getDeviceId()) && StringUtils.isNotBlank(baseAlarm.getAlarmType())){
            LambdaQueryWrapper<DmpProduct> lambdaQuery = Wrappers.lambdaQuery();
            lambdaQuery.eq(DmpProduct::getProductCode,baseAlarm.getProductCode())
                    .eq(DmpProduct::getDeleteFlag,0);
            List<DmpProduct> records = dmpProductService.list(lambdaQuery);
            LambdaQueryWrapper<BaseFacilityDevice> lambdaQuery1 = Wrappers.lambdaQuery();
            lambdaQuery1.eq(BaseFacilityDevice::getDeviceId,baseAlarm.getDeviceId());
            List<BaseFacilityDevice> records1 = baseFacilityDeviceService.list(lambdaQuery1);
            LambdaQueryWrapper<DmpDevice> lambdaQuery2 = Wrappers.lambdaQuery();
            lambdaQuery2.eq(DmpDevice::getDeviceId,baseAlarm.getDeviceId())
                    .eq(DmpDevice::getProductCode,baseAlarm.getProductCode())
                    .eq(DmpDevice::getServiceStatus,2)
                    .eq(DmpDevice::getDeleteFlag,0);
            List<DmpDevice> records2 = dmpDeviceInfoService.list(lambdaQuery2);
            BaseAlarmType baseAlarmType = baseMapper.getAlarmTypeOne(baseAlarm.getAlarmType());
            if(records.size()>0 && baseAlarmType !=null && records2.size()>0){
                baseAlarm.setTenantId(records.get(0).getTenantId());
                if (StringUtils.isNotBlank(baseAlarm.getHandleBy()) || StringUtils.isNotBlank(baseAlarm.getHandlePhone())) {
                    baseAlarm.setHandleStatus(1);
                    LambdaQueryWrapper<BaseAlarm> queryWrapper = Wrappers.lambdaQuery();
                    queryWrapper.eq(BaseAlarm::getDeviceId, baseAlarm.getDeviceId())
                            .eq(BaseAlarm::getAlarmType, baseAlarm.getAlarmType())
                            .eq(BaseAlarm::getAlarmAddress, baseAlarm.getAlarmAddress())
                            .eq(BaseAlarm::getAlarmGrade, baseAlarm.getAlarmGrade());
                    return this.update(baseAlarm, queryWrapper);
                } else {
                    boolean saveResult = this.save(baseAlarm);
                    Integer alarmId = baseAlarm.getId();
                    if (records1.size() > 0) {
                        baseAlarm.setFacilityId(records1.get(0).getFacilityId());
                    }
                    baseAlarm.setDeviceName(records2.get(0).getDeviceName());
                    baseAlarm.setTypeImg(baseAlarmType.getTypeImg());
                    baseAlarm.setAlarmType(baseAlarmType.getTypeName());
                    baseAlarm.setAlarmTime1(baseAlarm.getAlarmTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd " +
                            "HH:mm:ss")));
                    webSocket.sendMessage(baseAlarm, records.get(0).getTenantId().toString());
                    LambdaQueryWrapper<BaseAlarmNotice> lambdaQuery3 = Wrappers.lambdaQuery();
                    lambdaQuery3.eq(BaseAlarmNotice::getProductCode,baseAlarm.getProductCode())
                            .eq(BaseAlarmNotice::getTypeCode,baseAlarmType.getTypeCode())
                            .eq(BaseAlarmNotice::getDeleteFlag,0);
                    List<BaseAlarmNotice> records3 = baseAlarmNoticeService.list(lambdaQuery3);
                    if (records3.size()>0){
                        Integer saveAlarmResult = baseAlarmNoticeResultService.send(baseAlarm,records3,alarmId,records,baseAlarmType,records2);
                        log.info("异步发送告警通知数据: {}", baseAlarm);
                    }
                    return saveResult;
                }
            }else {
                //throw new BusinessException("告警数据投递失败，请检查产品编码、设备编号、告警类型，是否有误;设备是否激活");
                log.error("告警数据投递失败，请检查产品编码、设备编号、告警类型，是否有误;设备是否激活");
                return false;
            }
        }else {
            //throw new BusinessException("告警数据投递失败，请检查产品编码、设备编号、告警类型，不能为空");
            log.error("告警数据投递失败，请检查产品编码、设备编号、告警类型，不能为空");
            return false;
        }
    }

//    public SingleCallByTtsResponse sendCVoice(String phone,String visitorName,String gz,String bjsj) throws ClientException {
//        SingleCallByTtsResponse code = voiceNotice.sendCVoice(phone,visitorName,gz,bjsj);
//        return code;
//    }
}
