package com.zd.alg.alarm.controller;

import com.zd.alg.alarm.domain.AlarmLog;
import com.zd.alg.alarm.service.IAlarmLogService;
import com.zd.alg.alarm.utils.AlarmUtil;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.web.domain.AjaxResult;
import com.zd.system.api.alarm.domain.AlarmEntrty;
import com.zd.system.api.alarm.domain.SendTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/alarm")
public class AlarmController {

    @Autowired
    private AlarmUtil alarmUtil;

    @Autowired
    private IAlarmLogService alarmLogService;

    @PostMapping("/send")
    public AjaxResult queryOption(@RequestBody AlarmEntrty alarmEntrty) {
        Map<String, String> map = alarmUtil.sendPost(alarmEntrty);

        String data = map.get("Reply");
        if((SendTypes.Call + "").equals(alarmEntrty.getType()) || (SendTypes.All + "").equals(alarmEntrty.getType())){
            if("OK".equals(data)) {
                String[] phones = alarmEntrty.getTo();
                for (String phone : phones) {
                    AlarmLog alarmLog = new AlarmLog();
                    alarmLog.setIsBack(1);
                    alarmLog.setPhone(phone);
                    alarmLog.setNotice(alarmEntrty.getText());
                    alarmLog.setMethod("电话");
                    alarmLog.setStatus("成功");
                    alarmLog.setCreateTime(DateUtils.getNowDate());
                    alarmLog.setUpdateTime(DateUtils.getNowDate());

                    alarmLogService.insertAlarmLog(alarmLog);
                }
                return AjaxResult.success();
            }else {
                String[] phones = alarmEntrty.getTo();
                for (String phone : phones) {
                    AlarmLog alarmLog = new AlarmLog();
                    alarmLog.setIsBack(1);
                    alarmLog.setPhone(phone);
                    alarmLog.setNotice(alarmEntrty.getText());
                    alarmLog.setMethod("电话");
                    alarmLog.setStatus("失败");
                    alarmLog.setRemark(data);
                    alarmLog.setCreateTime(DateUtils.getNowDate());
                    alarmLog.setUpdateTime(DateUtils.getNowDate());

                    alarmLogService.insertAlarmLog(alarmLog);
                }
                return AjaxResult.error(data);
            }
        }else if((SendTypes.SMS + "").equals(alarmEntrty.getType())) {
            if ("OK".equals(data)) {
                return AjaxResult.success();
            }
        }
        return AjaxResult.error("报警发送错误：" + data);
    }
}
