package com.zfire.jiasm.syncdata.utils.oss;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.common.AddJdueServiceImpl;
import com.zfire.jiasm.syncdata.data.Token;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.utils.HttpUtil;
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.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class AddJdueUtil {
	@Value("${jdueurl}")
	private String jdueurl = "";

	@Autowired
	private TokenCenter tokenCenter;
	@Autowired
	private AddJdueServiceImpl service;
	@Resource
	private PublicService publicService;

	public void process(String name, String apiUrl, String tableName, String[] cols) {
		String url = jdueurl + apiUrl;

		try {
			Token token = tokenCenter.getCurrentToken();
			// 提取待同步的数据
			List<Map<String, Object>> result = service.getTaskData(tableName,true);
			for (Map<String, Object> row : result) {
				Long synReqId = (Long) row.get("syn_req_id");

				// 查看该网点数据是否需要回传，不需要回传时直接修改同步状态将不再回传
				// 工单号，名表，记录ID
				if (publicService.checkWebsitSyncFlag((String) row.get("worker_order_no"),tableName,synReqId)){
					continue;
				}

				try {
					JSONObject jsonResult = HttpUtil.httpRequestGetPgid(url, "POST", token, synReqId.toString(),
							JSON.toJSONStringWithDateFormat(genDataMapFromSource(row, cols), "yyyy-MM-dd HH:mm:ss"));
					String statusCode = jsonResult.getString("statusCode");
					if ("200".equals(statusCode)) {
						service.updateSuccess(synReqId, tableName);
					} else {
						String errorMessage = jsonResult.getString("message");
						if (errorMessage == null || errorMessage.trim().length() == 0) {
							errorMessage = "失败";
						}
						if("400".equals(statusCode)) {
							service.updateJDFinish(synReqId, tableName,"错误号["+statusCode+"],"+errorMessage);
						}else {
							throw new Exception(errorMessage);	
						}
					}
				} catch (Exception ex) {
					log.error("执行" + name + "任务[" + synReqId + "]发生错误:" + ex.getMessage());
					service.updateError(tableName, synReqId, ex.getMessage());
				}
			}
		} catch (Exception ex) {
			log.error("ִ执行" + name + "发生错误", ex);
		}
	}

	private Map<String, Object> genDataMapFromSource(Map<String, Object> row, String[] cols) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		for (String col : cols) {
			if(col.equals("siteNode")) {
				paramMap.put("siteCode", row.get(col));
			}else {
				paramMap.put(col, row.get(col));
			}
		}

		return paramMap;
	}

}
