package com.mortals.xhx.daemon.task;

import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.busiz.req.SmsThirdPartyReq;
import com.mortals.xhx.common.code.SendStatusEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.utils.SendSmsTask;
import com.mortals.xhx.common.utils.SendTaskThreadPool;
import com.mortals.xhx.module.alarm.model.AlarmSmsSendEntity;
import com.mortals.xhx.module.alarm.model.AlarmSmsSendQuery;
import com.mortals.xhx.module.alarm.service.AlarmSmsSendService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.security.DenyAll;
import java.util.Date;
import java.util.List;

/**
 * 短信发送任务
 *
 * @author: zxfei
 * @date: 2022/3/9 15:19
 */
@CommonsLog
@Service("SmsSendTask")
public class SmsSendTaskImpl implements ITaskExcuteService {

    @Autowired
    private AlarmSmsSendService alarmSmsSendService;

    @Autowired
    private SendTaskThreadPool sendTaskThreadPool;

    @Value("${sms.smsSendUrl:http://127.0.0.1:8089/api/index/index}")
    private String smsSendUrl;

    @Value("${sms.apiId:''}")
    private String apiId;

    @Value("${sms.type:''}")
    private String type;

    @Override
    public void excuteTask(ITask task) throws AppException {

        String sendUrl = GlobalSysInfo.getParamValue(Constant.PARAM_SMS_HTTP_URL, smsSendUrl);
        List<AlarmSmsSendEntity> sendList = alarmSmsSendService.find(new AlarmSmsSendQuery().sendStatus(SendStatusEnum.未发送.getValue()));
        sendList.stream().forEach(sms -> {
            SmsThirdPartyReq smsThirdPartyReq = new SmsThirdPartyReq();
            smsThirdPartyReq.setAppid(apiId);
            smsThirdPartyReq.setType(type);
            smsThirdPartyReq.setAlarmSmsSendId(sms.getId());
            smsThirdPartyReq.setPhone(sms.getMobile());
            SendSmsTask sendSmsTask = new SendSmsTask(smsThirdPartyReq, sendUrl);
            sendTaskThreadPool.execute(sendSmsTask);
            sms.setSendStatus(SendStatusEnum.提交.getValue());
            sms.setSendTime(new Date());
            alarmSmsSendService.update(sms,null);

        });

    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }


}
