package com.zfire.jiasm.syncdata.sendmessage;


import com.zfire.jiasm.syncdata.constant.TaskConfigEnum;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.service.SMSService;
import com.zfire.jiasm.syncdata.utils.SMSSelfManager;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 自建短信发送类
 * 数据源： fa_marketing_sms
 * 需排除禁发营销短信的手机号 fa_exception_mobile
 * yaozx 
 */
@Component
@Slf4j
public class MarketingSMSSelfTask {
	@Value("${SMSSelf_marketing_Ratec}")
	private String SMSSelf_marketing_Ratec = "";
	@Autowired
	private SMSSelfManager smsSelfManager;
	@Autowired
	private SMSService smsService;
	@Value("${SMSSelf_marketing_templateId}")
	private String templateId;
	@Resource
	PublicService publicService;

	@Scheduled(fixedRateString = "${SMSSelf_marketing_Rate}")
	private void process() {
		if (SMSSelf_marketing_Ratec.equals(TaskConfigEnum.FALSE.getCode())){
			return;
		}

		try {
			log.info("营销短信发送.....................开始");
			List<String> mobiles = new ArrayList<>();
			List<Map<String, Object>> result = smsService.getTaskMarkeginData4Self();

			List<Map<String, Object>> exception = smsService.getTaskExceptionData();
			for (Map<String, Object> row : exception) {
				mobiles.add((String) row.get("mobile"));
			}

			for (Map<String, Object> row : result) {
				String synTaskNo = (String) row.get("syn_task_no");
				Integer synTimes = (Integer) row.get("syn_times");
				Long yhlb = (Long) row.get("yhlb");
				String phoneNo = (String) row.get("sjid");

				// 禁发送处理
				if (mobiles.contains(phoneNo)){
					smsService.stopSendUpdate("fa_marketing_sms", 99, synTaskNo, "该用户已屏蔽此类短信");
					continue;
				}

				// 不需要控制发送时间段判断 (!smsSelfManager.checkCanSend())

				try {
					String[] datas = new String[1];
					datas[0] = (String) row.get("fsnr");
					smsSelfManager.templateSMS(phoneNo, templateId, (String) row.get("syn_task_no"),
							(String) row.get("fsma"), datas);
					smsService.successUpdate("fa_marketing_sms", synTaskNo);
					publicService.upSmsRecordSendTime(synTaskNo,phoneNo,new Date());
				} catch (Exception ex) {
					log.error("营销短信发送失败[syn_task_no=" + synTaskNo + "]", ex);
					synTimes++;
					smsService.errorUpdate("fa_marketing_sms", synTimes, synTaskNo, ex.getMessage());
				}
			}
			log.info("营销短信发送.....................结束");
		} catch (Exception ex) {
			log.error("营销短信发送失败", ex);
		}
	}

}
