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

import cn.superdesk.libs.common.util.BeanUtils;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.WeekDate;
import com.palmnest.application.dto.input.MealSearchDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.dao.dinner.MealDao;
import com.palmnest.model.Element;
import com.palmnest.model.dinner.Meal;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.dinner.manager.MealManager;
import com.palmnest.service.impl.GenericManagerImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 餐品manager实现类
 *
 * @author longmeizhen
 */
@Slf4j
@Service("mealManager")
public class MealManagerImpl extends GenericManagerImpl<Meal, Long> implements MealManager {


	private MealDao mealDao;

	@Autowired
	public void setMealDao(MealDao mealDao) {
		this.mealDao = mealDao;
		this.dao = mealDao;
	}

	@Autowired
	private ElementGroupManager elementGroupManager;

	/**
	 * 保存修改餐品
	 *
	 * @param userId
	 * @param dto
	 * @return
	 */
	@Override
	public Meal saveAndUpdateMeal(Meal meal) {
		if (meal.getId() == null || meal.getId() == 0) {
			meal.setCreateTime(new Date());
			return mealDao.save(meal);
		} else {
			meal.setModifyTime(new Date());
			mealDao.updateObj(meal);
			return meal;
		}
	}

	/**
	 * 上架下架删除
	 *
	 * @param id
	 * @param type1上架2下架3删除
	 * @return
	 */
	@Override
	public String updateMeal(Long id, int type, String userId) {
		String res = "FAIL";
		if (mealDao.exists(id)) {
			Meal meal = mealDao.get(id);
			meal.setModifier(userId);
			meal.setModifyTime(new Date());
			if (meal != null) {
				if (type == 1) {//上架
					meal.setStatus("1");
				} else if (type == 2) {//下架
					meal.setStatus("2");
				} else if (type == 3) {//删除
					meal.setIsEnabled("0");
				}
				mealDao.updateObj(meal);
				res = "SUCCESS";
			}
		}
		return res;
	}

	/**
	 * 获取餐品列表
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public Page findList(MealSearchDto dto) {
		return mealDao.findList(dto);
	}

	/**
	 * 获取餐品列表
	 * （获取当天且是上架的餐品）
	 *
	 * @param orgId
	 * @return
	 */
	@Override
	public List<Meal> findMealList(String orgId) {
		return mealDao.findMealList(orgId);
	}

	/**
	 * 判断该产品是否为有效的
	 *
	 * @param mealId
	 * @return
	 */
	@Override
	public boolean isMealEnabled(Long mealId) {
		boolean res = true;
		if (mealDao.exists(mealId)) {
			Meal             meal = mealDao.get(mealId);
			SimpleDateFormat df   = new SimpleDateFormat("yyyy-MM-dd");
			Date             date = new Date();
			String           time = df.format(date);
			if ("2".equals(meal.getStatus()) || "0".equals(meal.getIsEnabled())) {
				return false;
			}
			//当购物车中的餐品类型为指定时间供应且当前日期不等于供应时间时，设置成无效产品
			if ("2".equals(meal.getSupplyType()) && !time.equals(meal.getSupplyTime())) {
				res = false;
			}
		}
		return res;
	}

	@Override
	public List<Meal> findMealList(String orgId, String time) {
		return mealDao.findMealList(orgId, time);
	}

	@Override
	public List<Meal> getMealList(String orgId, String time) {
		return mealDao.getMealList(orgId, time);
	}

	@Override
	public List<Meal> findMealByMealCodeId(String orgId, String mealCodeId, String mealCodeOrgId) {
		return mealDao.findMealByMealCodeId(orgId, mealCodeId, mealCodeOrgId);
	}

