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 com.iamberry.app.core.entity.*;
import org.apache.commons.lang3.math.NumberUtils;
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.face.MilkService;
import com.iamberry.app.ulitity.Utility;

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

	/**
	 * setMilkMakingRecord
	 * @param makingRecord
	 * @param token
	 * @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
	 * @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) {
		//判断当前机器30秒内是否有数据上传
		/*System.out.println(devId+"-"+value+"-"+time+"-"+userId+"正在添加奶粉记录..");*/
		Date timestamp_ = milkMapper.selectMakingRecordAndmachine(devId);
		boolean msg = true;
		if(timestamp_ != null){
			/*System.out.println("最新奶粉记录："+timestamp_.getTime()+"当前时间："+new Date().getTime()+"当前需要存的"+time);*/
			if((time - timestamp_.getTime()) <= 30000){
				msg = false;
			}
		}
		if(msg){
			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);
	}
<<<<<<< .mine

	@Override
	public List<MilkDatetimeValue> getMilkRecordByTime(String mac, String time) {
		return null;
	}

	@Override
	public List<MilkDatetimeValue> getMilkRecordByDate(String mac, String date) {
		return null;
	}
||||||| .r4402
=======

	@Override
	public MilkPowderInfo selectMilkPowderByBar(String barcode) {
		// TODO Auto-generated method stub
		return milkMapper.selectMilkPowderByBar(barcode);
	}
>>>>>>> .r5268
}
