package com.sifang.modules.platform.utils;


import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.platform.controller.form.ComplaintReply;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class JSONAppendUtils {

	/**
	 * 获取详细过程信息
	 *
	 * @param pros
	 *            as:2017-05-04 21:40:32#@工单接入@#@2017-05-05 10:01:40#@工单进行派工
	 * @return
	 */
	public static List<ComplaintReply> getProcess(String pros) {
		try {
			ArrayList<ComplaintReply> list = Lists.newArrayList();
			if (StringUtils.isNotBlank(pros)) {
				Gson gson = new Gson();
				list = gson.fromJson(pros, new TypeToken<ArrayList<ComplaintReply>>() {
				}.getType());
			}
			// 升序 按时间升序排序
			Collections.sort(list, new Comparator<ComplaintReply>() {
				public int compare(ComplaintReply o1, ComplaintReply o2) {
					return o1.getT().compareTo(o2.getT());
				}
			});
			return list;
		} catch (Exception ex) {
			return new ArrayList<>();
		}
	}

	/**
	 * 拼接过程信息
	 */
	public static String appendProcessDetail(ComplaintReply ta, String existsDetail) {
		if (ta == null || StringUtil.isBlank(ta.getC())) {
			throw new RuntimeException();
		}
		try {
			ArrayList<ComplaintReply> list = getFittingProcessWithoutSort(existsDetail);// 先前已经存在的过程信息
			list.add(ta);
			Collections.sort(list, new Comparator<ComplaintReply>() {
				public int compare(ComplaintReply o1, ComplaintReply o2) {
					return o1.getT().compareTo(o2.getT());
				}
			});
			Gson gson = new Gson();
			return gson.toJson(list, new TypeToken<ArrayList<ComplaintReply>>() {
			}.getType());
		} catch (Exception ex) {
			return existsDetail;
		}
	}

	public static ArrayList<ComplaintReply> getFittingProcessWithoutSort(String pros) {
		ArrayList<ComplaintReply> list = Lists.newArrayList();
		if (StringUtils.isNotBlank(pros)) {
			Gson gson = new Gson();
			list = gson.fromJson(pros, new TypeToken<ArrayList<ComplaintReply>>() {
			}.getType());
		}
		return list;
	}

}
