package com.iamberry.app.international.controller;

import static com.iamberry.app.config.Response.BARCODE_NOT_FOUND;
import static com.iamberry.app.config.Response.INVALID_TOKEN;
import static com.iamberry.app.config.Response.SUCCESS;
import static com.iamberry.app.config.Response.INSERT_DUPLICATE;

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.iamberry.app.config.APIStatus;
import com.iamberry.app.config.Response;
import com.iamberry.app.config.ResponseHeader;
import com.iamberry.app.core.dto.RecordDTO;
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.wechat.file.FileUtils;
import com.iamberry.wechat.file.UploadResultBean;

/**
 * UserController
 *
 * @author Moon Cheng
 * @date 2016年1月18日 上午11:53:04
 */
@Controller
@RequestMapping("/secure/milk")
public class MilkController extends BaseController {

	@InitBinder("makingRecord")
	public void initBinderRecord(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("makingRecord.");
	}

	@InitBinder("milkPowderInfo")
	public void initBinderMilkPowder(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("milkPowderInfo.");
	}

	/**
	 * 添加冲奶信息 
	 * @author Moon Cheng
	 * @param token 唯一标识符 
	 * @param makingRecord 冲奶信息实体类
	 * @return 1000：请求成功；2100：无效token；
	 */
	@RequestMapping(value = "/set_milk_making_record", method = RequestMethod.POST)
	@ResponseBody
	private Response setMilkMakingRecord(@RequestParam("token") String token, MilkMakingRecord makingRecord) {
		//目前添加了新的冲奶数据同步接口，所以当前方法做空实现处理
		if(1 == 1){
			return SUCCESS.setData(makingRecord, 1);
		}
		makingRecord = milkService.setMilkMakingRecord(makingRecord, token);
		if (makingRecord == null) {
			return INVALID_TOKEN;
		}
		return SUCCESS.setData(makingRecord, 1);
	}

	/**
	 *  通过日期，日期类型，统计某时间的，冲奶总量
	 * @param token   唯一标识符
	 * @param dateStatus 标识符 : day week year 
	 * @param chosenDate 结束时间
	 * @param machineMac 机器mac地址
	 * @return
	 */
	@RequestMapping(value = "/search_user_records_by_time", method = RequestMethod.POST)
	@ResponseBody
	private Response searchUserRecordsByTime(@RequestParam(value = "token") String token,
			@RequestParam("date_status") String dateStatus, @RequestParam("chosen_date") String chosenDate,
			@RequestParam("devid") String machineMac) {

		User userInfo = userService.validateUserToken(token);
		if (userInfo == null) {
			return INVALID_TOKEN;
		}
		Map<String, List<RecordDTO>> makingRecords = milkService.searchUserRecordsByTime(userInfo.getId(), dateStatus,
				chosenDate, machineMac);
		return SUCCESS.setData(makingRecords, makingRecords.size());
	}

	/**
	 * 通过冲奶记录id获取冲奶记录详情
	 * @author Moon Cheng
	 * @param recordId 冲奶记录,id
	 * @return 
	 *//*
	@RequestMapping(value = "/search_user_record_by_id", method = RequestMethod.POST)
	@ResponseBody
	private Response searchUserRecordById(@RequestParam(value = "record_id") Long recordId) {
		MilkMakingRecord makingRecord = milkService.searchUserRecordById(recordId);
		return SUCCESS.setData(makingRecord, 1);
	}*/

	/**
	 * 根据用户id获取用户，冲奶总容量
	 * @author Moon Cheng
	 * @param userId  用户id 
	 * @return
	 */
	@RequestMapping(value = "/get_user_total_milk_volume", method = RequestMethod.POST)
	@ResponseBody
	private Response getTotalMilkVolumeMadeByUser(@RequestParam(value = "user_id") Long userId) {
		return SUCCESS.setData(milkService.getTotalMilkVolumeMadeByUser(userId), 0);
	}

