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.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.alarm.domain.*;
import com.usky.alarm.mapper.BaseAlarmNoticeResultMapper;
import com.usky.alarm.mapper.SysUserMapper;
import com.usky.alarm.service.BaseAlarmNoticeResultService;
import com.usky.alarm.service.config.voice.VoiceNotice;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
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-25
 */
@Slf4j
@Service
public class BaseAlarmNoticeResultServiceImpl extends AbstractCrudService<BaseAlarmNoticeResultMapper, BaseAlarmNoticeResult> implements BaseAlarmNoticeResultService {
    @Autowired
    private VoiceNotice voiceNotice;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public CommonPage<BaseAlarmNoticeResult> resultInfo(String receiver, Integer alarmId, Integer current, Integer size) {
        IPage<BaseAlarmNoticeResult> page = new Page<>(current, size);
        LambdaQueryWrapper<BaseAlarmNoticeResult> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.like(StringUtils.isNotBlank(receiver),BaseAlarmNoticeResult::getReceiver, receiver)
                .eq(BaseAlarmNoticeResult::getAlarmId, alarmId);
//                .eq(BaseAlarmNoticeResult::getTenantId, SecurityUtils.getTenantId());
        page = this.page(page,queryWrapper1);
        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getCurrent(),page.getSize());
    }

    //异步多线程调用
    @Async("asyncServiceExecutor")
    public Integer send(BaseAlarm baseAlarm, List<BaseAlarmNotice> records3, Integer alarmId, List<DmpProduct> records,
                        BaseAlarmType baseAlarmType, List<DmpDevice> records2) throws ClientException {
        log.info("start asyncServiceExecutor--------------------");
        String[] array = records3.get(0).getReceiver1().split(",");
        Integer saveAlarmResult = 0;
        for (String s : array) {
            LambdaQueryWrapper<SysUser> lambdaQuery4 = Wrappers.lambdaQuery();
            lambdaQuery4.eq(SysUser::getUserId,s)
                    .eq(SysUser::getDelFlag,0);
            SysUser sysUser = sysUserMapper.selectOne(lambdaQuery4);
            BaseAlarmNoticeResult baseAlarmNoticeResult = new BaseAlarmNoticeResult();
            baseAlarmNoticeResult.setReceiver(sysUser.getNickName());
            baseAlarmNoticeResult.setReceiverPhone(sysUser.getPhonenumber());
            baseAlarmNoticeResult.setAlarmId(alarmId);
            baseAlarmNoticeResult.setNoticeTime(LocalDateTime.now());
            baseAlarmNoticeResult.setNoticeContent(records.get(0).getProductName()+","+baseAlarmType.getTypeName()+","+baseAlarm.getAlarmTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd " +
                    "HH:mm:ss")));
            baseAlarmNoticeResult.setTenantId(records.get(0).getTenantId());
            if (records3.get(0).getNoticeMethod().contains("电话")){
                SingleCallByTtsResponse code = voiceNotice.sendCVoice(sysUser.getPhonenumber(),
                        records.get(0).getProductName(),baseAlarmType.getTypeName(),
                        baseAlarm.getAlarmTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd " +
                                "HH:mm:ss")));
                baseAlarmNoticeResult.setNoticeType(3);
                if(code.getCode() != null && code.getCode().equals("OK")) {
                    //请求成功
                    baseAlarmNoticeResult.setNoticeResult(1);
                }else {
                    baseAlarmNoticeResult.setNoticeResult(2);
                }
                saveAlarmResult = baseMapper.insert(baseAlarmNoticeResult);
            }
            if (records3.get(0).getNoticeMethod().contains("短信")){
                DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", "LTAI5tH3VvRL5BUkovCokHJX", "SaaWUouNqvcA0C746gcNOH9m6SRYN4");
                IAcsClient client = new DefaultAcsClient(profile);
                SendSmsRequest request = new SendSmsRequest();
                request.setPhoneNumbers(sysUser.getPhonenumber());//接收短信的手机号码
                request.setSignName("上海永天科技股份有限公司");//短信签名名称
                request.setTemplateCode("SMS_463791105");//短信模板CODE
                request.setTemplateParam("{\"deviceName\":\""+records2.get(0).getDeviceName()+"\","+"\"time\":\""+baseAlarm.getAlarmTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd " +
                        "HH:mm:ss"))+"\","+
                        "\"alarmType\":\""+baseAlarmType.getTypeName()+"\","+"\"alarmContent\":\""+baseAlarm.getAlarmContent()+"\"}");
                SendSmsResponse code = client.getAcsResponse(request);
                baseAlarmNoticeResult.setNoticeType(4);
                if(code.getCode() != null && code.getCode().equals("OK")) {
                    //请求成功
                    baseAlarmNoticeResult.setNoticeResult(1);
                }else {
                    baseAlarmNoticeResult.setNoticeResult(2);
                }
                saveAlarmResult = baseMapper.insert(baseAlarmNoticeResult);
            }
        }
        return saveAlarmResult;
    }
}