package com.palmnest.service.dinner.service.impl;

import cn.jiguang.common.utils.StringUtils;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.StapleFoodDto;
import com.palmnest.application.dto.input.MealDto;
import com.palmnest.application.dto.input.MealSearchDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.application.dto.output.MealOutPutDto;
import com.palmnest.model.Element;
import com.palmnest.model.OrgElement;
import com.palmnest.model.dinner.Meal;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.dinner.manager.MealCarManager;
import com.palmnest.service.dinner.manager.MealManager;
import com.palmnest.service.dinner.service.MealService;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.redis.BaseRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 餐品service实现类
 *
 * @author longmeizhen
 */
@Slf4j
@Service("mealService")
public class MealServiceImpl implements MealService {


	@Autowired
	private MealManager         mealManager;
	@Autowired
	private ElementGroupManager elementGroupManager;
	@Autowired
	private MealCarManager      mealCarManager;
	@Autowired
	private AppUserManager      appUserManager;
	@Autowired
	private BaseRedisService    baseRedisService;

	public static final String IMAGE_URL = PropertiesKit.readPropertiesValue("image_server", "wechat.properties");

	/**
	 * 保存修改餐品
	 *
	 * @param userId
	 * @param dto
	 * @return
	 */
	@Override
	public AppResultDto saveAndUpdateMeal(String userId, MealDto dto, MultipartHttpServletRequest request) {
		//根据餐品名、餐品
		if (StringUtils.isNotEmpty(dto.getMealCodeId()) && "1".equals(dto.getIsModel()) && StringUtils.isEmpty(dto.getId())) {
			Map<String, Object> map  = getEleAndOrgEleId(dto.getOrgId(), dto.getMealCodeId());
			List<Meal>          list = mealManager.findMealByMealCodeId(dto.getOrgId(), map.get("elId").toString(), map.get("orgElId").toString());
			if (list != null && list.size() > 0) {
				return AppResultUtil.createErrorDto("100", "已有该餐品模板，无法上架");
			}
		}
		Meal meal = new Meal();
		if (StringUtils.isNotEmpty(dto.getId())) {//新增
			meal = mealManager.get(Long.parseLong(dto.getId()));
			if (meal != null) {
				if (!"1".equals(meal.getIsModel()) && "1".equals(dto.getIsModel())) {
					Map<String, Object> map  = getEleAndOrgEleId(dto.getOrgId(), dto.getMealCodeId());
					List<Meal>          list = mealManager.findMealByMealCodeId(dto.getOrgId(), map.get("elId").toString(), map.get("orgElId").toString());
					if (list != null && list.size() > 0) {
						return AppResultUtil.createErrorDto("100", "已有该餐品模板，无法上架");
					}
				}
				//删除原有的图片
				String mealImage = meal.getMealImages();
				if (StringUtils.isNotEmpty(mealImage)) {
					String[] images = mealImage.split(";");
					for (int i = 0; i < images.length; i++) {
						if (StringUtils.isNotEmpty(images[i])) {
							if (StringUtils.isNotEmpty(dto.getMealImages())) {//不包含在提交的图片里面，就删除
								if (!dto.getMealImages().contains(images[i])) {
									FileUploadUtils.deleteFileByPath(IMAGE_URL + images[i]);
								}
							}
						}
					}
				}
			} else {
				return AppResultUtil.createErrorDto("100", "找不到该单据");
			}
		}
		try {
			meal.setDeliveryTimeStr(dto.getDeliveryTimeStr() == null ? "" : dto.getDeliveryTimeStr());
			meal.setMealDescribe(dto.getMealDescribe() == null ? "" : dto.getMealDescribe());
			meal.setMealCodeId(dto.getMealCodeId() == null ? "" : dto.getMealCodeId());
			meal.setIsMeetingFood(dto.getIsMeetFood() == null ? 0 : dto.getIsMeetFood());
			meal.setIsModel(dto.getIsModel() == null ? "" : dto.getIsModel());
			meal.setOrgId(dto.getOrgId());
			meal.setSpec(dto.getSpec() == null ? "" : dto.getSpec());
			meal.setStapleFood(dto.getStapleFood() == null ? "" : dto.getStapleFood());
			meal.setStatus(dto.getStatus() == null ? "2" : dto.getStatus());
			meal.setSupplyTime(dto.getSupplyTime() == null ? "" : dto.getSupplyTime());
			meal.setSupplyType(dto.getSupplyType() == null ? "" : dto.getSupplyType());
			meal.setIsEnabled("1");
			meal.setMealImages(dto.getMealImages());
			meal = mealManager.saveAndUpdateMeal(meal);
			if (meal != null) {
				baseRedisService.dele(CodeConstants.ORG_MEAL_LIST_KEY + dto.getOrgId());
				return AppResultUtil.createSuccesDto(meal.getId().toString());
			}
			return AppResultUtil.createErrorDto("100", "操作失败");
		} catch (Exception e) {
			log.error("操作失败" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "操作失败" + e.getMessage());
		}
	}

