package com.quantgroup.asset.distribution.service.product.impl;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quantgroup.asset.distribution.enums.ExecuteType;
import com.quantgroup.asset.distribution.model.form.AssetForm;
import com.quantgroup.asset.distribution.service.jpa.entity.FinanceProductHitLog;
import com.quantgroup.asset.distribution.service.jpa.repository.IFinanceProductHitLogRepository;
import com.quantgroup.asset.distribution.service.product.IFinanceProductHitLogService;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author liwenbin
 *
 */
@Slf4j
@Service
public class FinanceProductHitLogServiceImpl implements IFinanceProductHitLogService{
	
	@Autowired
	private IFinanceProductHitLogRepository financeProductHitLogRepository;
	
	@Async
	@Override
	public void saveLog(AssetForm assetForm, String oldFinanceProduct, String newFinanceProduct, 
			String oldAuditResult, String newAuditResult, ExecuteType executeType) {
		try {
			FinanceProductHitLog hitLog = new FinanceProductHitLog();
			hitLog.setBizChannel(assetForm.getBizChannel());
			hitLog.setUuid(assetForm.getUuid());
			hitLog.setAssetNo(assetForm.getAssetNo());
			hitLog.setBizNo(assetForm.getBizNo());
			hitLog.setOldFinanceProduct(oldFinanceProduct);
			hitLog.setNewFinanceProduct(newFinanceProduct);
			hitLog.setOldAuditResult(oldAuditResult);
			hitLog.setNewAuditResult(newAuditResult);
			hitLog.setEnable(true);
			hitLog.setEquals(financeProducEquals(oldFinanceProduct, newFinanceProduct));
			hitLog.setExecuteType(executeType.getCode());
			financeProductHitLogRepository.save(hitLog);
		} catch (Exception e) {
			log.error("金融产品集命中记录比较保存异常, uuid : {}, bizNo : {}, assetNo : {}, oldFInanceProduct : {}, newFinanceProduct : {}",
					assetForm.getUuid(), assetForm.getBizNo(), assetForm.getAssetNo(), oldFinanceProduct, newFinanceProduct);
		}
	}
	
	
	/**
	 * 比较是否相等
	 * @param oldFinanceProduct
	 * @param newFinanceProduct
	 * @return
	 */
	public boolean financeProducEquals(String oldFinanceProduct, String newFinanceProduct) {
		JSONArray oldArray = JSON.parseArray(oldFinanceProduct);
		JSONArray newArray = JSON.parseArray(newFinanceProduct);
		if (oldArray == null || newArray == null || oldArray.size() != newArray.size()) {
			return false;
		}
		List<Map<String, String>> oldList = getAllTransToMap(oldArray);
		List<Map<String, String>> newList = getAllTransToMap(newArray);
		if (oldList.size() != newList.size()) {
			return false;
		}
		int count = 0;
		for (Map<String, String> oldMap : oldList) {
			for (Map<String, String> newMap : newList) {
				if (!oldMap.get("min").equals(newMap.get("min"))) {
					continue;
				}
				if (!oldMap.get("max").equals(newMap.get("max"))) {
					continue;
				}
				if (!oldMap.get("term").equals(newMap.get("term"))) {
					continue;
				}
				if (!oldMap.get("fundId").equals(newMap.get("fundId"))) {
					continue;
				}
				if (!oldMap.get("rate").equals(newMap.get("rate"))) {
					continue;
				}
				if (!oldMap.get("rateType").equals(newMap.get("rateType"))) {
					continue;
				}
				if (!oldMap.get("priority").equals(newMap.get("priority"))) {
					continue;
				}
				if (!oldMap.get("feeType").equals(newMap.get("feeType"))) {
					continue;
				}
				String oldFundProductId = oldMap.get("fundProductId");
				String newFundProductId = newMap.get("fundProductId");
				if (StringUtils.isEmpty(oldFundProductId) && StringUtils.isEmpty(newFundProductId)) {
					count++;
				} else if (StringUtils.isNotEmpty(oldFundProductId) && StringUtils.isNotEmpty(newFundProductId)) {
					if (oldFundProductId.equals(newFundProductId)) {
						count++;
					}
				}
			}
		}
		if (count == oldList.size()) {
			return true;
		}
		return false;
	}
	
	/**
	 * 金融产品集组件每一个对象，List
	 * @return
	 */
	public List<Map<String, String>> getAllTransToMap(JSONArray array) {
		List<Map<String, String>> list = new ArrayList<>();
		for (int i = 0, len = array.size(); i < len; ++i) {
			JSONObject amountJSON = array.getJSONObject(i);
			String min = amountJSON.getString("min");
			String max = amountJSON.getString("max");
			JSONArray termArray = amountJSON.getJSONArray("terms");
			for (int j = 0; j < termArray.size(); j++) {
				JSONObject termJSON = termArray.getJSONObject(j);
				String term = termJSON.getString("term");
				JSONArray fundArray = termJSON.getJSONArray("fundInfo");
				for (int k = 0; k < fundArray.size(); k++) {
					JSONObject fundJSON = fundArray.getJSONObject(k);
					String fundId = fundJSON.getString("fundId");
					String rate = fundJSON.getString("rate");
					String rateType = fundJSON.getString("rateType");
					String priority = fundJSON.getString("priority");
					String feeType = fundJSON.getString("feeType");
					String fundProductId = fundJSON.getString("fundProductId");
					
					Map<String, String> one = new HashMap<>();
					one.put("min", min);
					one.put("max", max);
					one.put("term", term);
					one.put("fundId", fundId);
					one.put("rate", rate);
					one.put("rateType", rateType);
					one.put("priority", priority);
					one.put("feeType", feeType);
					one.put("fundProductId", fundProductId);
					list.add(one);
				}
			}
		}
		return list;
	}
}
