package com.zfire.jiasm.syncdata.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.plus.entity.SmsRecord;
import com.zfire.jiasm.syncdata.plus.entity.SyncSmsOrder;
import com.zfire.jiasm.syncdata.plus.service.SmsRecordService;
import com.zfire.jiasm.syncdata.plus.service.SyncSmsOrderService;
import com.zfire.jiasm.syncdata.pojo.bo.DownRepairOrderGD;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.test;
import com.zfire.jiasm.syncdata.utils.HttpUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SMSSelfGetArrivedServiceImpl {
	@Value("${gdbaseurl}")
	private String baseurl = "";

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Resource
	SmsRecordService smsRecordService;
	@Resource
	PublicService publicService;
	@Resource
	SyncSmsOrderService syncSmsOrderService;

	@Transactional(rollbackFor = Exception.class)
	public void insertData(JSONObject datas) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		JSONArray reports = datas.getJSONArray("reports");
		for (int i = 0; i < reports.size(); i++) {
			JSONObject data = reports.getJSONObject(i);

			// 生成对像
			saveItfReceiveSms(sdf, data);

			// 同步回复内容信息smsrecord
			syncSmsRecord(data);
		}
	}

	public Boolean getSyncSmsOrderById(String id) {
		SyncSmsOrder sso = syncSmsOrderService.lambdaQuery()
				.eq(SyncSmsOrder::getId,id).one();
		if (sso !=null){
			return Boolean.FALSE;
		}
		// 无数据不处理
		if (StringUtils.isEmpty(id)){
			return Boolean.FALSE;
		}

		return Boolean.TRUE;
	}

	public void syncSmsOrderStatus() throws Exception {
		String url = baseurl + "sync/smsorderup";
		List<SyncSmsOrder> ssos = syncSmsOrderService.lambdaQuery()
				.eq(SyncSmsOrder::getSynStatus,0).list();
		if (CollectionUtils.isEmpty(ssos)){
			return;
		}
		for (SyncSmsOrder item :ssos){
			String gdid =item.getId();
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("id", gdid);
			JSONObject jsonResult = HttpUtil.httpRequestWithGD(url, "POST",JSONObject.toJSONString(paramMap));

			String code = jsonResult.getString("code");
			if ("200".equals(code)) {
				item.setSynStatus(1);
			}
			item.setSynTime(new Date());
			item.setExeCount(item.getExeCount() + 1);
			item.updateById();
		}
	}




	@Transactional(rollbackFor = Exception.class)
	public void insertDataGD(DownRepairOrderGD datas) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		JSONArray reports = datas.getData();

		// 写入接收表中 状态同步使用
		saveSyncSmsOrder(datas);

		for (int i = 0; i < reports.size(); i++) {
			JSONObject data = reports.getJSONObject(i);

			// 回复数据写入表
			saveItfReceiveSms(sdf, data);

			// 同步回复内容信息 smsrecord
			syncSmsRecord(data);
		}

	}

	private void saveItfReceiveSms(SimpleDateFormat sdf, JSONObject data) throws ParseException {
		String sql = "insert into itf_receive_sms (smsType,fromNum,content,recvTime,"
				+ "dateSent,status,appendCode,action,deliverCode,reqId,smsCount,spCode,subappend) "
				+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?) ";

		Object[] insertValue = new Object[13];
		insertValue[0] = data.getString("smsType");
		insertValue[1] = data.getString("fromNum");
		insertValue[2] = data.getString("content");

		insertValue[3] = sdf.parse(data.getString("recvTime"));

		if (data.containsKey("dateSent")) {
			insertValue[4] = sdf.parse(data.getString("dateSent"));
		} else {
			insertValue[4] = null;
		}

		insertValue[5] = data.getOrDefault("status", "0");
		insertValue[6] = data.getOrDefault("appendCode", "");
		insertValue[7] = data.getString("action");
		insertValue[8] = data.getOrDefault("deliverCode", "");
		insertValue[9] = data.getOrDefault("reqId", "");
		insertValue[10] = data.getOrDefault("smsCount", "0");
		insertValue[11] = data.getOrDefault("spCode", "");
		insertValue[12] = data.getOrDefault("subAppend", "");

		jdbcTemplate.update(sql, insertValue);
	}

	private void saveSyncSmsOrder(DownRepairOrderGD datas) {
		SyncSmsOrder sso = new SyncSmsOrder();
		sso.setId(datas.getId());
		sso.setSmsJson(JSONObject.toJSONString(datas.getData()));
		sso.setCreateTime(new Date());
		sso.setDownloadTaskNo(datas.getId());
		syncSmsOrderService.save(sso);
	}

	private DownRepairOrderGD downloadOrderFromGD(String api) throws Exception {
		DownRepairOrderGD datas = new DownRepairOrderGD();
		String url = baseurl + api;
		JSONObject jsonResult = HttpUtil.httpRequestGetPgidGD(url, "GET", null);
		String code = jsonResult.getString("code");
		if ("200".equals(code)) {
			String json = jsonResult.getString("data");
			JSONObject jsona = JSONObject.parseObject(json);
			String id = jsona.getString("id");
			datas.setId(id);
			datas.setData(jsona.getJSONArray("data"));
			return datas;
		} else {
			String errorMessage = jsonResult.getString("message");
			if (errorMessage == null || errorMessage.trim().length() == 0) {
				errorMessage = "失败";
			}
			throw new Exception(errorMessage);
		}

	}

	private void syncSmsRecord(JSONObject data) {
		// 同步工单回复信息 这里使用手机号+发送码来确认 存在无对应的情况不处理
		// 最近两个月的一定只有一条，为防止出现问题，用list
		List<SmsRecord> rec = smsRecordService.lambdaQuery()
				.eq(SmsRecord::getPhone, data.getString("fromNum"))
				.eq(SmsRecord::getFsma, data.getOrDefault("subAppend", ""))
				.ge(SmsRecord::getCreateTime,publicService.stepMonth(new Date(),-2)).list();
		if (CollectionUtils.isNotEmpty(rec)){
			List<SmsRecord> u = new ArrayList<>();
			for (SmsRecord item:rec){
				item.setReplyContent(data.getString("content"));
				item.setReplyTime(new Date());
				u.add(item);
			}
			smsRecordService.updateBatchById(u);
			u.clear();


			// 差评时向申诉表插入数据


		}
	}

}
