package com.iamberry.app.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import com.iamberry.app.config.Constants;
import com.iamberry.app.core.dto.MilkInfoDTO;
import com.iamberry.app.core.dto.RecordCountInfoDTO;
import com.iamberry.app.core.dto.RecordDTO;
import com.iamberry.app.core.entity.MilkDatetimeValue;
import com.iamberry.app.core.entity.MilkImages;
import com.iamberry.app.core.entity.MilkMakingRecord;
import com.iamberry.app.core.entity.MilkPowderInfo;
import com.iamberry.app.core.entity.User;
import com.iamberry.app.face.MilkService;
import com.iamberry.app.ulitity.Utility;
import com.iamberry.wechat.tools.DateTimeUtil;

/**
 * MilkService
 *
 * @author Moon Cheng
 * @date 2016年3月23日 上午11:33:10
 */
@Service
public class MilkServiceImpl extends BaseService implements MilkService {

	/**
	 * setMilkMakingRecord
	 * @param makingRecord
	 * @param token
	 * @param recordId
	 * @return
	 */
	public MilkMakingRecord setMilkMakingRecord(MilkMakingRecord makingRecord, String token) {
		User userInfo = validateUserToken(token);
		if (userInfo == null) {
			return null;
		}
		makingRecord.setUser(userInfo.getId());
		makingRecord.setTimestamp_(new Date());
		milkMapper.insertMilkMakingRecord(makingRecord);
		return makingRecord;
	}