	@Override
	public Map<String, Object> importMeal(InputStream ins, String orgId) {
		Map<String, Object> retMap   = new HashMap<String, Object>();
		List<Object>        userList = new ArrayList<Object>();
		int                 bugCount = 0;
		StringBuffer        bugStr   = new StringBuffer("");
		Sheet               sheet    = null;
		SimpleDateFormat    sdf      = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Workbook workbook = WorkbookFactory.create(ins);
			sheet = workbook.getSheet("Meal");
		} catch (Exception e) {
			bugStr.append("模板格式有问题，请下载最新的模板");
		}
		try {
			if (sheet == null) {
				bugStr.append("模板格式有问题，请下载最新的模板");
			} else {
				int rows = sheet.getLastRowNum();
				//如果大于2000行数据
				if (rows > 20000) {
					bugStr.append("数据量太大，不能大于2w行");
				} else if (rows < 1) {
					bugStr.append("数据为空，请录入账单信息");
				} else {
					Row row1  = sheet.getRow(0);
					int cells = row1.getPhysicalNumberOfCells();
					if (cells < 1) {
						bugStr.append("数据为空，请录入账单信息");
					} else {
						Map<String, List<Meal>> map = new HashMap<String, List<Meal>>();
						for (int i = 1; i < cells; i++) {
							if (sheet.getRow(0).getCell(i) == null) {
								bugStr.append("第" + i + "列数据有问题，请检查，问题：标题必填，请导出系统模板匹配录入<br/>");
								bugCount++;
								continue;
							}
							sheet.getRow(0).getCell(i).setCellType(Cell.CELL_TYPE_STRING);
							if (StringUtils.isBlank(sheet.getRow(0).getCell(i).getStringCellValue())) {
								bugStr.append("第" + i + "列数据有问题，请检查，问题：标题必填，请导出系统模板匹配录入<br/>");
								bugCount++;
								continue;
							}
							//标题
							String     title = sheet.getRow(0).getCell(i).getStringCellValue();
							Element    el    = elementGroupManager.getByItemname("mealName", title);
							ElementDto elOrg = elementGroupManager.getByItemname(orgId, "mealName", title);
							if (el == null && elOrg == null) {
								bugStr.append("问题：获取不到'" + title + "'该餐品名,请先联系管理员增加餐品名,请导出系统模板匹配录入<br/>");
								bugCount++;
								continue;
							}
							String elId = "";
							if (el != null) {
								elId = el.getId().toString();
							}
							String elOrgId = "";
							if (elOrg != null) {
								elOrgId = elOrg.getId().toString();
							}
							List<Meal> list = mealDao.findMealByMealCodeId(orgId, elId, elOrgId);
							if (list != null && list.size() > 0) {
								map.put("list" + i, list);
							} else {
								bugStr.append("问题：餐品列表中未找到'" + title + "'所设置的模板，请先增加'川菜'模板<br/>");
								bugCount++;
								continue;
							}
						}

						for (int i = 1; i <= rows; i++) {
							if (sheet.getRow(i) == null) {
								continue;
							}
							if (sheet.getRow(i).getCell(0) == null) {
								bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：日期必填，请导出系统模板匹配录入<br/>");
								bugCount++;
								continue;
							}
							sheet.getRow(i).getCell(0).setCellType(Cell.CELL_TYPE_STRING);
							if (StringUtils.isBlank(sheet.getRow(i).getCell(0).getStringCellValue())) {
								bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：日期必填，请导出系统模板匹配录入<br/>");
								bugCount++;
								continue;
							}
							//供应时间
							String supplyTime = sheet.getRow(i).getCell(0).getStringCellValue();
							try {
								Date date = sdf.parse(supplyTime);
								for (int k = 1; k < cells; k++) {
									if (sheet.getRow(i).getCell(k) != null) {
										sheet.getRow(i).getCell(k).setCellType(Cell.CELL_TYPE_STRING);
										String mealDescribe = sheet.getRow(i).getCell(k).getStringCellValue();
										if (StringUtils.isNotBlank(mealDescribe)) {
											List<Meal> mealList = map.get("list" + k);
											if (mealList != null && mealList.size() > 0) {
												Meal mealModel = mealList.get(0);
												Meal meal      = new Meal();
												meal.setDeliveryTimeStr(mealModel.getDeliveryTimeStr());
												meal.setIsEnabled(mealModel.getIsEnabled());
												meal.setIsMeetingFood(mealModel.getIsMeetingFood());
												meal.setIsModel("0");
												meal.setMealCodeId(mealModel.getMealCodeId());
												meal.setMealDescribe(mealDescribe);
												meal.setOrgId(orgId);
												meal.setMealImages(mealModel.getMealImages());
												meal.setSpec(mealModel.getSpec());
												meal.setStapleFood(mealModel.getStapleFood());
												meal.setStatus(mealModel.getStatus());
												meal.setSupplyTime(sdf.format(date));
												meal.setSupplyType("2");
												userList.add(meal);
											}
										}
									}
								}
							} catch (Exception e) {
								bugStr.append("第" + i + "行第1列数据有问题，请检查，问题：日期格式有问题(例:2019-01-01)，请导出系统模板匹配录入<br/>");
								bugCount++;
								continue;
							}
						}
					}
				}
			}
			retMap.put("bugCount", bugCount);
			retMap.put("bugStr", bugStr.toString());
			retMap.put("mealList", userList);
			retMap.put("okCount", userList.size());
			return retMap;

		} catch (Exception e) {
			log.error(e.getMessage());
			retMap.put("bugCount", bugCount);
			retMap.put("bugStr", bugStr.toString());
			retMap.put("mealList", userList);
			retMap.put("okCount", userList.size());
			e.printStackTrace();
			return retMap;
		}
	}

	@Transactional
	public String saveImportMeal(List<Meal> list, String userId) throws RuntimeException {
		String res = "";
		try {
			for (int i = 0; i < list.size(); i++) {
				Meal meal = list.get(i);
				meal.setCreateTime(new Date());
				meal.setCreator(userId);
				mealDao.saveObj(meal);
			}
			res = "SUCCESS";
		} catch (Exception e) {
			res = "";
			throw new RuntimeException(e.getMessage());
		}
		return res;
	}

	@Override
	public List<WeekDate> getMealDate(Integer orgId) {
		List<Map<String,Object>> list = mealDao.getMealDate(orgId);
		List<WeekDate> resList = new ArrayList<>();
		if(CollectionUtils.isEmpty(list)){
			return resList;
		}

		for(int i=0;i<list.size();i++){
			Map<String,Object> map = list.get(i);
			WeekDate weekDate=new WeekDate();
			weekDate.setWeekNo(Integer.parseInt(map.get("weekNo").toString()));
			weekDate.setWeekName(map.get("weekName").toString());
			weekDate.setDateTime(map.get("supplyTime").toString());
			weekDate.setIsToday(Integer.parseInt(map.get("isToday").toString()));
			resList.add(weekDate);
		}
		return resList;
	}

	@Override
	public String getNextMealDate(Integer orgId, String date , int type) {
		return mealDao.getNextMealDate(orgId,date,type);
	}

}
