package com.reptileclient.jlifeapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.reptileclient.jlifeapp.constant.HemaConstant;
import com.reptileclient.jlifeapp.dao.hm.HmSalesOrderMapper;
import com.reptileclient.jlifeapp.dao.hm.HmTokenMapper;
import com.reptileclient.jlifeapp.entity.hm.HmSalesOrder;
import com.reptileclient.jlifeapp.entity.hm.HmToken;
import com.reptileclient.jlifeapp.service.HmDownHistoryService;
import com.reptileclient.jlifeapp.service.HmSalesOrderService;
import com.reptileclient.jlifeapp.service.RetryService;
import com.reptileclient.jlifeapp.util.HttpUtil;
import com.reptileclient.jlifeapp.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

/**
 * 
 * @author 陆， 银联商交易及销售数据抓取
 *
 */
@Service
public class HmSalesOrderServiceImpl implements HmSalesOrderService {

	private static final Logger logger = LoggerFactory.getLogger(HmSalesOrderServiceImpl.class);
	public static Gson gson = new Gson();

	@Autowired
	HmSalesOrderMapper hmSalesOrderMapper;

	@Autowired
	HmDownHistoryService hmDownHistoryService;

	@Autowired
	HmTokenMapper hmtk;

	@Resource
	private RetryService retryService;

	public static Map<String, String> supplierNoMap = new HashMap<String, String>();
	static {
		supplierNoMap.put("282136170", "北京");
		supplierNoMap.put("282160323", "南京");
		supplierNoMap.put("282139010", "深圳");
		supplierNoMap.put("282121208", "上海");
//		supplierNoMap.put("282139010", "苏州");
		supplierNoMap.put("282160847", "杭州");
		supplierNoMap.put("282661107", "青岛");

		supplierNoMap.put("282695147", "广州");
		supplierNoMap.put("282695964", "成都");
		supplierNoMap.put("282695845", "重庆");
	}