	@Override
	public MealDto findById(Long id) {
		MealDto dto = new MealDto();
		if (mealManager.exists(id)) {
			Meal meal = mealManager.get(id);
			dto.setDeliveryTimeStr(meal.getDeliveryTimeStr());
			dto.setId(meal.getId().toString());
			dto.setMealDescribe(meal.getMealDescribe());
			dto.setMealCodeId(meal.getMealCodeId());
			if (StringUtils.isNotEmpty(meal.getMealCodeId())) {
				ElementDto elDto = elementGroupManager.getElementById(Long.parseLong(meal.getMealCodeId()));
				if (elDto != null) {
					dto.setMealName(elDto.getItemname());
				}
			}
			dto.setIsMeetFood(meal.getIsMeetingFood());
			dto.setOrgId(meal.getOrgId());
			dto.setIsModel(meal.getIsModel());
			dto.setSpec(meal.getSpec());
			dto.setStapleFood(meal.getStapleFood());
			String stapleFoodStr = "";
			if (StringUtils.isNotEmpty(meal.getStapleFood())) {
				List<Map<String, Object>> foodList = new ArrayList<Map<String, Object>>();
				String[]                  urls     = meal.getStapleFood().split(";");
				if (urls != null && urls.length > 0) {
					for (int i = 0; i < urls.length; i++) {
						Map<String, Object> food  = new HashMap<String, Object>();
						ElementDto          elDto = elementGroupManager.getElementById(Long.parseLong(urls[i]));
						if (elDto != null) {
							stapleFoodStr = stapleFoodStr + elDto.getItemname() + ";";
							food.put("foodId", elDto.getId());
							food.put("foodCode", elDto.getItemcode());
							food.put("foodName", elDto.getItemname());
							foodList.add(food);
						}
					}
				}
				dto.setStapleFoodArr(foodList);
			}
			if ("1".equals(meal.getSpec())) {
				dto.setSpecStr("单品");
			} else {
				if (StringUtils.isNotEmpty(meal.getSpec())) {
					ElementDto elDto = elementGroupManager.getElementById(Long.parseLong(meal.getSpec()));
					if (elDto != null) {
						dto.setSpecStr(elDto.getItemname());
					}
				}
			}
			dto.setStapleFoodStr(stapleFoodStr);
			dto.setStatus(meal.getStatus());
			dto.setSupplyTime(meal.getSupplyTime());
			dto.setSupplyType(meal.getSupplyType());
			String          mealImagesUrl   = "";
			FileUploadUtils fileUploadUtils = new FileUploadUtils();
			fileUploadUtils.init();
			if (StringUtils.isNotEmpty(meal.getMealImages())) {
				String[] urls = meal.getMealImages().split(";");
				if (urls != null && urls.length > 0) {
					for (int i = 0; i < urls.length; i++) {
						mealImagesUrl = mealImagesUrl + fileUploadUtils.fullVisitPath(urls[i]) + ";";
					}
				}
			}
			dto.setMealImagesUrl(mealImagesUrl);
			dto.setMealImages(meal.getMealImages());
		}
		return dto;
	}

