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.GLPPWXGQueryAddService;
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 org.springframework.stereotype.Component;

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


/**
 * 安装工单附加信息下载
 */
@Slf4j
@Component
public class DetailDownloadInstallTask {
	@Value("${baseurl}")
	private String baseurl = "";
	@Value("${detaildownc}")
	private String detaildownc = "";
	@Value("${cjfilec}")
	private String cjfilec = "";



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


	@Scheduled(fixedDelayString = "${detaildown}")
	private void process() {
		try {
			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
			List<Map<String, Object>> types = detailDownloadService.getTaskTypeInstall();
			for (Map<String, Object> downloadType : types) {
				int topDownloadTaskType = (Integer) downloadType.get("download_task_type");

				// 关联任务表提取相应的数据
				List<Map<String, Object>> result = detailDownloadService.getTaskDataInstall(topDownloadTaskType);

				// 测试用
				// List<Map<String, Object>> result = detailDownloadService.getTaskDataInstallTest(topDownloadTaskType);

				for (Map<String, Object> row : result) {
					// ID
					Long id = (Long) row.get("id");
					// 任务类型
					int downloadTaskType = (Integer) row.get("download_task_type");
					// 任务号，自生成(主表下载后平台自生成与总部无关联)
					String downloadTaskNo = (String) row.get("download_task_no");
					Integer downloadTimes = (Integer) row.get("download_times");
					// 下载任务标识即工单的pgguid 维修工单为pgid
					String downloadKeyValue = ((String) row.get("download_key_value")).trim();

					try {
						// 数据同步规则表中提取相应的同步表字段
						List<Map<String, Object>> tables = detailDownloadService.getTaskTables(downloadTaskType);
						List<DetailDownloadData> detailDownloadDatas = new ArrayList<>();
						// 获取数据
						getDatas(token, downloadTaskNo, downloadKeyValue, tables, detailDownloadDatas);

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

					} catch (Exception ex) {
						log.error("执行安装明细下载任务[" + downloadTaskNo + "]发生错误", ex);
						String errMessage = "同步出错";
						if (ex.getMessage() !=null){
							errMessage = errMessage + ex.getMessage();
							if (errMessage.length()>2048){
								errMessage = errMessage.substring(0,2048);
							}
						}
						detailDownloadService.updateError(downloadTaskNo, downloadTimes, errMessage);
					}
				}
			}
		} catch (Exception ex) {
			log.error("ִ执行安装明细任务发生错误", ex);
		}
	}

	// 从格力总部同步的采集附件图生成平台的采集图
	@Scheduled(fixedDelayString = "${cjfile}")
	public void processFJ(){
		if (cjfilec.equals(TaskConfigEnum.FALSE.getCode())){
			return;
		}

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

		log.info("开始生成商户到平台采集附件图信息: \uF0B7{}",sdf.format(new Date()));

		glppwxgQueryAddService.extractedMXFile();

		log.info("生成商户到平台采集附件图信息结束: \uF0B7{}",sdf.format(new Date()));
	}

	// 从格力总部同步的商用条码图生成平台的条码图
	@Scheduled(fixedDelayString = "${cjfile}")
	public void processSY(){
		if (cjfilec.equals(TaskConfigEnum.FALSE.getCode())){
			return;
		}

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

		log.info("开始生成商户(商用)到平台采集条码图信息: \uF0B7{}",sdf.format(new Date()));

		glppwxgQueryAddService.extractedTMSYFile();

		log.info("生成商户(商用)到平台采集条码图信息结束: \uF0B7{}",sdf.format(new Date()));
	}



















	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 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;

	}

}