	/**
	 * searchUserRecordsBytime
	 *
	 * @author Moon Cheng
	 * @param userId
	 * @param startTime
	 * @param endTime
	 * @return Milk Making Record List
	 */
	public Map<String, List<RecordDTO>> searchUserRecordsByTime(Long userId, String dateStatus, String chosenDate,
			String machineMac) {

		Map<String, List<RecordDTO>> recordInfos = new LinkedHashMap<String, List<RecordDTO>>();
		String dateType = null, formatter = null;
		Calendar calendar = Calendar.getInstance();
		if (chosenDate != null) {
			// calendar.setTime(Utility.formatStringToDate("yyyy-MM-dd
			// HH:mm:ss", chosenDate));
			// 防止无数据时显示分钟错误
			chosenDate = chosenDate.substring(0, chosenDate.length() - 6) + ":00:00";
			calendar.setTime(Utility.formatStringToDate("yyyy-MM-dd HH:mm:ss", chosenDate));
		} else {
			calendar.setTime(new Date());
		}
		Date start = null, end = null;
		switch (dateStatus) {
		case "day":
			dateType = "days";
			formatter = "%Y%m%d%H";
			calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONDAY), calendar.get(Calendar.DATE), 0, 0,
					0);
			start = calendar.getTime();
			calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONDAY), calendar.get(Calendar.DATE), 23,
					59, 59);
			end = calendar.getTime();
			recordInfos.put("app", Utility.convertMap(
					milkMapper.selectMilkMakingRecords(start, end, "app", dateType, formatter, userId, machineMac),
					dateType));
			recordInfos.put("machine", Utility.convertMap(
					milkMapper.selectMachineMilkMakingRecords(start, end, "machine", dateType, formatter, machineMac),
					dateType));
			break;
		case "week":
			dateType = "weeks";
			formatter = "%Y%m%d";
			calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONDAY), calendar.get(Calendar.DATE), 0, 0,
					0);
			calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
			start = calendar.getTime();
			calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONDAY), calendar.get(Calendar.DATE), 23,
					59, 59);
			if (Calendar.SUNDAY < Calendar.MONDAY) {
				calendar.add(Calendar.DATE, 7);
			}
			calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
			end = calendar.getTime();
			recordInfos.put("app", Utility.convertMap(
					milkMapper.selectMilkMakingRecords(start, end, "app", dateType, formatter, userId, machineMac),
					dateType));
			recordInfos.put("machine", Utility.convertMap(
					milkMapper.selectMachineMilkMakingRecords(start, end, "machine", dateType, formatter, machineMac),
					dateType));
			break;
		case "year":
			dateType = "years";
			formatter = "%Y%m";
			calendar.set(calendar.get(Calendar.YEAR), 0, 1, 0, 0, 0);
			start = calendar.getTime();
			calendar.set(calendar.get(Calendar.YEAR), 11, 31, 23, 59, 59);
			end = calendar.getTime();
			recordInfos.put("app", Utility.convertMap(
					milkMapper.selectMilkMakingRecords(start, end, "app", dateType, formatter, userId, machineMac),
					dateType));
			recordInfos.put("machine", Utility.convertMap(
					milkMapper.selectMachineMilkMakingRecords(start, end, "machine", dateType, formatter, machineMac),
					dateType));
			break;
		}
		return Utility.fillAppMachineRecordWithZero(Utility.synAppMachineRecord(recordInfos), dateType, chosenDate);
	}

	/**
	 * searchUserRecordById
	 *
	 * @author Moon Cheng
	 * @param recordId
	 * @return Milk Making Record Information
	 */
	public MilkMakingRecord searchUserRecordById(Long recordId) {
		MilkMakingRecord makingRecord = milkMapper.selectMilkMakingRecord(recordId);
		return makingRecord;
	}

	/**
	 * 根据用户，获取冲奶记录的-->总量和次数
	 *
	 * @author Moon Cheng
	 * @param userId
	 * @return
	 */
	public RecordCountInfoDTO getTotalMilkVolumeMadeByUser(Long userId) {
		RecordCountInfoDTO recordcount = milkMapper.getMilkPowderSumByUser(userId);
		return  recordcount;
	}

	/**
	 * setMilkPowderInfo
	 *
	 * @author Moon Cheng
	 * @param entity
	 * @param token
	 * @return Milk Powder Information
	 */
	public MilkPowderInfo setMilkPowderInfo(MilkPowderInfo entity, String token) {
		User userInfo = validateUserToken(token);
		if (userInfo == null) {
			return null;
		}

		// change status as user's phone number
		entity.setStatus_(
				userInfo.getUsername().length() > 11 ? Constants.MILK_POWDER_NOT_APPROVED : userInfo.getUsername());
		entity.setCreated_on(new Date());
		milkMapper.insertMilkPowderInfo(entity);
		return entity;
	}

	/**
	 * searchMilkPowderInfoByBarCode
	 *
	 * @author Moon Cheng
	 * @param barcode
	 * @return Milk Powder Information
	 */
	public MilkPowderInfo searchMilkPowderInfoByBarCode(String barcode) {
		MilkPowderInfo milkPowderInfo = milkMapper.selectMilkPowderInfo(barcode);
		return milkPowderInfo;
	}

	/**
	 * 
	 * 通过品牌名获取奶粉信息
	 * @author Moon Cheng, Yin
	 * @param brand
	 * @return Milk Powder List
	 */
	public Map<String, List<String>> searchMilkPowderInfosByBrand(String brand) {
		brand = "%" + brand.trim() + "%";
		Map<String, List<String>> infos = new IdentityHashMap<String, List<String>>();
		List<MilkInfoDTO> milkInfo = milkMapper.selectMilkInfoBybrand(brand);
		for (int i = 0; i < milkInfo.size(); i++) {
			List<String> list = new LinkedList<String>();
			list.add(milkInfo.get(i).getLevel() + ":" + milkInfo.get(i).getType() + ":"
					+ milkInfo.get(i).getPowder_ratio() + ":" + milkInfo.get(i).getId() + ":"
					+ milkInfo.get(i).getWeight_per_spoon());
			infos.put(milkInfo.get(i).getSeries(),list);
		}
		
		return infos;
	}

	/**
	 * searchMilkPowderBrand
	 *
	 * @return Brand List
	 */
	public List<String> searchMilkPowderBrand() {
		List<String> milkPowderInfos = milkMapper.selectMilkPowderBrand();
		List<String> result = new ArrayList<>();
		milkPowderInfos.forEach(milk -> {
			if (NumberUtils.isNumber(milk) && milk.contains(".")) {
				milk = milk.substring(0, milk.indexOf("."));
			}
			result.add(milk);
		});
		return result;
	}

	/**
	 * searchMilkInfoByBrandSeriesLevel
	 *
	 * @param brand
	 * @param series
	 * @param level
	 * @return
	 */
	public MilkPowderInfo searchMilkInfoByBrandSeriesLevel(String brand, String series, String level) {
		return milkMapper.selectMilkInfoByBrandSeriesLevel(brand, series, level);
	}

	// =====================================TuyaHistoryData======================================
	/**
	 * getLastRecordDate
	 *
	 * @return
	 */
	public Date getLastRecordDate() {
		Date lastDate = milkMapper.selectLastRecordDate();
		return lastDate == null ? new Date() : lastDate;
	}

	/**
	 * addRecordData
	 * @param devId
	 * @param value
	 * @param time
	 */
	public void addRecordData(String devId, String value, Long time, Long userId) {
		MilkMakingRecord milkMakingRecord = new MilkMakingRecord();
		milkMakingRecord.setVolume(Integer.parseInt(value));
		milkMakingRecord.setMachine(devId);
		milkMakingRecord.setTimestamp_(new Date(time));
		milkMakingRecord.setUser(userId);
		milkMapper.insertRecordData(milkMakingRecord);
	}

	@Override
	public void setMilkImages(MilkImages images) {
		// TODO Auto-generated method stub
		milkMapper.insertMilkImages(images);
	}

	@Override
	public List<MilkDatetimeValue> getMilkRecordByTime(String mac, String date) {
		// TODO Auto-generated method stub
		
		// 处理搜索的时间
		date = (date != null ? date : DateTimeUtil.format(new Date(), "yyyy-MM-dd"));
		
		// 获取时间区间
		Date startDate = DateTimeUtil.parse(date, "yyyy-MM-dd");
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(startDate);
		calendar.set(Calendar.HOUR_OF_DAY, 24);
		
		// 获取
		List<MilkDatetimeValue> list = milkMapper.getMilkRecordByTime(mac, startDate, calendar.getTime());
		return list;
	}

	@Override
	public List<MilkDatetimeValue> getMilkRecordByDate(String mac, String date) {
		
		// 处理搜索的时间
		date = (date != null ? date : DateTimeUtil.format(new Date(), "yyyy-MM"));
		
		// 判断统计单位：年份或者是月
		boolean isYear = false;
		if (date.indexOf("-") == -1) {
			isYear = true;
		}
		
		// year =  true 表示统计年份，false : 表示统计月
		final boolean year = isYear;
		
		// 返回的数据格式
		String dateFormat = year ? "yyyy-MM" : "yyyy-MM-dd";
		
		// 获取时间区间
		Date startDate = year ? DateTimeUtil.parse(date, "yyyy") : DateTimeUtil.parse(date, "yyyy-MM");
		Date endDate = getLastDayOfYear(startDate, year);
		
		// 查询数据
		List<MilkDatetimeValue> values = milkMapper.getMilkRecordByDate(year, mac, startDate, endDate);
		
		// 如果为空需要填充数据到8条
		if (values == null || values.size() <= 0) {
			values = new ArrayList<MilkDatetimeValue>();
			Date tempDate = startDate;
			for (int i = 0; i < 8; i++) {
				values.add(new MilkDatetimeValue(DateTimeUtil.format(tempDate, dateFormat), 0));
				tempDate = getDate(tempDate, year);
			}
			return values;
		}
		
		// 创建返回对象
		List<MilkDatetimeValue> returnValues = new ArrayList<MilkDatetimeValue>(year ? 12 : 31);
		
		// 当前已经填充的时间
		Date paddDate = null;
		
		for (int i = 0; i < values.size(); i++) {
			
			// 获取当前迭代的数据，如果为空，那么跳过
			MilkDatetimeValue milkDatetimeValue = values.get(i);
			if (milkDatetimeValue == null || milkDatetimeValue.getDateTime() == null) {
				continue;
			}
			
			// 获取当前时间
			Date temp = DateTimeUtil.parse(milkDatetimeValue.getDateTime(), dateFormat);
			
			// 填充
			paddDate = padding(temp, returnValues, year, paddDate, milkDatetimeValue);
		}
		
		// 保证返回数据为8条，可能还需要填充
		if (returnValues.size() <= 8) {
			int count = 8 - returnValues.size();
			Date tempDate = DateTimeUtil.parse(returnValues.get(returnValues.size() - 1).getDateTime(), dateFormat);
			for (int i = 0; i < count; i++) {
				tempDate = getAddDate(tempDate, year);
				returnValues.add(new MilkDatetimeValue(DateTimeUtil.format(tempDate, dateFormat), 0));
			}
		}
		
		// 返回
		return returnValues;
	}
	
	/**
	 * 填充数据方法
	 * @param dateYear
	 * @param values
	 * @param isYear
	 * @author 献
	 * @Time   2016年12月12日
	 */
	public static Date padding(Date dateYear, List<MilkDatetimeValue> values, final boolean isYear, Date paddDate, MilkDatetimeValue milkDatetimeValue) {
		
		// 填充的原则是，如果已经填充过的时间为空，表示可以填充；
		// 如果需要填充的时间大于已经填充的时间，表示可以填充
		if (paddDate == null || dateYear.getTime() > paddDate.getTime()) {
			// next
			Date nextDate = getUpDate(dateYear, isYear);
			if (nextDate != null) {
				padding(nextDate, values, isYear, paddDate, null);
			}
			
			// add Data
			MilkDatetimeValue datetimeValue = new MilkDatetimeValue();
			datetimeValue.setDateTime(DateTimeUtil.format(dateYear, isYear ? "yyyy-MM" : "yyyy-MM-dd"));
			datetimeValue.setValue(milkDatetimeValue == null ? 0 : milkDatetimeValue.getValue());
			values.add(datetimeValue);
			
			// 替换已经填充过的时间
			paddDate = dateYear;
		}
		return paddDate;
	}
	
	/**
	 * 根据当前时间，获取上一个记录的时间
	 * @param date
	 * @param isYear
	 * @return
	 * @author 献
	 * @Time   2016年12月12日
	 */
	public static Date getUpDate(Date date, final boolean isYear) {
		Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if (isYear) {
        	// 如果当前月份为1月，那么，不需要处理啦，应该跳过
        	if (cal.get(Calendar.MONTH) == 0) {
        		return null;
        	}
        	cal.add(Calendar.MONTH, -1);
        } else {
        	// 如果当前天为1日，那么，不需要处理啦，应该跳过
        	if (cal.get(Calendar.DAY_OF_MONTH) <= 1) {
        		return null;
        	}
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
		return cal.getTime();
	}
	
	public static Date getDate(Date date, final boolean isYear) {
		Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if (isYear) {
        	cal.add(Calendar.MONTH, -1);
        } else {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
		return cal.getTime();
	}
	
	public static Date getAddDate(Date date, final boolean isYear) {
		Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if (isYear) {
        	cal.add(Calendar.MONTH, +1);
        } else {
            cal.add(Calendar.DAY_OF_MONTH, +1);
        }
		return cal.getTime();
	}

	/**
	 * 根据一个数据获取对应的结束时间，如果是年，获取本年最后一个月的最后一天
	 * @param date
	 * @param year
	 * @return
	 * @author 献
	 * @Time   2016年12月12日
	 */
    public static Date getLastDayOfYear(Date date, boolean year) {
    	Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 24);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        if (year) {
        	cal.set(Calendar.MONTH, cal.getActualMaximum(Calendar.MONTH));
        }
        return cal.getTime();
    }
}