	/**
	 * 手动添加，奶粉信息！
	 * @author Moon Cheng
	 * @param token  唯一标识符
	 * @param milkPowderInfo  奶粉信息
	 * @return
	 */
	@RequestMapping(value = "/set_milk_powder_info", method = RequestMethod.POST)
	@ResponseBody
	private Response setMilkPowderInfo(
			@RequestParam(value = "a_mount") String amountStr,
			@RequestParam(value = "spoon_num") String spoon_num,
			@RequestParam(value = "spoon_ml") String spoon_ml,
			@RequestParam(value = "imageFront") String imageFront,
			@RequestParam(value = "imageBar") String imageBar,
			@RequestParam(value = "imageFeed") String imageFeed,@RequestParam(value = "token") String token, MilkPowderInfo milkPowderInfo) {
		if(milkPowderInfo.getBar_code() == null){
			return INVALID_TOKEN;
		}
		/*MilkPowderInfo	milkInfo = milkService.selectMilkPowderByBar(milkPowderInfo.getBar_code());
		if(milkInfo != null){
			return INSERT_DUPLICATE;
		}*/
		
		// 勺量,每勺多少克     量勺 克数范围2-18
		//String amountStr = request.getParameter("a_mount");
		if (amountStr == null) {
			// 兼容低版本
			milkPowderInfo = milkService.setMilkPowderInfo(milkPowderInfo, token);
			if (milkPowderInfo == null) {
				return INVALID_TOKEN;
			}
			return SUCCESS.setData(milkPowderInfo, 1);
		}
		
		float amount = Float.parseFloat(amountStr);
		// 勺数,多少少		量勺勺数范围 1-10
		int spoonNum = Integer.parseInt(spoon_num);
		// ML,1勺多少奶量  水量范围30-300
		float spoonML = Float.parseFloat(spoon_ml);
		
		// 毫升/勺	
		float s = spoonML / spoonNum;
		
		// 混合比 计算公式：勺量   * 勺数  / 毫升 / 100 = 混合比
		float ratio = amount * spoonNum / spoonML * 100;
		milkPowderInfo.setPowder_ratio(ratio);
		milkPowderInfo.setWeight_per_spoon(amount);
		milkPowderInfo.setMilk_volume_per_spoon(s);
		
		// 密度
		/*
		 *     A<13.2                6
			   13.21<A<15.3          7
			   15.31<A<17.4          8 
			   17.41<A<19.5          9
			   19.51<A<22.0         10 
			   22.1 <A              10
		 */
		int m = 6;
		if (ratio < 13.2) {
			m = 6;
		} else if (ratio > 13.21 && ratio < 15.3) {
			m = 7;
		} else if (ratio > 15.31 && ratio < 17.4) {
			m = 8;
		} else if (ratio > 17.41 && ratio < 19.5) {
			m = 9;
		} else {
			m = 10;
		}
		milkPowderInfo.setDensity((float)m);
		milkPowderInfo.setType(m);//同密度字段
		// 保存操作
		try {
			milkPowderInfo = milkService.setMilkPowderInfo(milkPowderInfo, token);
		} catch (DataAccessException  e) {
			return INSERT_DUPLICATE;
		}
		
		if (milkPowderInfo == null) {
			return INVALID_TOKEN;
		}
		
		// 保存图片
		/*String imageFront = request.getParameter("imageFront");
		String imageBar = request.getParameter("imageBar");
		String imageFeed = request.getParameter("imageFeed");*/
		MilkImages images = new MilkImages();
		images.setImage_Front(imageFront);
		images.setImage_Bar(imageBar);
		images.setImage_Feed(imageFeed);
		images.setImage_Milk_ID(milkPowderInfo.getId());
		milkService.setMilkImages(images);
		return SUCCESS.setData(milkPowderInfo, 1);
	}

	/**
	 * 通过，条形码获取奶粉信息
	 * @author Moon Cheng
	 * @param barcode 条形码code
	 * @return
	 */
	@RequestMapping(value = "/search_milk_powder_info_by_barcode", method = RequestMethod.POST)
	@ResponseBody
	private Response searchMilkPowderInfoByBarCode(@RequestParam(value = "barcode") String barcode) {
		MilkPowderInfo milkPowderInfo = milkService.searchMilkPowderInfoByBarCode(barcode);
		if (milkPowderInfo == null) {
			return BARCODE_NOT_FOUND;
		}
		return SUCCESS.setData(milkPowderInfo, 1);
	}

	/**
	 * 铜鼓品牌名获取奶粉信息
	 * @author Moon Cheng, Yin
	 * @param brand 品牌名
	 * @return
	 */
	@RequestMapping(value = "/search_milk_powder_infos_by_brand", method = RequestMethod.POST)
	@ResponseBody
	private Response searchMilkPowderInfosByBrand(@RequestParam(value = "brand") String brand) {
		Map<String, List<String>> milkPowderInfos = milkService.searchMilkPowderInfosByBrand(brand);
		return SUCCESS.setData(milkPowderInfos, milkPowderInfos.size());
	}

	/**
	 * 获取奶粉品牌
	 * @author Yin 
	 * @return  过滤掉品牌名中有.的 例如 a.b 这里或只查询到a
	 */
	@RequestMapping(value = "/search_milk_powder_brand", method = RequestMethod.GET)
	@ResponseBody
	private Response searchMilkPowderBrand() {
		List<String> milkPowderInfos = milkService.searchMilkPowderBrand();
		return SUCCESS.setData(milkPowderInfos, milkPowderInfos.size());
	}

	/**
	 * 通过奶粉品牌、段数、系列、查询奶粉信息
	 * @param brand 品牌
	 * @param series 系列
	 * @param level 段数
	 * @return
	 */
/*	@RequestMapping(value = "/search_milk_info_by_brand_series_level", method = RequestMethod.POST)
	@ResponseBody
	private Response searchMilkInfoByBrandSeriesLevel(@RequestParam("brand") String brand,
			@RequestParam("series") String series, @RequestParam("level") String level) {
		return SUCCESS.setData(milkService.searchMilkInfoByBrandSeriesLevel(brand, series, level), 1);
	}*/

	/**
	 * 上传奶粉信息的域名，及保存的路径，需要tomcat单独域名映射/或者是nginx
	 */
	private static String SAVE_MILK_IMAGE_DOMAIN = "http://milk.iamberry.com/";
	private static String SAVE_MILK_IMAGE_PATH = "/common/";
	/**
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/upload_image", method = RequestMethod.POST)
	public Response uploadFileImage(@RequestParam("file")MultipartFile[] files, HttpServletRequest request) {
		Map<String, String> filemap= new HashMap<String, String>();
		
		for (int i = 0; i < files.length; i++) {
			MultipartFile file = files[i];
			// 保存文件
			UploadResultBean bean = FileUtils.saveFile(request.getServletContext(), file, SAVE_MILK_IMAGE_PATH);
			if (bean == null) {
				// 文件有误
				return new Response(new ResponseHeader(4204, "文件有误!", -1));
			}
			filemap.put("file"+i,SAVE_MILK_IMAGE_DOMAIN + bean.getSaveFileName());
		}
		return SUCCESS.setData(filemap, filemap.size());
	}
}
