package com.zehong.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zehong.common.exception.CustomException;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.http.HttpClientUtils;
import com.zehong.system.domain.*;
import com.zehong.system.mapper.*;
import com.zehong.system.service.ITEmergencyAlarmNotifyRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 应急报警通知记录Service业务层处理
 * 
 * @author zehong
 * @date 2024-12-10
 */
@Service
public class TEmergencyAlarmNotifyRecordServiceImpl implements ITEmergencyAlarmNotifyRecordService 
{
    private static final Logger logger = LoggerFactory.getLogger(TEmergencyAlarmNotifyRecordServiceImpl.class);

    @Autowired
    private TEmergencyAlarmNotifyRecordMapper tEmergencyAlarmNotifyRecordMapper;

   /* @Resource
    private TEmergencyAlarmRelationInfoMapper tEmergencyAlarmRelationInfoMapper;*/

    @Resource
    private TUrgentContactsMapper tUrgentContactsMapper;

    @Resource
    private TEmergencyAlarmInfoMapper tEmergencyAlarmInfoMapper;

    @Resource
    private TUrgentContactsGroupInfoMapper tUrgentContactsGroupInfoMapper;

    /**
     * 阿里语音地址
     */
    private static String VOICE_NOTIFY_URL = "http://36.138.180.154:8801/aliVoiceNotify/sendAliVoiceNotify";

    /**
     * 阿里短信地址
     */
    private static String SMS_NOTIFY_URL = "http://36.138.180.154:8801/sms/sendSms";

    /**
     * 查询应急报警通知记录
     * 
     * @param id 应急报警通知记录ID
     * @return 应急报警通知记录
     */
    @Override
    public TEmergencyAlarmNotifyRecord selectTEmergencyAlarmNotifyRecordById(Long id)
    {
        return tEmergencyAlarmNotifyRecordMapper.selectTEmergencyAlarmNotifyRecordById(id);
    }

    /**
     * 查询应急报警通知记录列表
     * 
     * @param tEmergencyAlarmNotifyRecord 应急报警通知记录
     * @return 应急报警通知记录
     */
    @Override
    public List<TEmergencyAlarmNotifyRecord> selectTEmergencyAlarmNotifyRecordList(TEmergencyAlarmNotifyRecord tEmergencyAlarmNotifyRecord)
    {
        return tEmergencyAlarmNotifyRecordMapper.selectTEmergencyAlarmNotifyRecordList(tEmergencyAlarmNotifyRecord);
    }

    /**
     * 新增应急报警通知记录
     * 
     * @param tEmergencyAlarmNotifyRecord 应急报警通知记录
     * @return 结果
     */
    @Override
    public int insertTEmergencyAlarmNotifyRecord(TEmergencyAlarmNotifyRecord tEmergencyAlarmNotifyRecord)
    {
        tEmergencyAlarmNotifyRecord.setCreateTime(DateUtils.getNowDate());
        return tEmergencyAlarmNotifyRecordMapper.insertTEmergencyAlarmNotifyRecord(tEmergencyAlarmNotifyRecord);
    }

    /**
     * 修改应急报警通知记录
     * 
     * @param tEmergencyAlarmNotifyRecord 应急报警通知记录
     * @return 结果
     */
    @Override
    public int updateTEmergencyAlarmNotifyRecord(TEmergencyAlarmNotifyRecord tEmergencyAlarmNotifyRecord)
    {
        return tEmergencyAlarmNotifyRecordMapper.updateTEmergencyAlarmNotifyRecord(tEmergencyAlarmNotifyRecord);
    }

    /**
     * 批量删除应急报警通知记录
     * 
     * @param ids 需要删除的应急报警通知记录ID
     * @return 结果
     */
    @Override
    public int deleteTEmergencyAlarmNotifyRecordByIds(Long[] ids)
    {
        return tEmergencyAlarmNotifyRecordMapper.deleteTEmergencyAlarmNotifyRecordByIds(ids);
    }

    /**
     * 删除应急报警通知记录信息
     * 
     * @param id 应急报警通知记录ID
     * @return 结果
     */
    @Override
    public int deleteTEmergencyAlarmNotifyRecordById(Long id)
    {
        return tEmergencyAlarmNotifyRecordMapper.deleteTEmergencyAlarmNotifyRecordById(id);
    }