	/**
	 * 获取菜品详情
	 *
	 * @param id
	 * @return
	 */
	@Override
	public MealDto findById(Long id, String wxUserId, String time) {
		AppUser user = null;
		if (StringUtils.isNotEmpty(wxUserId) && appUserManager.exists(Integer.parseInt(wxUserId))) {
			user = appUserManager.get(Integer.parseInt(wxUserId));
		}
		MealDto dto = new MealDto();
		if (mealManager.exists(id)) {
			Meal meal = mealManager.get(id);
			dto.setDeliveryTimeStr(meal.getDeliveryTimeStr());
			dto.setId(meal.getId().toString());
			dto.setMealDescribe(meal.getMealDescribe());
			dto.setMealCodeId(meal.getMealCodeId());
			if (StringUtils.isNotEmpty(meal.getMealCodeId())) {
				ElementDto elDto = elementGroupManager.getElementById(Long.parseLong(meal.getMealCodeId()));
				if (elDto != null) {
					dto.setMealName(elDto.getItemname());
				}
			}
//			dto.setMealName(meal.getMealName());
			dto.setIsMeetFood(meal.getIsMeetingFood());
			dto.setOrgId(meal.getOrgId());
			dto.setIsModel(meal.getIsModel());
			dto.setSpec(meal.getSpec());
			dto.setStapleFood(meal.getStapleFood());
			String stapleFoodStr = "";
			if (StringUtils.isNotEmpty(meal.getStapleFood())) {
				List<Map<String, Object>> foodList = new ArrayList<Map<String, Object>>();
				String[]                  urls     = meal.getStapleFood().split(";");
				if (urls != null && urls.length > 0) {
					for (int i = 0; i < urls.length; i++) {
						Map<String, Object> food = new HashMap<String, Object>();
						ElementDto          el   = elementGroupManager.getElementById(Long.parseLong(urls[i]));
						if (el != null) {
							stapleFoodStr = stapleFoodStr + el.getItemname() + ";";
							food.put("foodId", el.getId());
							food.put("foodCode", el.getItemcode());
							food.put("foodName", el.getItemname());
							foodList.add(food);
						}
					}
				}
				dto.setStapleFoodArr(foodList);
			}
			if ("1".equals(meal.getSpec())) {
				dto.setSpecStr("单品");
			} else {
				if (StringUtils.isNotEmpty(meal.getSpec())) {
					ElementDto el = elementGroupManager.getElementById(Long.parseLong(meal.getSpec()));
					if (el != null) {
						dto.setSpecStr(el.getItemname());
					}
				}
			}
			dto.setStapleFoodStr(stapleFoodStr);
			dto.setStatus(meal.getStatus());
			dto.setSupplyTime(meal.getSupplyTime());
			dto.setSupplyType(meal.getSupplyType());
			if (user != null) {
				int count = mealCarManager.findMealCarListByUserId(user.getId().toString(), time, meal.getId().toString());
				dto.setFoodCount(count);
			}
			String          mealImagesUrl   = "";
			FileUploadUtils fileUploadUtils = new FileUploadUtils();
			fileUploadUtils.init();
			if (StringUtils.isNotEmpty(meal.getMealImages())) {
				String[] urls = meal.getMealImages().split(";");
				if (urls != null && urls.length > 0) {
					for (int i = 0; i < urls.length; i++) {
						mealImagesUrl = mealImagesUrl + fileUploadUtils.fullVisitPath(urls[i]) + ";";
					}
				}
			}
			dto.setMealImagesUrl(mealImagesUrl);
			dto.setMealImages(meal.getMealImages());
		}
		return dto;
	}

