package com.zfire.jiasm.syncdata.download.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.constant.TaskConfigEnum;
import com.zfire.jiasm.syncdata.data.DetailDownloadData;
import com.zfire.jiasm.syncdata.data.Token;
import com.zfire.jiasm.syncdata.plus.entity.SysDict;
import com.zfire.jiasm.syncdata.service.DetailDownloadService;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.utils.DataUtil;
import com.zfire.jiasm.syncdata.utils.HttpUtil;
import com.zfire.jiasm.syncdata.utils.JSONResult;
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 javax.annotation.Resource;
import java.util.*;


/**
 * 维修工单附加信息下载  这里在工单主表同步那里有了不需要再做
 */
@Slf4j
// @Component
public class DetailDownloadRepairTask {
	@Value("${baseurl}")
	private String baseurl = "";
	@Value("${detaildownc}")
	private String detaildownc = "";

	@Autowired
	private TokenCenter tokenCenter;
	@Autowired
	private DetailDownloadService detailDownloadService;
	@Resource
	PublicService publicService;


	@Scheduled(fixedDelayString = "${detaildown}")
	private void process() {
		try {
			if (1==1){
				return ;
			}

			if (detaildownc.equals(TaskConfigEnum.FALSE.getCode())){
				return;
			}


			Map<String, List<SysDict>> sysDictRefDLMap = new HashMap<>();
			sysDictRefDLMap = publicService.getStringListMapXqLb();

			Token token = tokenCenter.getCurrentToken();
			// 同步规则表中提取数据 itf_gree_to_fa_download_task_type
			// 这里只查到一个92的记录数据
			List<Map<String, Object>> types = detailDownloadService.getTaskTypeRepair();
			for (Map<String, Object> downloadType : types) {
				int topDownloadTaskType = (Integer) downloadType.get("download_task_type");
				// 关联任务表提取相应的数据 这里也只能取到92的任务
				List<Map<String, Object>> result = detailDownloadService.getTaskDataRepair(topDownloadTaskType);
				for (Map<String, Object> row : result) {
					// 任务类型
					int downloadTaskType = (Integer) row.get("download_task_type");
					// 任务号，自生成(主表下载后平台自生成与总部无关联)
					String downloadTaskNo = (String) row.get("download_task_no");
					Integer downloadTimes = (Integer) row.get("download_times");
					// 下载任务标识即工单的pgguid
					String downloadKeyValue = ((String) row.get("download_key_value")).trim();
					try {
						// 数据同步规则表中提取相应的同步表字段
						List<Map<String, Object>> tables = detailDownloadService.getTaskTables(downloadTaskType);
						List<DetailDownloadData> detailDownloadDatas = new ArrayList<>();
						// 获取数据
						getDatasRepair(token, downloadTaskNo, downloadKeyValue, tables, detailDownloadDatas);

						// 数据插入到相关表中
						detailDownloadService.insertDataRepair(downloadTaskNo, detailDownloadDatas,downloadTaskType,
								downloadKeyValue,sysDictRefDLMap);

					} catch (Exception ex) {
						log.error("执行维修明细下载任务[" + downloadTaskNo + "]发生错误", ex);
						detailDownloadService.updateError(downloadTaskNo, downloadTimes, ex.getMessage());
					}
				}
			}
		} catch (Exception ex) {
			log.error("ִ执行维修明细任务发生错误", ex);
		}
	}

