package com.palmnest.webapp.controller.dinner;

import cn.jiguang.common.utils.StringUtils;
import com.palmnest.application.AppConstants;
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.dto.OrgDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.MealDto;
import com.palmnest.application.dto.input.MealSearchDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.model.User;
import com.palmnest.service.AppUserService;
import com.palmnest.service.dinner.service.MealService;
import com.palmnest.service.washcar.service.ElementGroupService;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 餐品
 *
 * @author longmeizhen
 */
@Slf4j
@Controller
@RequestMapping("/admin/dinner/*")
public class MealController extends BaseFormController {


	@Autowired
	private MealService         mealService;
	@Autowired
	private AppUserService      appUserService;
	@Autowired
	private ElementGroupService elementGroupService;

	/**
	 * 跳转到餐品管理界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "jumpMealList")
	public ModelAndView jumpMealList(HttpServletRequest request,
									 HttpServletResponse response) {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		return new ModelAndView("admin/orderDinner/mealManage", model.asMap());
	}

	/**
	 * 跳转到用户信息界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "jumpConsumerList")
	public ModelAndView jumpConsumerList(HttpServletRequest request,
										 HttpServletResponse response) {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		initPageOrgInfo(request, model);
		model.addAttribute("orgs", dtos);
		return new ModelAndView("admin/orderDinner/accountManage", model.asMap());
	}

	/**
	 * 跳转到订餐目录下用户信息界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "jumpPersonnel")
	public ModelAndView jumpPersonnel(HttpServletRequest request,
									  HttpServletResponse response) {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		model.addAttribute("funcid", request.getParameter("funcid"));
		return new ModelAndView("admin/orderDinner/personnelManagement", model.asMap());
	}

	/**
	 * 跳转到订餐目录下用户信息界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "jumpPersonnelDetails")
	public ModelAndView personnelDetails(HttpServletRequest request,
									  HttpServletResponse response) {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		initPageOrgInfo(request, model);
		model.addAttribute("billId", request.getParameter("billId"));
		model.addAttribute("funcid", request.getParameter("funcid"));
		model.addAttribute("orgs", dtos);
		return new ModelAndView("admin/orderDinner/personnelDetails", model.asMap());
	}

	/**
	 * 跳转到订单管理界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "jumpOrderDinnerList")
	public ModelAndView jumpOrderDinnerList(HttpServletRequest request,
											HttpServletResponse response) {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		return new ModelAndView("admin/orderDinner/orderManage", model.asMap());
	}


	/**
	 * 跳转到餐品管理界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "jumpDataStatistics")
	public ModelAndView jumpDataStatistics(HttpServletRequest request,
										   HttpServletResponse response) {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		return new ModelAndView("admin/orderDinner/dataStatistics", model.asMap());
	}

	/**
	 * 跳转到操作日志界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "jumpOperationLog")
	public ModelAndView jumpOperationLog(HttpServletRequest request,
										 HttpServletResponse response) {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		return new ModelAndView("admin/orderDinner/operationLog", model.asMap());
	}

	/**
	 * 获取主食
	 *
	 * @return
	 */
	@RequestMapping(value = "getStapleFood")
	@ResponseBody
	public AppResultDto getStapleFood(HttpServletRequest request, int type, String orgId) {
		User user = (User) request.getSession().getAttribute("UserCache");
//		String userId="";
//		if(user!=null){
//			userId=user.getId().toString();
//		}
		//如果单个项目时，可不传项目
		if (StringUtils.isEmpty(orgId)) {
			String orgIds = getUserManageOrgIds(user);
			if (StringUtils.isEmpty(orgIds)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
			orgId = orgIds.split(",")[0];
		}
		//主食
		if (type == 1) {
			List<ElementDto> stapleFoodDtoList = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "stapleFood");
			Collections.sort(stapleFoodDtoList, new Comparator<ElementDto>() {
				@Override
				public int compare(ElementDto o1, ElementDto o2) {
					Long name1 = o1.getSort();
					Long name2 = o2.getSort();
					return name1.compareTo(name2);
				}
			});
			return AppResultUtil.createSuccesDto(stapleFoodDtoList);
		} else if (type == 2) {
			//规格
			List<ElementDto> specDtoList = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "spec");
			Collections.sort(specDtoList, new Comparator<ElementDto>() {
				@Override
				public int compare(ElementDto o1, ElementDto o2) {
					Long name1 = o1.getSort();
					Long name2 = o2.getSort();
					return name1.compareTo(name2);
				}
			});
			return AppResultUtil.createSuccesDto(specDtoList);
		} else if (type == 3) {
			//餐品名(组合)
			List<ElementDto> specDtoList = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "mealName");
			Collections.sort(specDtoList, new Comparator<ElementDto>() {
				@Override
				public int compare(ElementDto o1, ElementDto o2) {
					Long name1 = o1.getSort();
					Long name2 = o2.getSort();
					return name1.compareTo(name2);
				}
			});
			return AppResultUtil.createSuccesDto(specDtoList);
		} else if (type == 4) {
			//餐品名(单品)
			List<ElementDto> specDtoList = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "mealNameBySingle");
			Collections.sort(specDtoList, new Comparator<ElementDto>() {
				@Override
				public int compare(ElementDto o1, ElementDto o2) {
					Long name1 = o1.getSort();
					Long name2 = o2.getSort();
					return name1.compareTo(name2);
				}
			});
			return AppResultUtil.createSuccesDto(specDtoList);
		} else if (type == 5) {
			//餐品名(一起)
			List<ElementDto> mealNameList = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "mealName");
			List<ElementDto> specDtoList  = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "mealNameBySingle");
			mealNameList.addAll(specDtoList);
			return AppResultUtil.createSuccesDto(mealNameList);
		}
		return AppResultUtil.createSuccesDto();
	}

	/**
	 * 保存或修改菜品
	 *
	 * @param dto
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "saveAndUpdateMeal")
	@ResponseBody
	public AppResultDto saveAndUpdateMeal(MealDto dto, MultipartHttpServletRequest request) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = user.getId().toString();
		}
		if (StringUtils.isEmpty(dto.getOrgId())) {
			//如果单个项目时，可不传项目
			String orgIds = getUserManageOrgIds(user);
			if (StringUtils.isEmpty(orgIds)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
			dto.setOrgId(orgIds);
		}
		return mealService.saveAndUpdateMeal(userId, dto, request);

	}

	/**
	 * 获取菜品详情
	 *
	 * @param dto
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getMealInfo")
	@ResponseBody
	public AppResultDto getMealInfo(Long id) {
		try {
			if (null == id) {
				return AppResultUtil.createErrorDto("100", "id不能为空");
			}
			MealDto dto = mealService.findById(id);
			if (dto == null) {
				return AppResultUtil.createErrorDto("100", "获取餐品详情失败");
			}
			return AppResultUtil.createSuccesDto(dto);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取餐品详情失败");
		}
	}

	/**
	 * 上架下架删除
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "updateMeal")
	@ResponseBody
	public AppResultDto updateMeal(Long id, int type, HttpServletRequest request) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = user.getId().toString();
		}
		if (null == id) {
			return AppResultUtil.createErrorDto("100", "id不能为空");
		}
		return mealService.updateMeal(id, type, userId);
	}

	/**
	 * 获取餐品列表
	 *
	 * @param dto
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getMealList")
	@ResponseBody
	public WebPageResultDto getMealList(MealSearchDto dto, HttpServletRequest request) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String orgIds = getUserManageOrgIds(user);
		if (StringUtils.isEmpty(dto.getOrgId())) {
			dto.setOrgId(orgIds);
		}
		Page             page   = mealService.findList(dto);
		WebPageResultDto webDto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
		webDto.setCount(page.getTotalCount());
		return webDto;
	}

	/**
	 * 删除图片文件
	 *
	 * @param path
	 * @return
	 */
	@RequestMapping(value = "deleteFileByPath")
	@ResponseBody
	public AppResultDto deleteFileByPath(String path) {
		try {
			FileUploadUtils.deleteFileByPath(path);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "删除图片失败(deleteFileByPath):" + e.getMessage());
		}
	}

	@RequestMapping(value = "importMeal")
	@ResponseBody
	public AppResultDto importMeal(@RequestParam("excelFile") MultipartFile excelFile, String orgId, HttpServletRequest request) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		if (StringUtils.isEmpty(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目不允许为空");
		}
		try {
			return mealService.importMeal(orgId, userId, excelFile.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "导入餐品失败:" + e.getMessage());
		}
	}
}