	/**
	 * 上架下架删除
	 *
	 * @param id
	 * @param type1上架2下架3删除
	 * @return
	 */
	@Override
	public AppResultDto updateMeal(Long id, int type, String userId) {
		try {
			if (mealManager.exists(id)) {
				Meal meal = mealManager.get(id);
				if (meal != null) {
					if (type == 1 && "1".equals(meal.getIsModel())) {//上架且是模板的时候
						Map<String, Object> map  = getEleAndOrgEleId(meal.getOrgId(), meal.getMealCodeId());
						List<Meal>          list = mealManager.findMealByMealCodeId(meal.getOrgId(), map.get("elId").toString(), map.get("orgElId").toString());
						if (list != null && list.size() > 0) {
							return AppResultUtil.createErrorDto("100", "已有该餐品模板，无法上架");
						}
					}
					String res = mealManager.updateMeal(id, type, userId);
					if ("SUCCESS".equals(res)) {
						baseRedisService.dele(CodeConstants.ORG_MEAL_LIST_KEY + meal.getOrgId());
						return AppResultUtil.createSuccesDto();
					}
				}
			}
			return AppResultUtil.createErrorDto("100", "操作失败");
		} catch (Exception e) {
			log.error("操作失败" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "操作失败" + e.getMessage());
		}
	}

