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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.constant.OrderTypeEnum;
import com.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.*;
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;
	@Resource
	FaExceptionMobileService faExceptionMobileService;
	@Resource
	OrderBaseService orderBaseService;
	@Resource
	OrderAppealService orderAppealService;

	@Transactional(rollbackFor = Exception.class)
	public void insertData(JSONObject datas) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		JSONArray reports = datas.getJSONArray("reports");
		List<String> mobiles = new ArrayList<>();

		// 提取 退订用户信息
		List<FaExceptionMobile> fems = faExceptionMobileService.lambdaQuery().list();
		if (CollectionUtils.isNotEmpty(fems)){
			fems.stream().forEach(event->{
				mobiles.add(event.getMobile());
			});
			fems.clear();
		}

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

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

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

			// 退订写入 fa_exception_mobile
			addFaExceptionMobile(mobiles, 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 insertDataGDtest(){
		List<String> mobiles = new ArrayList<>();

		// 提取 退订用户信息
		List<FaExceptionMobile> fems = faExceptionMobileService.lambdaQuery().list();
		if (CollectionUtils.isNotEmpty(fems)){
			fems.stream().forEach(event->{
				mobiles.add(event.getMobile());
			});
			fems.clear();
		}

		// 同步回复内容信息 smsrecord
		syncSmsRecordtest();

		// 退订写入 fa_exception_mobile
		addFaExceptionMobiletest(mobiles);

	}


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

		// 提取 退订用户信息
		List<FaExceptionMobile> fems = faExceptionMobileService.lambdaQuery().list();
		if (CollectionUtils.isNotEmpty(fems)){
			fems.stream().forEach(event->{
				mobiles.add(event.getMobile());
			});
			fems.clear();
		}


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

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

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

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

			// 退订写入 fa_exception_mobile
			addFaExceptionMobile(mobiles, data);
		}

	}

	private void addFaExceptionMobiletest(List<String> mobiles) {
		if (!mobiles.contains("16626205908")){
			String content = "3";
			if (content.length()==2 && "QX".equals(content)){
				FaExceptionMobile fem = new FaExceptionMobile();
				fem.setMobile("16626205908");
				fem.setCreatetime(new Date());
				fem.insert();
			}
		}
	}

	private void addFaExceptionMobile(List<String> mobiles, JSONObject data) {
		if (!mobiles.contains(data.getString("fromNum"))){
			String content = data.getString("content").toUpperCase();
			if (content.length()==2 && "QX".equals(content)){
				FaExceptionMobile fem = new FaExceptionMobile();
				fem.setMobile(data.getString("fromNum"));
				fem.setCreatetime(new Date());
				fem.insert();
			}
		}
	}

	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 syncSmsRecordtest() {
		Map<String,String> orderPjnr = new HashMap<>();
		// 同步工单回复信息 这里使用手机号+发送码来确认 存在无对应的情况不处理
		// 最近两个月的一定只有一条，为防止出现问题，用list
		List<SmsRecord> rec = smsRecordService.lambdaQuery()
				.eq(SmsRecord::getPhone, "16626205908")
				.eq(SmsRecord::getFsma, "6103")
				.ge(SmsRecord::getCreateTime,publicService.stepMonth(new Date(),-2)).list();
		if (CollectionUtils.isNotEmpty(rec)){
			List<SmsRecord> u = new ArrayList<>();
			for (SmsRecord item:rec){
				item.setReplyContent("3");
				item.setReplyTime(new Date());
				u.add(item);

				orderPjnr.put(item.getOrderBaseId(),item.getReplyContent().trim());
			}
			smsRecordService.updateBatchById(u);
			u.clear();

			// 差评时向申诉表插入数据(自建工单插入差评申诉(非商用空调且为差评信息))
			// 总部发送的短信回复在从总部同步时已做了处理
			getOrderAppeal(orderPjnr);

		}
	}


	private void syncSmsRecord(JSONObject data) {
		Map<String,String> orderPjnr = new HashMap<>();
		// 同步工单回复信息 这里使用手机号+发送码来确认 存在无对应的情况不处理
		// 最近两个月的一定只有一条，为防止出现问题，用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);

				orderPjnr.put(item.getOrderBaseId(),item.getReplyContent().trim());
			}
			smsRecordService.updateBatchById(u);
			u.clear();

			// 差评时向申诉表插入数据(自建工单插入差评申诉(非商用空调且为差评信息))
			// 总部发送的短信回复在从总部同步时已做了处理
			getOrderAppeal(orderPjnr);

		}
	}

	private void getOrderAppeal(Map<String, String> orderPjnr) {
		List<OrderAppeal> orderAppeals = new ArrayList<>();
		// 首评信息用于填写差评中的首评内容
		String spmessage="";

		for (Map.Entry entry : orderPjnr.entrySet()){
			OrderBase orderBase = orderBaseService.lambdaQuery()
					.eq(OrderBase::getId,(String) entry.getKey())
					.eq(OrderBase::getUploadFlag,Boolean.FALSE).one();
			// 工单分安装工单与维修工单
			if (orderBase!=null){
				// 提取差评申诉信息 差评申诉 仅一次
				OrderAppeal oldcpss = orderAppealService.lambdaQuery()
						.eq(OrderAppeal::getOrderBaseId,(String) entry.getKey())
						.last("limit 1").one();

				// 生成差评申诉
				if (oldcpss == null &&
						!orderBase.getMainId().equals("102") && !orderBase.getMainId().equals("109") &&
						publicService.getCppjly((String) entry.getValue())){
					OrderAppeal orderAppeal=new OrderAppeal();
					// 提取首评信息 目的放在追评信息中的首评信息内
					spmessage = publicService.getSpmessage(orderBase, spmessage);
					orderAppeal.setFirstEvaluate(spmessage);
					// 首评即差评
					if (StringUtils.isEmpty(spmessage)){
						orderAppeal.setFirstEvaluate((String) entry.getValue());
					}

					orderAppeal.setOrderBaseId(orderBase.getId());
					orderAppeal.setPgid(orderBase.getPgid());
					orderAppeal.setWorkerName(orderBase.getWorkerName());
					orderAppeal.setWorkerId(orderBase.getWorkerId());
					// 网点必填
					orderAppeal.setWebsitId(orderBase.getWebsitId());
					orderAppeal.setBadEvaluate((String) entry.getValue());
					orderAppeal.setAppraiseStatus(publicService.getAppraiseStatusT((String) entry.getValue()));
					orderAppeal.setStatus(1);
					orderAppeal.setCanApply(Boolean.TRUE);
					orderAppeal.setCreateTime(new Date());
					orderAppeal.setCreateBy("system");
					orderAppeal.setEvaluateTime(new Date());
					orderAppeals.add(orderAppeal);
				} else if (oldcpss != null &&
						!orderBase.getMainId().equals("102") && !orderBase.getMainId().equals("109")){
					// 补追评信息 可能存在追评 判断不是差评记录
					oldcpss.setLastEvaluate((String) entry.getValue());

				}
			}
		}

		// 生成申诉数据
		if (orderAppeals.size()>0){
			orderAppealService.saveOrUpdateBatch(orderAppeals);
			orderAppeals.clear();
		}
	}

}
