package com.yihu.wlyy.task;

import java.util.concurrent.LinkedBlockingQueue;

import org.json.JSONArray;
import org.json.JSONObject;

import com.yihu.wlyy.service.app.statistics.DoctorStatisticsService;

/**
 * 医生统计任务
 * @author George
 *
 */
public class DoctorStatisticsTask {

	private DoctorStatisticsService doctorStatisticsService;

	// 最大容量为50的数组堵塞队列
	private static LinkedBlockingQueue<JSONObject> queue = new LinkedBlockingQueue<JSONObject>();

	private static DoctorStatisticsTask instance;

	private static Object lock = new Object();

	public static DoctorStatisticsTask getInstance(DoctorStatisticsService doctorStatisticsService) {
		synchronized (lock) {
			if (instance == null) {
				instance = new DoctorStatisticsTask();
				instance.doctorStatisticsService = doctorStatisticsService;
				instance.run();
			}
		}
		return instance;
	}

	/**
	 * 添加一个队列
	 * @param doctor 医生标识
	 * @param flag 统计类型：1咨询统计，2评价统计
	 * @param type 类型：1三师咨询（指定咨询），2视频咨询
	 * @param star 评价统计时，评价的星级
	 */
	public void put(String doctor, int flag, int type, int star) {
		try {
			JSONObject json = new JSONObject();
			json.put("doctor", doctor);
			json.put("flag", flag);
			json.put("type", type);
			json.put("star", star);
			queue.put(json);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 批量添加
	 * @param array
	 */
	public void put(JSONArray array) {
		try {
			for (int i = 0; i < array.length(); i++) {
				JSONObject json = array.getJSONObject(i);
				if(json == null){
					continue;
				}
				queue.put(json);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void run() {
		new Thread(new ConsumerTask()).start();
	}

	// 消费者
	class ConsumerTask implements Runnable {
		@Override
		public void run() {
			try {
				while (true) {
					JSONObject json = queue.take();
					if (json == null) {
						continue;
					}
					String doctor = json.getString("doctor");
					// 1咨询统计，2评价统计
					int flag = json.getInt("flag");
					int type = json.getInt("type");
					int star = json.has("star") ? json.getInt("star") : 0;
					if (flag == 1) {
						doctorStatisticsService.addConsult(doctor, type);
					} else if (flag == 2) {
						doctorStatisticsService.addComment(doctor, type, star);
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

}