	/**
	 * 获取餐品列表
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public Page findList(MealSearchDto dto) {
		if (StringUtil.isNotEmpty(dto.getMealName())) {
			Map<String, Object> map = getEleAndOrgEleId(dto.getOrgId(), dto.getMealName());
			dto.setMealName(map.get("elId").toString());
			dto.setMealNameOrg(map.get("orgElId").toString());
		}
		Page page = mealManager.findList(dto);
		//设置主食
		try {
			if (page != null && page.getItems() != null && page.getItems().size() > 0) {
				List list = page.getItems();
				for (int i = 0; i < list.size(); i++) {
					Map<Object, Object> map = (Map<Object, Object>) list.get(i);
					if (map.containsKey("stapleFood")) {
						String stapleFoodStr = "";
						if (map.get("stapleFood") != null && StringUtils.isNotEmpty(map.get("stapleFood").toString())) {
							String[] str = map.get("stapleFood").toString().split(";");
							if (str != null && str.length > 0) {
								for (int k = 0; k < str.length; k++) {
									ElementDto el = elementGroupManager.getElementById(Long.parseLong(str[k]));
									if (el != null) {
										stapleFoodStr = stapleFoodStr + el.getItemname() + "、";
									}
								}
							}
						}
						if (StringUtils.isNotEmpty(stapleFoodStr)) {
							stapleFoodStr = stapleFoodStr.substring(0, stapleFoodStr.length() - 1);
						}
						map.put("stapleFoodStr", stapleFoodStr);
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return page;
	}

	@Override
	public List<MealOutPutDto> getMealList(String orgId) {
		List<MealOutPutDto> dtoList = new ArrayList<MealOutPutDto>();
		List<Meal>          list    = mealManager.findMealList(orgId);
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Meal meal = list.get(i);
				if (meal != null) {
					MealOutPutDto mealDto = new MealOutPutDto();
					mealDto.setId(meal.getId().toString());
					mealDto.setMealDescribe(meal.getMealDescribe());
					String          mealImagesUrl   = "";
					FileUploadUtils fileUploadUtils = new FileUploadUtils();
					fileUploadUtils.init();
					if (StringUtils.isNotEmpty(meal.getMealImages())) {
						String[] urls = meal.getMealImages().split(";");
						if (urls != null && urls.length > 0) {
							for (int j = 0; j < urls.length; j++) {
								mealImagesUrl = mealImagesUrl + fileUploadUtils.fullVisitPath(urls[j]) + ";";
							}
							mealDto.setMealImagesUrl(fileUploadUtils.fullVisitPath(urls[0]));
							mealDto.setMealImages(mealImagesUrl);
						}
					}
//					mealDto.setMealName(meal.getMealName());
					mealDto.setSpec(meal.getSpec());
					//设置主食
					if (StringUtils.isNotEmpty(meal.getStapleFood())) {
						List<StapleFoodDto> foodList = new ArrayList<StapleFoodDto>();
						String[]            str      = meal.getStapleFood().split(";");
						if (str != null && str.length > 0) {
							String stapleFoodStr = "";
							for (int k = 0; k < str.length; k++) {
								StapleFoodDto food = new StapleFoodDto();
								ElementDto    el   = elementGroupManager.getElementById(Long.parseLong(str[k]));
								if (el != null) {
									stapleFoodStr = stapleFoodStr + el.getItemname() + "、";
									food.setFoodId(el.getId());
									food.setFoodCode(el.getItemcode());
									food.setFoodName(el.getItemname());
									food.setOrderNo(el.getSort());
									foodList.add(food);
								}
							}
							if (StringUtils.isNotEmpty(stapleFoodStr)) {
								stapleFoodStr = stapleFoodStr.substring(0, stapleFoodStr.length() - 1);
								mealDto.setStapleFoodStr(stapleFoodStr);
							}
							mealDto.setIsHaveFood(1);
							mealDto.setStapleFood(foodList);
						}
					} else {
						mealDto.setIsHaveFood(0);
					}
					dtoList.add(mealDto);
				}
			}
		}
		return dtoList;
	}

	@Override
	public AppResultDto importMeal(String orgId, String userId, InputStream ins) {
		Map<String, Object> map      = mealManager.importMeal(ins, orgId);
		int                 bugCount = Integer.parseInt(map.get("bugCount").toString());
		if (bugCount > 0) {//如果bug数量大于0，说明有异常，直接返回异常即可
			return AppResultUtil.createErrorDto("100", map.get("bugStr").toString());
		} else {//否则的话就将用户信息保
			if (map.containsKey("mealList")) {
				List<Meal> mealList = (List<Meal>) map.get("mealList");
				if (mealList != null && mealList.size() > 0) {
					String res = mealManager.saveImportMeal(mealList, userId);//保存餐品
					if ("SUCCESS".equals(res)) {
						baseRedisService.dele(CodeConstants.ORG_MEAL_LIST_KEY + orgId);
						return AppResultUtil.createSuccesDto();
					} else {
						return AppResultUtil.createErrorDto("100", "保存餐品数据失败" + res);
					}
				}
				return AppResultUtil.createErrorDto("100", "导入的餐品信息为空");
			} else {
				return AppResultUtil.createErrorDto("100", "导入餐品数据失败：获取不到mealList");
			}
		}
	}

	public Map<String, Object> getEleAndOrgEleId(String orgId, String id) {
		Map<String, Object> map     = new HashMap<String, Object>();
		String              elId    = "";
		String              orgElId = "";
		OrgElement          orgEl   = elementGroupManager.getOrgElementId(Long.parseLong(id));
		if (orgEl != null) {//如果是项目级且存在，那么获取该项目级的ID，且根据父级code,名称获取原有的
			orgElId = orgEl.getId().toString();
			Element el = elementGroupManager.getByItemname(orgEl.getElementGroup().getGroupcode(), orgEl.getItemname());
			if (el != null) {
				elId = el.getId().toString();
			}
		} else {
			//如果不是项目级的那么就查找是否为非项目级的，如果是就获取该id,且根据项目、父级code,名称获取项目级的
			Element el = elementGroupManager.getElementId(Long.parseLong(id));
			if (el != null) {
				elId = el.getId().toString();
				ElementDto elOrg = elementGroupManager.getByItemname(orgId, el.getElementGroup().getGroupcode(), el.getItemname());
				if (elOrg != null) {
					orgElId = elOrg.getId().toString();
				}
			}
		}
		map.put("elId", elId);
		map.put("orgElId", orgElId);
		return map;
	}

}
