package com.zfire.jiasm.syncdata.sendmessage;

import com.alibaba.fastjson.JSON;
import com.zfire.jiasm.syncdata.constant.TaskConfigEnum;
import com.zfire.jiasm.syncdata.data.Token;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.service.SMSService;
import com.zfire.jiasm.syncdata.utils.DataUtil;
import com.zfire.jiasm.syncdata.utils.OLDSystemUtil;
import com.zfire.jiasm.syncdata.utils.SMSUtil;
import com.zfire.jiasm.syncdata.utils.TokenCenter;
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.text.SimpleDateFormat;
import java.util.*;

/**
 * 派服务人员-短信发送到格力总部  给师傅发短信  暂停短信发送
 * fa_gree_sms_worker
 */
@Slf4j
@Component
public class SMSWorkerSend {
	@Autowired
	private TokenCenter tokenCenter;
	@Value("${installTopicName}")
	private String installTopicName;
	@Value("${repaireMessageDispatchTopicName}")
	private String repaireMessageDispatchTopicName;
	@Value("${pgmsgsendc}")
	private String pgmsgsendc = "";
	@Autowired
	private SMSService smsService;
	@Autowired
	private OLDSystemUtil oldSystemTask;
	@Resource
	PublicService publicService;




	@Scheduled(fixedDelayString = "${pgmsgsend}")
	private void process() {
		if (pgmsgsendc.equals(TaskConfigEnum.FALSE.getCode())){
			return;
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		try {
			log.info("开始派工短信发送: \uF0B7{}", sdf.format(new Date()));

			List<Map<String, Object>> result = smsService.getTaskData("fa_gree_sms_worker");
			Token token = tokenCenter.getCurrentToken();

			for (Map<String, Object> row : result) {
				String synTaskNo = (String) row.get("syn_task_no");
				Map<String, Object> messageTableData = row;
				boolean isInstall = (((Integer) row.get("azorwx")) == 1);
				String key = (String)row.get("fjid");;
				if(isInstall) {
					SMSUtil.minus8Hour(row);
					StringBuffer messageJson = new StringBuffer();
					messageJson.append("{\"messageEntityList\":[");
					messageJson.append(JSON.toJSONStringWithDateFormat(genMessage(messageTableData, false,isInstall),
							"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
					if (row.get("fsnr2") != null && ((String) row.get("fsnr2")).length() > 0) {
						messageJson.append(","+JSON.toJSONStringWithDateFormat(genMessage(messageTableData, true,isInstall),
								"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
					}
					messageJson.append("]}");
					String json = messageJson.toString();
					log.info("安装派工短信" + json);
					oldSystemTask.sendMessage2Server(this.installTopicName, json,
							token, key);
				}else {
					StringBuffer messageJson = new StringBuffer();
					messageTableData.put("fsdt", row.get("crdt"));
					messageJson.append(JSON.toJSONStringWithDateFormat(genMessage(messageTableData, false,isInstall),
							"yyyy-MM-dd HH:mm:ss"));
					String json = messageJson.toString();
					log.info("维修派工短信发给客户" + json);
					oldSystemTask.sendMessage2Server(this.repaireMessageDispatchTopicName, json,
							token, key);
					if (row.get("fsnr2") != null && ((String) row.get("fsnr2")).length() > 0) {
						StringBuffer messageJson2 = new StringBuffer();
						messageJson2.append(JSON.toJSONStringWithDateFormat(genMessage(messageTableData, true,isInstall),
								"yyyy-MM-dd HH:mm:ss"));
						String json2 = messageJson2.toString();
						log.info("维修派工短信发给师傅" + json2);
						oldSystemTask.sendMessage2Server(this.repaireMessageDispatchTopicName, json2,
								token, key);
					}
				}
				smsService.successUpdate("fa_gree_sms_worker", synTaskNo);
				publicService.upSmsRecordSendTime(synTaskNo,(String)row.get("sjid"),new Date());
				publicService.upSmsRecordSendTime(synTaskNo,(String)row.get("sjid2"),new Date());
			}
			log.info("派工短信发送结束: \uF0B7{}", sdf.format(new Date()));
		} catch (Exception ex) {
			log.error("派工短信发送失败", ex);
		}
	}

	private Map<String, Object> genMessage(Map<String, Object> row, boolean isSecond,boolean isInstall) {

		Map<String, Object> paramMap = new HashMap<String, Object>();

		paramMap.put(DataUtil.fromDbName2ServiceName("azorwx"), row.get("azorwx"));
		paramMap.put(DataUtil.fromDbName2ServiceName("crdt"), row.get("crdt"));
		paramMap.put(DataUtil.fromDbName2ServiceName("fsdt"), row.get("fsdt"));
		paramMap.put(DataUtil.fromDbName2ServiceName("fjid"), row.get("fjid"));
		paramMap.put(DataUtil.fromDbName2ServiceName("fjwd"), row.get("fjwd"));
		paramMap.put(DataUtil.fromDbName2ServiceName("fsnr"), row.get("fsnr" + (isSecond ? "2" : "")));
		paramMap.put(DataUtil.fromDbName2ServiceName("sjid"), row.get("sjid" + (isSecond ? "2" : "")));
		paramMap.put(DataUtil.fromDbName2ServiceName("stat"), row.get("stat"));
		if(!isInstall) {
			paramMap.put(DataUtil.fromDbName2ServiceName("dxguid"), UUID.randomUUID().toString().replaceAll("\\Q-\\E", ""));
		}
		return paramMap;
	}


}