	private void getDatas(Token token, String downloadTaskNo, String downloadKeyValue, List<Map<String, Object>> tables, List<DetailDownloadData> detailDownloadDatas) throws Exception {
		for (Map<String, Object> table : tables) {
			String downloadMode = (String) table.get("download_mode");
			String srcTabName = (String) table.get("src_tab_name");

			log.info("安装明细任务开始下载[" + srcTabName + ",download_task_no=" + downloadTaskNo + "]");
			String srcTabColList = ((String) table.get("src_tab_col_list"));
			String destTabName = (String) table.get("dest_tab_name");
			String destTabColList = ((String) table.get("dest_tab_col_list"));
			String filterKeyName = ((String) table.get("filter_key_name")).trim();

			String paramJson;
			String url;
			JSONArray jsonArray;

			if ("interface".equalsIgnoreCase(downloadMode)) {
				// 接口只用到了工单的PGGUID
				String serviceName = srcTabName;
				url = baseurl + serviceName;
				paramJson = "[\"" + downloadKeyValue + "\"]";
				JSONObject jsonResult = HttpUtil.httpRequestGetPgid(url, "POST", token, downloadKeyValue,paramJson);
				String statusCode = jsonResult.getString("status");
				if ("200".equals(statusCode)) {
					jsonArray = jsonResult.getJSONArray("data");
				} else {
					String errorMessage = jsonResult.getString("message");
					if (errorMessage == null || errorMessage.trim().length() == 0) {
						errorMessage = "失败";
					}
					throw new Exception(errorMessage);
				}

			} else {
				String serviceName = DataUtil.fromDbName2ServiceName(srcTabName);
				url = baseurl + serviceName + "/querylist";
				Map<String, String> paramMap = new HashMap<String, String>();
				paramMap.put(filterKeyName, downloadKeyValue);
				paramJson = JSON.toJSONString(paramMap);

				log.info("url[" + url + "],send[" + paramJson + "]");
				JSONResult jsonResult = HttpUtil.httpRequestWithToken(url, "POST", paramJson, token);
				jsonArray = (JSONArray) jsonResult.getData();
			}
			String[] arySrcTabCol = srcTabColList.split("\\Q,\\E");
			String[] arySrcTabColValue;
			if (jsonArray != null && jsonArray.size() > 0) {
				log.info("安装明细任务[" + srcTabName + "," + downloadTaskNo + "][" + url + "]下载了["
						+ jsonArray.size() + "]条数据");
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject aData = jsonArray.getJSONObject(i);
					arySrcTabColValue = new String[arySrcTabCol.length];
					for (int j = 0; j < arySrcTabCol.length; j++) {
						arySrcTabColValue[j] = findValue(
								DataUtil.fromDbName2ServiceName(arySrcTabCol[j].trim()), aData);
					}
					DetailDownloadData detailDownloadData = new DetailDownloadData();
					detailDownloadData.setDestTabName(destTabName);
					detailDownloadData.setDestTabColList(destTabColList);
					detailDownloadData.setArySrcTabColValue(arySrcTabColValue);
					detailDownloadDatas.add(detailDownloadData);
				}
			} else {
				log.info("安装明细任务[" + srcTabName + "," + downloadTaskNo + "][" + url + "]无数据");
			}
		}
	}

	private void getDatasRepair(Token token, String downloadTaskNo, String downloadKeyValue, List<Map<String, Object>> tables, List<DetailDownloadData> detailDownloadDatas) throws Exception {
		for (Map<String, Object> table : tables) {
			String srcTabName = (String) table.get("src_tab_name");

			log.info("安装明细任务开始下载[" + srcTabName + ",download_task_no=" + downloadTaskNo + "]");
			String srcTabColList = ((String) table.get("src_tab_col_list"));
			String destTabName = (String) table.get("dest_tab_name");
			String destTabColList = ((String) table.get("dest_tab_col_list"));
			String filterKeyName = ((String) table.get("filter_key_name")).trim();

			String url;
			JSONArray jsonArray;

			String serviceName = DataUtil.fromDbName2ServiceName(srcTabName);
			url = baseurl + serviceName + "/querylist";
			String[] arySrcTabCol = srcTabColList.split("\\Q,\\E");
			String[] arySrcTabColValue = new String[arySrcTabCol.length];

			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put(filterKeyName, downloadKeyValue);
			String paramJson = JSON.toJSONString(paramMap);
			log.info("url[" + url + "],send[" + paramJson + "]");
			JSONResult jsonResult = HttpUtil.httpRequestWithToken(url, "POST", paramJson, token);

			jsonArray = (JSONArray) jsonResult.getData();
			if (jsonArray != null && jsonArray.size() > 0) {
				log.info("维修明细任务[" + srcTabName + "," + downloadTaskNo + "][" + url + "]下载了["
						+ jsonArray.size() + "]条数据");
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject aData = jsonArray.getJSONObject(i);
					arySrcTabColValue = new String[arySrcTabCol.length];
					for (int j = 0; j < arySrcTabCol.length; j++) {
						arySrcTabColValue[j] = findValue(
								DataUtil.fromDbName2ServiceName(arySrcTabCol[j].trim()), aData);
					}
					DetailDownloadData detailDownloadData = new DetailDownloadData();
					detailDownloadData.setDestTabName(destTabName);
					detailDownloadData.setDestTabColList(destTabColList);
					detailDownloadData.setArySrcTabColValue(arySrcTabColValue);
					detailDownloadDatas.add(detailDownloadData);
				}
			} else {
				log.info("维修明细任务[" + srcTabName + "," + downloadTaskNo + "][" + url + "]无数据");
			}
		}
	}

	private String findValue(String srcTabCol, JSONObject aData) {

		Set<String> set = aData.keySet();
		for (String key : set) {
			if (key.equalsIgnoreCase(srcTabCol)) {
				return aData.getString(key);
			}
		}

		return null;

	}

}