    /**
     * 通知
     * @param alarmId 报警主键
     */
    public void alarmNotify(Long alarmId){
        //2025-01-02 联系人选择改为选择组号
        TEmergencyAlarmInfo alarmInfo = tEmergencyAlarmInfoMapper.selectTEmergencyAlarmInfoById(alarmId);
        TUrgentContactsGroupInfo groupInfo = new TUrgentContactsGroupInfo();
        groupInfo.setGroupId(alarmInfo.getGroupId());
        List<TUrgentContactsGroupInfo> groupInfoList = tUrgentContactsGroupInfoMapper.selectTUrgentContactsGroupInfoList(groupInfo);
        for(TUrgentContactsGroupInfo group : groupInfoList){
            TUrgentContacts contacts = tUrgentContactsMapper.selectTUrgentContactsById(group.getUrgentContactsId());
            sendVoiceNotify(alarmId,contacts,alarmInfo);
            sendSmsNotify(alarmId,contacts,alarmInfo);
        }
    }

    /**
     * 发送语音
     * @param alarmId 报警主键
     * @param contacts 联系人
     */
    private void sendVoiceNotify(Long alarmId,TUrgentContacts contacts,TEmergencyAlarmInfo alarmInfo){
        TEmergencyAlarmNotifyRecord record = new TEmergencyAlarmNotifyRecord();
        record.setAlarmId(alarmId);
        record.setRecordType("1");
        record.setCreateTime(DateUtils.getNowDate());
        record.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
        record.setDisposerId(contacts.getId());
        try {
            //Map<String,Object> param = new HashMap<>();
            JSONObject param = new JSONObject();
            param.put("calledShowNumber","057128067981");
            param.put("calledNumber",contacts.getPhone());
            param.put("ttsCode","TTS_307445068");
            JSONObject ttsParam = new JSONObject();
            ttsParam.put("address",alarmInfo.getAddress());
            ttsParam.put("name", alarmInfo.getEventTitle());
            param.put("ttsParam",ttsParam.toJSONString());
            param.put("secretKey","f225e66813e6d6a663daf919c1935dcb");
            logger.info("语音参数:========" + param.toJSONString());
            String result = HttpClientUtils.doPost(VOICE_NOTIFY_URL,param.toJSONString(),null);
            if(StringUtils.isEmpty(result)){
                record.setNotifyResult("1");
                record.setNotifyLog(result);
            }
            if(StringUtils.isNotEmpty(result)){
                JSONObject resultJson = JSON.parseObject(result);
                if(!"0".equals(resultJson.getString("code"))){
                    record.setNotifyResult("1");
                    record.setNotifyLog(result);
                    throw new CustomException(resultJson.getString("msg"));
                }
                record.setNotifyResult("0");
                record.setNotifyLog(result);
            }

        } catch (IOException e) {
            record.setNotifyResult("1");
            record.setNotifyLog(e.getMessage());
        }finally {
            tEmergencyAlarmNotifyRecordMapper.insertTEmergencyAlarmNotifyRecord(record);
        }
    }

    /**
     * 发送短信
     * @param alarmId 报警主键
     * @param contacts 联系人
     */
    private void sendSmsNotify(Long alarmId,TUrgentContacts contacts,TEmergencyAlarmInfo alarmInfo){
        TEmergencyAlarmNotifyRecord record = new TEmergencyAlarmNotifyRecord();
        record.setAlarmId(alarmId);
        record.setRecordType("0");
        record.setCreateTime(DateUtils.getNowDate());
        record.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
        record.setDisposerId(contacts.getId());
        try {
            //Map<String,Object> param = new HashMap<>();
            JSONObject param = new JSONObject();
            param.put("phoneNumber",contacts.getPhone());
            param.put("templateCode","SMS_475945845");
            param.put("signName","泽宏云");
            JSONObject templateParam = new JSONObject();
            templateParam.put("address",alarmInfo.getAddress());
            templateParam.put("name", alarmInfo.getEventTitle());
            param.put("templateParam",templateParam.toJSONString());
            param.put("secretKey","f225e66813e6d6a663daf919c1935dcb");
            logger.info("短信参数:========" + param.toJSONString());
            String result = HttpClientUtils.doPost(SMS_NOTIFY_URL,param.toJSONString(),null);
            if(StringUtils.isEmpty(result)){
                record.setNotifyResult("1");
                record.setNotifyLog(result);
            }
            if(StringUtils.isNotEmpty(result)){
                JSONObject resultJson = JSON.parseObject(result);
                if(!"0".equals(resultJson.getString("code"))){
                    record.setNotifyResult("1");
                    record.setNotifyLog(result);
                    throw new CustomException(resultJson.getString("msg"));
                }
                record.setNotifyResult("0");
                record.setNotifyLog(result);
            }
        } catch (IOException e) {
            record.setNotifyResult("1");
            record.setNotifyLog(e.getMessage());
        }finally {
            tEmergencyAlarmNotifyRecordMapper.insertTEmergencyAlarmNotifyRecord(record);
        }
    }

}