	@SuppressWarnings("unchecked")
	public void fetchingData(String startDate, String endDate) {
		HmToken hm = hmtk.selectAll();
		// 分4个城市

		try {
			for (Entry<String, String> s : supplierNoMap.entrySet()) {
				postHm(startDate, endDate, hm.getToken(), s.getKey());
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("银联商交易及销售数据抓取异常：" + e.getMessage());
		}

	}

	@SuppressWarnings("unchecked")
	private void postHm(String startDate, String endDate, String token, String supplierNo) {
		Integer total = 0;
		Integer pageIndex = 1;
		Integer pageSize = 500;

		while (true) {
			try {
				new Thread().sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String parmJson = HemaConstant.HEMADATA_LYSJYJXS_PARM.replace("parm_startDate", startDate)
					.replace("parm_endDate", endDate).replace("parm_supplierNo", supplierNo)
					.replace("parm_pageIndex", pageIndex + "").replace("parm_pageSize", pageSize + "");

			logger.info(supplierNoMap.get(supplierNo) + "联营商交易及销售单请求参数：" + parmJson);

			Map<String, Object> request = retryService.requestPost(token, parmJson, HemaConstant.HEMADATA_LYSJYJXS_URL);
			if (request.get("success").toString().equals("true")) {
				Map<String, Object> data = (Map<String, Object>) request.get("data");
				String tt = data.get("total").toString();
				total = (int) Double.parseDouble(tt);
				logger.info(supplierNoMap.get(supplierNo) + "联营商交易及销售单总条数：" + +total);

				if (total > 0) {
					List<HmSalesOrder> fromJson = JsonUtil.jsonToList(JsonUtil.getJson(data.get("data")),
							HmSalesOrder.class);

					// 插入到数据库
					hmSalesOrderMapper.batcInsert(fromJson);
				}
				hmDownHistoryService.insertDownLog(HemaConstant.HEMADATA_LYSJYJXS_NAME + supplierNoMap.get(supplierNo),
						HemaConstant.HEMADATA_LYSJYJXS_URL, parmJson, startDate + " 00:00:00", endDate + " 00:00:00",
						0);
			} else {
				// 失败
				hmDownHistoryService.insertDownLog(HemaConstant.HEMADATA_LYSJYJXS_NAME + supplierNoMap.get(supplierNo),
						HemaConstant.HEMADATA_LYSJYJXS_URL, parmJson, startDate + " 00:00:00", endDate + " 00:00:00",
						1);
			}

			if (pageIndex * pageSize >= total) {
				break;
			}
			pageIndex = pageIndex + 1;

		}
	}

	/**
	 * 同步历史销售数据，必须分类型跑，不然只能查出某一类的数据
	 * 
	 * @param startDate
	 * @param endDate
	 */
	public void fetchingDataType(String startDate, String endDate) {
		HmToken hm = hmtk.selectAll();
		// 分4个城市
		// 分3个类型
		List<String> queryTypeList = new ArrayList<String>();
		queryTypeList.add("i_sale_detail_zzb");// 掌中宝销售明细
		queryTypeList.add("i_fin_income_detail");// 财务收入明细
		queryTypeList.add("i_sale_fin_diff_detail");// 差异明细

		try {
			for (Entry<String, String> s : supplierNoMap.entrySet()) {
				queryTypeList.forEach(type -> {
					postHmQueryType(startDate, endDate, hm.getToken(), s.getKey(), type);
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("银联商交易及销售数据抓取异常：" + e.getMessage());
		}

	}

	private void postHmQueryType(String startDate, String endDate, String token, String supplierNo, String queryType) {
		Integer total = 0;
		Integer pageIndex = 1;
		Integer pageSize = 500;
//queryType:{i_sale_detail_zzb,i_fin_income_detail,i_sale_fin_diff_detail]
		while (true) {
			String parmJson = HemaConstant.HEMADATA_LYSJYJXS_PARM_TYPE.replace("parm_startDate", startDate)
					.replace("parm_endDate", endDate).replace("parm_supplierNo", supplierNo)
					.replace("parm_pageIndex", pageIndex + "").replace("parm_pageSize", pageSize + "")
					.replace("query_type", queryType);

			logger.info(supplierNoMap.get(supplierNo) + "联营商交易及销售单请求参数：" + parmJson);

			Map<String, Object> request = HttpUtil.request(token, parmJson, HemaConstant.HEMADATA_LYSJYJXS_URL);
			if (request.get("success").toString().equals("true")) {
				Map<String, Object> data = (Map<String, Object>) request.get("data");
				String tt = data.get("total").toString();
				total = (int) Double.parseDouble(tt);
				logger.info(supplierNoMap.get(supplierNo) + "联营商交易及销售单总条数：" + +total);

				if (total > 0) {
					List<HmSalesOrder> fromJson = new ArrayList<HmSalesOrder>();
					if ("i_fin_income_detail".equals(queryType)) {// 财务收入明细（对账结算）
						fromJson = setCWSR(data);
					} else {
						fromJson = JsonUtil.jsonToList(JsonUtil.getJson(data.get("data")), HmSalesOrder.class);
					}

					// 插入到数据库
					hmSalesOrderMapper.batcInsert(fromJson);
				}
				hmDownHistoryService.insertDownLog(HemaConstant.HEMADATA_LYSJYJXS_NAME + supplierNoMap.get(supplierNo),
						HemaConstant.HEMADATA_LYSJYJXS_URL, parmJson, startDate + " 00:00:00", endDate + " 00:00:00",
						0);
			} else {
				// 失败
				hmDownHistoryService.insertDownLog(HemaConstant.HEMADATA_LYSJYJXS_NAME + supplierNoMap.get(supplierNo),
						HemaConstant.HEMADATA_LYSJYJXS_URL, parmJson, startDate + " 00:00:00", endDate + " 00:00:00",
						1);
			}

			if (pageIndex * pageSize >= total) {
				break;
			}
			pageIndex = pageIndex + 1;

		}
	}

	public static List<HmSalesOrder> setCWSR(Map<String, Object> data) {
		// 财务收入明细（对账结算）
		JSONArray jsonArr = JSONArray.parseArray(JsonUtil.getJson(data.get("data")));
		List<HmSalesOrder> fromJson = new ArrayList<HmSalesOrder>();
		for (int i = 0; i < jsonArr.size(); i++) {
			JSONObject jsonObject = jsonArr.getJSONObject(i);
			HmSalesOrder hs = new HmSalesOrder();
			hs.setBizOrderId(jsonObject.getString("biz_order_id"));
			hs.setSupplierNo(jsonObject.getString("supplier_no"));
			hs.setSupplierName(jsonObject.getString("supplier_name"));
			hs.setStoreName(jsonObject.getString("store_name"));
			hs.setPayTime(jsonObject.getDate("pay_time"));
			hs.setRefundTime(jsonObject.getString("refund_time"));
			hs.setSkuCode(jsonObject.getString("sku_code"));
			hs.setAuctionTitle(jsonObject.getString("sku_name"));
			hs.setAuctionPrice(jsonObject.getBigDecimal("unit_price"));
			hs.setOrderChannel(jsonObject.getString("order_channel"));
			hs.setStockUnit(jsonObject.getString("sku_stock_unit"));
			hs.setBuyAmount(jsonObject.getBigDecimal("buy_amount"));
			hs.setPayFee(jsonObject.getBigDecimal("total_price_old"));
			hs.setDiscountInfo(jsonObject.getString("discount_info"));
			fromJson.add(hs);
		}
		return fromJson;
	}

	public static void main(String[] args) {

//		Map<String, Object> data2 =JsonUtil.getEntity(str, Map.class);
//		Map<String, Object> data = (Map<String, Object>) data2.get("data");
//		System.out.println(data.size());
//		
//		List<HmSalesOrder> setCWSR = setCWSR(data);
//		System.out.println(setCWSR.size());
	}
}
