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

import cn.jiguang.common.utils.StringUtils;

import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.*;
import com.palmnest.application.core.util.hangdian.MapUtils;
import com.palmnest.application.dto.MeetintDto;
import com.palmnest.application.dto.input.OrderDinnerInputDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.dao.ElementGroupDao;
import com.palmnest.dao.UserDateActiveDao;
import com.palmnest.dao.dinner.*;
import com.palmnest.dao.estateserve.AppUserDao;
import com.palmnest.model.Element;
import com.palmnest.model.OrgElement;
import com.palmnest.model.dinner.MealCar;
import com.palmnest.model.dinner.OrderDinner;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.dinner.manager.MealManager;
import com.palmnest.service.dinner.manager.OrderDinnerManager;
import com.palmnest.service.impl.GenericManagerImpl;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service("orderDinnerManager")
public class OrderDinnerManagerImpl extends GenericManagerImpl<OrderDinner, Long> implements OrderDinnerManager {


	private OrderDinnerDao orderDinnerDao;

	@Autowired
	public void setOrderDinnerDao(OrderDinnerDao orderDinnerDao) {
		this.orderDinnerDao = orderDinnerDao;
		this.dao = orderDinnerDao;
	}

	@Autowired
	private MealCarDao          mealCarDao;
	@Autowired
	private MealDao             mealDao;
	@Autowired
	private MealManager         mealManager;
	@Autowired
	private OrderDinnerInfoDao  orderDinnerInfoDao;
	@Autowired
	private ElementGroupManager elementGroupManager;
	@Autowired
	private ElementGroupDao     elementGroupDao;
	@Autowired
	private ConsumerDao         consumerDao;
	@Autowired
	private AppUserDao          appUserDao;
	@Autowired
	private DeptDao             deptDao;
	@Autowired
	private OrganizationManager organizationManager;
	@Autowired
	private UserDateActiveDao   userDateActiveDao;

	public static String MEETURL = PropertiesKit.readPropertiesValue("meeting_url", "wechat.properties");

	/**
	 * 根据当前登录用户获取购物车的餐品
	 * 该方法获取的是封装好的标注了餐品是有效还是无效的
	 *
	 * @param consId
	 * @return
	 */
	@Override
	public List<MealCar> delMealCarByConsId(String consId) {
		List<MealCar> carlist = new ArrayList<MealCar>();
		List<MealCar> list    = mealCarDao.findMealCarListByConsId(consId, "");
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				MealCar mealcar = list.get(i);
				if (mealcar != null) {
					String mealId = mealcar.getMealId();
					if (StringUtils.isNotEmpty(mealId)) {
						if (!mealManager.isMealEnabled(Long.parseLong(mealId))) {
							mealCarDao.removeMealCarById(mealcar.getId());
						} else {
							carlist.add(mealcar);
						}
					}

				}
			}
		}
		return carlist;
	}

	/**
	 * PC/WECHAT端获取订餐列表
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public Page findList(OrderDinnerInputDto dto, int pageSize, int pageNo) {
		return orderDinnerDao.findList(dto, pageSize, pageNo);
	}

	/**
	 * 获取订单
	 */
	@Override
	public List<OrderDinner> findByCons(String consId, String orgId, String status) {
		return orderDinnerDao.findByCons(consId, orgId, status);
	}

	/**
	 * 确认送达后将当天所有有效的订单的状态改成待评价状态
	 *
	 * @param orgId
	 * @return
	 */
	@Override
	public int updateOrderStatus(String orgId, String consId) {
		return orderDinnerDao.updateOrderStatus(orgId, consId);
	}

	/**
	 * 获取订单
	 */
	@Override
	public List<OrderDinner> findByConsId(String consId, String orgId) {
		return orderDinnerDao.findByConsId(consId, orgId);
	}

	/**
	 * 获取该项目下最开始新增数据的创建时间
	 *
	 * @param orgId
	 * @return
	 */
	@Override
	public String getTopCreateTime(String orgId) {
		return orderDinnerDao.getTopCreateTime(orgId);
	}

	@Override
	public List<Map<String, Object>> getSumOrder(String orgId, int dateType,
												 String year, String time) {
		List<Map<String, Object>> foodList = orderDinnerDao.getStapleFoodOrderList(orgId, dateType, year, time);
		List<Map<String, Object>> map      = getSumOrderInfo(orgId, foodList, dateType, year, time);
		return map;
	}

	//获取综合
	public List<Map<String, Object>> getSumOrderInfo(String orgId, List<Map<String, Object>> foodList, int dateType,
													 String year, String time) {
		List<AppUser> list     = appUserDao.getAppUserByOrgId(Integer.parseInt(orgId));
		int           consSize = 0;
		if (list != null) {
			consSize = list.size();
		}
		List<Map<String, Object>> sumList = new ArrayList<Map<String, Object>>();
		//主食 
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("singleFood", "0");
		map.put("soupFood", "0");
		map.put("fruitFood", "0");
		map.put("groupFood", "0");//组合
		map.put("totalNum", "0");//总分数
		List<Element> stapleFoodList = elementGroupDao.getElementsByGroupName("stapleFood");
		if (stapleFoodList != null && stapleFoodList.size() > 0 && foodList != null && foodList.size() > 0) {
			for (int i = 0; i < stapleFoodList.size(); i++) {
				Element e = stapleFoodList.get(i);
				map.put(e.getItemcode(), "0");
				for (int j = 0; j < foodList.size(); j++) {
					Map<String, Object> foodMap = foodList.get(j);
					String              foodId  = foodMap.get("stapleFood") == null ? "" : foodMap.get("stapleFood").toString();
					if (String.valueOf(e.getId()).equals(foodId)) {
						map.put(e.getItemcode(), foodMap.get("sumCount") == null ? "0" : foodMap.get("sumCount").toString());
					}
				}
			}
		}
		//规格 1单品2三菜一汤3三菜一汤加水果
		BigDecimal sum        = new BigDecimal("0");
		BigDecimal group      = new BigDecimal("0");//组合
		BigDecimal avg        = new BigDecimal("0");
		int        singleFood = orderDinnerDao.getMeetCount(orgId, dateType, year, time, 3);//单品
		int        soupFood   = orderDinnerDao.getMeetCount(orgId, dateType, year, time, 2);//工作餐
		int        fruitFood  = orderDinnerDao.getMeetCount(orgId, dateType, year, time, 1);//会议餐
		group = new BigDecimal(soupFood).add(new BigDecimal(fruitFood));
		avg = new BigDecimal(soupFood).add(new BigDecimal(singleFood));
		map.put("singleFood", singleFood);//单品
		map.put("soupFood", soupFood);//工作餐
		map.put("fruitFood", fruitFood);//会议餐
		map.put("groupFood", String.valueOf(group));//组合
		sum = new BigDecimal(singleFood).add(group);//总份数
		map.put("totalNum", String.valueOf(sum));//总份数
		BigDecimal rate = new BigDecimal("0");
		//1年2季度3月
		if (dateType == 1) {
			int yearSum = consSize * 365;
			rate = avg.divide(new BigDecimal(yearSum), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP);
		} else if (dateType == 2) {
			int quarterSum = consSize * 90;
			rate = avg.divide(new BigDecimal(quarterSum), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP);
		} else if (dateType == 3) {
			int monthSum = consSize * 30;
			if (monthSum != 0) {
				rate = avg.divide(new BigDecimal(monthSum), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP);
			}
		}
		map.put("rate", rate + "%");//订餐率
		if (BigDecimal.ZERO.compareTo(sum) < 0) {
			sumList.add(map);
		}
		return sumList;

	}

	@Override
	public List<Map<String, Object>> getConsOrderList(String orgId,
													  int dateType, String year, String time) {
		List<Map<String, Object>> list = orderDinnerDao.getConsumerOrderList(orgId, dateType, year, time);
		return list;
	}

	@Override
	public List<Map<String, Object>> getStarOrderList(String orgId,
													  int dateType, String year, String time) {
		List<OrderDinner> orderList = orderDinnerDao.getOrderDinnerByOrgId(orgId, "2,3");
		int               orderSize = 0;
		if (orderList != null) {
			orderSize = orderList.size();
		}
		List<Map<String, Object>> sumOrderList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> list         = orderDinnerDao.getStarOrderList(orgId, dateType, year, time);
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				BigDecimal          rate  = new BigDecimal("0");
				Map<String, Object> map   = list.get(i);
				String              star  = map.get("star") == null ? "0" : map.get("star").toString();
				String              count = map.get("sumCount") == null ? "0" : map.get("sumCount").toString();
				if (StringUtils.isNotEmpty(count) && orderSize != 0) {
					rate = new BigDecimal(count).divide(new BigDecimal(orderSize), 6, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP);
				}
				if ("1".equals(star)) {
					map.put("starStr", "一星");
				} else if ("2".equals(star)) {
					map.put("starStr", "二星");
				} else if ("3".equals(star)) {
					map.put("starStr", "三星");
				} else if ("4".equals(star)) {
					map.put("starStr", "四星");
				} else if ("5".equals(star)) {
					map.put("starStr", "五星");
				}
				map.put("rate", rate + "%");
				sumOrderList.add(map);
			}
		}
		return sumOrderList;
	}

	@Override
	public List<Map<String, Object>> getDeptOrderList(String orgId,
													  int dateType, String year, String time) {
		List<Map<String, Object>> foodList = orderDinnerDao.getFoodListByDept(orgId, dateType, year, time);
		List<Map<String, Object>> list     = getDeptOrderInfo(foodList, orgId, dateType, year, time);
		return list;
	}

	public List<Map<String, Object>> getDeptOrderInfo(List<Map<String, Object>> foodList, String orgId,
													  int dateType, String year, String time) {
		List<Map<String, Object>> mapList    = new ArrayList<Map<String, Object>>();
		List<Element>             stapleFood = elementGroupDao.getElementsByGroupName("stapleFood");
		List<Element>             deptList   = elementGroupDao.getElementsByGroupName("dinnerDept");
		if (deptList != null && deptList.size() > 0) {
			for (int i = 0; i < deptList.size(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				Element             e   = deptList.get(i);
				if (e == null) {
					continue;
				}
				map.put("dept", e.getItemname());
				//规格 1单品2三菜一汤3三菜一汤加水果
				BigDecimal sum        = new BigDecimal("0");
				BigDecimal group      = new BigDecimal("0");//组合
				BigDecimal avg        = new BigDecimal("0");
				int        totalNum   = 0;
				int        singleFood = orderDinnerDao.getMeetCountByDept(orgId, dateType, year, time, 3, e.getId().toString());//单品
				int        soupFood   = orderDinnerDao.getMeetCountByDept(orgId, dateType, year, time, 2, e.getId().toString());//工作餐
				int        fruitFood  = orderDinnerDao.getMeetCountByDept(orgId, dateType, year, time, 1, e.getId().toString());//会议餐
				int        tempFood   = orderDinnerDao.getMeetCountByDept(orgId, dateType, year, time, 4, e.getId().toString());//临时工作餐
				group = new BigDecimal(soupFood).add(new BigDecimal(fruitFood));//组合是否需要累计临时工作餐的为组合的数量
				avg = new BigDecimal(soupFood).add(new BigDecimal(singleFood));
				map.put("singleFood", singleFood);//单品
				map.put("soupFood", soupFood);//工作餐
				map.put("fruitFood", fruitFood);//会议餐
				map.put("groupFood", String.valueOf(group));//组合
				sum = new BigDecimal(singleFood).add(group);//总份数
				totalNum = singleFood + soupFood + fruitFood;
				map.put("totalNum", String.valueOf(sum));//总份数
				if (foodList != null && foodList.size() > 0) {
					for (int j = 0; j < foodList.size(); j++) {
						Map<String, Object> specMap       = foodList.get(j);
						String              dept          = specMap.get("dept") == null ? "" : specMap.get("dept").toString();
						String              stapleFoodStr = specMap.get("stapleFoodStr") == null ? "" : specMap.get("stapleFoodStr").toString();
						if (e.getItemname().equals(dept)) {//部门名称相同时，进行汇总
							if (stapleFood != null && stapleFood.size() > 0) {
								for (int k = 0; k < stapleFood.size(); k++) {
									Element eFood = stapleFood.get(k);
									map.put(eFood.getItemcode(), "0");
									if (eFood.getItemname().equals(stapleFoodStr)) {
										String sumCount = specMap.get("sumCount") == null ? "0" : specMap.get("sumCount").toString();
										map.put(eFood.getItemcode(), sumCount);
									}
								}
							}
						}
					}
				}
				if (totalNum > 0) {
					mapList.add(map);
				}
			}
		}
		return mapList;
	}

	@Override
	public List<OrderDinner> getOrderDinnerByParentOrderId(String parentId, String status) {
		return orderDinnerDao.getOrderInfoByParentOrderId(parentId, status);
	}

	@Override
	public String getOrderTime(String orgId, String elName) {
		List<ElementDto> elList      = elementGroupManager.getOrgElementGroupInfo(Integer.parseInt(orgId), elName);
		String           sysDate     = DateUtils.formatDate(new Date(), "HHmmss");
		String           eleventTime = "110000";
		if (elList != null && elList.size() > 0) {
			ElementDto el = elList.get(0);
			if (el != null) {
				eleventTime = el.getItemname();
			}
		}
		int orderTime = Integer.parseInt(eleventTime);
		int dateTime  = Integer.parseInt(sysDate);
		if (dateTime > orderTime) {//如果当前时间大于订餐截止时间，那么不允许再订餐
			String res = eleventTime.substring(0, 2) + ":" + eleventTime.substring(2, 4) + ":" + eleventTime.substring(4, 6);
			return res;
		}
		return "";
	}

	@Override
	public String getOrderTimeStr(String orgId, String elName) {
		List<ElementDto> elList      = elementGroupManager.getOrgElementGroupInfo(Integer.parseInt(orgId), elName);
		String           sysDate     = DateUtils.formatDate(new Date(), "HHmmss");
		String           eleventTime = "110000";
		if (elList != null && elList.size() > 0) {
			ElementDto el = elList.get(0);
			if (el != null) {
				eleventTime = el.getItemname();
			}
		}
		//+":"+eleventTime.substring(4,6)
		String res = eleventTime.substring(0, 2) + ":" + eleventTime.substring(2, 4);
		return res;
	}

	@Override
	public int isOver(String orgId, String elName) {
		int    isOver = 0;
		String res    = getOrderTime(orgId, elName);
		if (StringUtils.isNotEmpty(res)) {//超出
			isOver = 1;
		}
		return isOver;
	}

	@Override
	public int updateOrderDinnerByTime(String orgIds, String time) {
		return orderDinnerDao.updateOrderDinnerByTime(orgIds, time);
	}

	@Override
	public List<Map<String, Object>> getAllMealName(String orgId) {
		return orderDinnerDao.getAllMealName(orgId);
	}

	@Override
	public List<Map<String, Object>> getMealRanking(String orgId) {
		return orderDinnerDao.getMealRanking(orgId);
	}

	@Override
	public List<Map<String, Object>> exportByAddress(String orgId,String date) {
		List<Map<String, Object>> infoList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> mealList = getAllItemMeal(orgId);
		Map<String, Object>       hejiMap  = new HashMap<String, Object>();
		hejiMap.put("address", "");
		hejiMap.put("deptname", "总合计");
		Map<String, Object> bunsMap  = getFoodItem(orgId, "stapleFood", "馒头");
		Map<String, Object> rollMap  = getFoodItem(orgId, "stapleFood", "花卷");
		int                 allCount = 0;
		if (mealList != null && mealList.size() > 0) {
			List<Map<String, Object>> mapList = getSysDateData(orgId, mealList,date);
			mealList.add(bunsMap);
			mealList.add(rollMap);
			infoList.addAll(mapList);
			for (int k = 0; k < mealList.size(); k++) {
				int                 sumCount    = 0;
				Map<String, Object> meal        = mealList.get(k);
				String              mealNamePin = ChineseCharacterUtil.getPingYin(meal.get("mealName").toString());
				if (mapList != null && mapList.size() > 0) {
					for (int i = 0; i < mapList.size(); i++) {
						Map<String, Object> map   = mapList.get(i);
						int                 count = 0;
						if (map.get(mealNamePin) != null && StringUtil.isNotEmpty(map.get(mealNamePin).toString())) {
							count = Integer.parseInt(map.get(mealNamePin).toString());
						}
						if (!"合计".equals(map.get("deptname"))) {
							sumCount = sumCount + count;
						}
					}
				}
				hejiMap.put(mealNamePin, sumCount);
				if (!"mantou".equals(mealNamePin) && !"huajuan".equals(mealNamePin)) {
					allCount = allCount + sumCount;
				}
			}
			hejiMap.put("heji", allCount);
		}
		infoList.add(hejiMap);
		return infoList;
	}

	private List<Map<String, Object>> getSysDateData(String orgId, List<Map<String, Object>> mealList,String date) {
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		List<ElementDto>          els     = elementGroupManager.getOrgElementGroupInfo(Integer.parseInt(orgId), "dinnerAddress");
		Collections.sort(els, new Comparator<ElementDto>() {
			public int compare(ElementDto o1, ElementDto o2) {
				String name1 = o1.getSort().toString();//name1是从你list里面拿出来的一个
				String name2 = o2.getSort().toString(); //name1是从你list里面拿出来的第二个name
				return name1.compareTo(name2);
			}
		});
		if (els != null && els.size() > 0) {
			for (int i = 0; i < els.size(); i++) {
				if (els.get(i) != null) {
					ElementDto dto = els.get(i);
					//地址
					String  addressOrgId = dto.getId().toString();
					Element el           = elementGroupManager.getByItemname("dinnerAddress", dto.getItemname());
					String  addressId    = "";
					if (el != null) {
						addressId = el.getId().toString();
					}
					List<Map<String, Object>> list = getAddressInfoList(orgId, addressId, addressOrgId,date);//getUserAndDeptByAddress(orgId, addressId,mealList);
					mapList.addAll(list);
				}
			}
		}
		return mapList;
	}

	private Map<String, Object> getFoodItem(String orgId, String code, String name) {
		Element             el    = elementGroupDao.getByItemname(code, name);
		OrgElement          orgEl = elementGroupDao.getByItemname(orgId, code, name);
		Map<String, Object> map   = new HashMap<String, Object>();
		if (orgEl != null) {
			if (el != null) {
				map.put("itemId", el.getId().toString());
			} else {
				map.put("itemId", "");
			}
			map.put("itemOrgId", orgEl.getId().toString());
			map.put("mealName", name);
		} else if (el != null) {
			map.put("itemId", el.getId().toString());
			map.put("itemOrgId", "");
			map.put("mealName", name);
		}
		return map;
	}

	/**
	 * 根据地址获取该地址下所有信息
	 *
	 * @param addressId`
	 * @return
	 */
	private List<Map<String, Object>> getAllInfoByAddress(String orgId, String addressId, String addressOrgId,String date) {
		//汇总领导、部门
		//List<Map<String, Object>> userList = orderDinnerDao.getUserByOrgAddress(orgId, addressId, addressOrgId);//不取领导，把领导配置为部门 by qzy
		List<Map<String, Object>> userList = new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> deptList = orderDinnerDao.getDeptByOrgAddress(orgId, addressId, addressOrgId,date);
		userList.addAll(deptList);
		return userList;
	}

	/**
	 * 获取组合餐品名及单品餐品名
	 *
	 * @param orgId
	 * @return
	 */
	private List<Map<String, Object>> getAllItemMeal(String orgId) {
		List<Map<String, Object>> zuMealList  = getAllItemMeal(orgId, "mealName");
		List<Map<String, Object>> danMealList = getAllItemMeal(orgId, "mealNameBySingle");
		zuMealList.addAll(danMealList);
		return zuMealList;
	}

	/**
	 * 将分项目级别的餐品名和非分项目级别的餐品名汇总
	 *
	 * @param orgId
	 * @param groupCode
	 * @return
	 */
	private List<Map<String, Object>> getAllItemMeal(String orgId, String groupCode) {
		List<Map<String, Object>> mapList        = new ArrayList<Map<String, Object>>();
		List<OrgElement>          orgElementList = elementGroupDao.getElementListByOrgAndGroup(groupCode, Integer.parseInt(orgId));
		List<Element>             elements       = elementGroupDao.getElementsByGroupName(groupCode);
		if (orgElementList != null && orgElementList.size() > 0) {
			for (int i = 0; i < orgElementList.size(); i++) {
				Map<String, Object> map   = new HashMap<String, Object>();
				OrgElement          orgEl = orgElementList.get(i);
				if (orgEl != null) {
					Element el = elementGroupDao.getByItemname(groupCode, orgEl.getItemname());
					if (el != null) {
						map.put("itemId", el.getId().toString());
					} else {
						map.put("itemId", "");
					}
					map.put("itemOrgId", orgEl.getId().toString());
					map.put("mealName", orgEl.getItemname());
					mapList.add(map);
				}
			}
		} else if (elements != null && elements.size() > 0) {
			for (int i = 0; i < elements.size(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				Element             el  = elements.get(i);
				if (el != null) {
					map.put("itemId", el.getId().toString());
					map.put("itemOrgId", "");
					map.put("mealName", el.getItemname());
					mapList.add(map);
				}

			}
		}
		return mapList;
	}

	/**
	 * 设置地址相关信息
	 *
	 * @param orgId
	 * @param addressId
	 * @param addressOrgId
	 * @return
	 */
	private List<Map<String, Object>> getAddressInfoList(String orgId, String addressId, String addressOrgId,String date) {
		List<Map<String, Object>> infoList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> mapList  = getAllInfoByAddress(orgId, addressId, addressOrgId,date);
		int                       rollsSum = 0;
		int                       bunsSum  = 0;
		if (mapList != null && mapList.size() > 0) {
			for (int i = 0; i < mapList.size(); i++) {
				Map<String, Object> info = new HashMap<String, Object>();
				Map<String, Object> map  = mapList.get(i);
				if (map != null) {
					String address  = map.get("address") == null ? "" : map.get("address").toString();
					String deptname = map.get("deptname") == null ? "" : map.get("deptname").toString();
					int    type     = Integer.parseInt(map.get("type") + "");
					String id       = map.get("id") == null ? "" : map.get("id").toString();
					if (StringUtil.isNotEmpty(id)) {
						info.put("address", address);
						info.put("deptname", deptname);
						if (1 == type) {//是否为用户
							info = setInfo(orgId, addressId, addressOrgId, id, "", info,date);
							infoList.add(info);
						} else if (2 == type) {//是否为部门
							info = setInfo(orgId, addressId, addressOrgId, "", id, info,date);
							int count = info.get("heji") == null ? 0 : Integer.parseInt(info.get("heji").toString());
							if (count > 0) {
								infoList.add(info);
							}
						}
						int rolls = info.get(CodeConstants.ROLLS) == null ? 0 : Integer.parseInt(info.get(CodeConstants.ROLLS).toString());
						int buns  = info.get(CodeConstants.BUNS) == null ? 0 : Integer.parseInt(info.get(CodeConstants.BUNS).toString());
						rollsSum = rollsSum + rolls;
						bunsSum = bunsSum + buns;
					}
				}
			}
			//求每个地址的汇总
			Map<String, Object> heji = new HashMap<String, Object>();
			heji.put("address", "");
			heji.put("deptname", "合计");
			List<Map<String, Object>> addList = orderDinnerDao.getCountByAddress(orgId, addressId, addressOrgId,date);
			if (addList != null && addList.size() > 0) {
				int sumAddHeji = 0;
				for (int i = 0; i < addList.size(); i++) {
					Map<String, Object> map      = addList.get(i);
					String              mealName = map.get("mealName") == null ? "" : map.get("mealName").toString();
					int                 sumCount = map.get("sumCount") == null ? 0 : Integer.parseInt(map.get("sumCount").toString());
					heji.put(ChineseCharacterUtil.getPingYin(mealName), sumCount);
					sumAddHeji = sumAddHeji + sumCount;
				}
				heji.put("heji", sumAddHeji);
			}
			heji.put(CodeConstants.ROLLS, rollsSum);
			heji.put(CodeConstants.BUNS, bunsSum);
			infoList.add(heji);
			Map<String, Object> mapNull = new HashMap<String, Object>();
			infoList.add(mapNull);
		}
		return infoList;
	}

	/**
	 * 设置用户及部门的具体餐品相应的信息
	 *
	 * @param orgId
	 * @param userId
	 * @param deptId
	 * @param info
	 * @return
	 */
	private Map<String, Object> setInfo(String orgId, String addressId, String addressOrgId, String userId, String deptId, Map<String, Object> info,String date) {
		List<Map<String, Object>> mapList = orderDinnerDao.getCountByUserOrDept(orgId, userId, addressId, addressOrgId, deptId,date);
		int                       sumHe   = 0;
		if (mapList != null && mapList.size() > 0) {
			for (int i = 0; i < mapList.size(); i++) {
				Map<String, Object> map = mapList.get(i);
				if (map != null) {
					String mealName = map.get("mealName") == null ? "" : map.get("mealName").toString();
					int    sumCount = map.get("sumCount") == null ? 0 : Integer.parseInt(map.get("sumCount").toString());
					if (StringUtil.isNotEmpty(mealName)) {
						String mealNamePin = ChineseCharacterUtil.getPingYin(mealName);
						if (info.containsKey(mealNamePin) && StringUtil.isNotEmpty(info.get(mealNamePin).toString())) {
							int count = sumCount + Integer.parseInt(info.get(mealNamePin).toString());
							info.put(mealNamePin, count);
						} else {
							info.put(mealNamePin, sumCount);
						}

						sumHe = sumHe + sumCount;
					}
				}
			}
		}
		//增加换花卷、换馒头
		int                 rollCount = 0;
		int                 bunsCount = 0;
		Map<String, Object> bunsMap   = getFoodItem(orgId, "stapleFood", "馒头");
		Map<String, Object> rollMap   = getFoodItem(orgId, "stapleFood", "花卷");
		if (StringUtil.isNotEmpty(userId)) {//是否为用户
			rollCount = orderDinnerDao.getCountByUserAndMealFood(userId, rollMap.get("itemId").toString(), rollMap.get("itemOrgId").toString(),date);
			bunsCount = orderDinnerDao.getCountByUserAndMealFood(userId, bunsMap.get("itemId").toString(), bunsMap.get("itemOrgId").toString(),date);
		} else if (StringUtil.isNotEmpty(deptId)) {//是否为部门
			rollCount = orderDinnerDao.getCountByDeptAndMealFood(addressId, addressOrgId, deptId, rollMap.get("itemId").toString(), rollMap.get("itemOrgId").toString(),date);
			bunsCount = orderDinnerDao.getCountByDeptAndMealFood(addressId, addressOrgId, deptId, bunsMap.get("itemId").toString(), bunsMap.get("itemOrgId").toString(),date);
		}
		info.put(CodeConstants.BUNS, bunsCount);
		info.put(CodeConstants.ROLLS, rollCount);
		info.put("heji", sumHe);
		return info;
	}

	/**
	 * 根据所有餐品获取相应的titles及fieldNames
	 *
	 * @param mapList
	 * @param arr
	 * @return
	 */
	@Override
	public String[] getTitles(List<Map<String, Object>> mapList, String[] arr,
							  int type) {
		if (mapList != null && mapList.size() > 0) {
			for (int i = 0; i < mapList.size(); i++) {
				Map<String, Object> map      = mapList.get(i);
				String              mealname = map.get("mealname") == null ? "" : map.get("mealname").toString();
				if (type == 1 && StringUtil.isNotEmpty(mealname)) {//获取标题
					arr = StringUtil.insert(arr, mealname);
				} else if (type == 2 && StringUtil.isNotEmpty(mealname)) {
					arr = StringUtil.insert(arr, ChineseCharacterUtil.getPingYin(mealname));
				}
			}
		}
		return arr;
	}

	@Override
	public List<Map<String, Object>> getDinnerDataByInfo(String orgId, int dateType, String date, String endDate) {
		return orderDinnerDao.getDinnerDataByInfo(orgId, dateType, date, endDate);
	}

	@Override
	public List<Map<String, Object>> getVisitorDataByInfo(String orgId,
														  int dateType, String date, String endDate) {
		return orderDinnerDao.getVisitorDataByInfo(orgId, dateType, date, endDate);
	}

	@Override
	public List<Map<String, Object>> getPlatformDataByInfo(String orgId,
														   int dateType, String date, String endDate, String dateString) {
		log.info("begin:dateType:" + dateType + ";date:" + date + ";endDate:" + endDate);
		//用户总数、平台使用数
		List<Map<String, Object>> list = orderDinnerDao.getOrgUser(orgId, dateType, date, endDate);
		//平台活跃度
		Map<String, Map<String, Object>> formLiveMap = getPlatformLiveness(orgId, dateType, date, endDate);
		//等于月份时
		if (dateType == 3) {
			String month = date.split("-")[1];
			endDate = month;
		}
		log.info("end:dateType:" + dateType + ";date:" + date + ";endDate:" + endDate);
		//会议室数据
		List<MeetintDto> mapList = getMeetingInfoList(orgId, dateType, date, endDate);
		//将平台活跃度、时间内新增用户数放到list中
		setPlatformData(orgId, list, formLiveMap, dateString, mapList);
		return list;
	}

	/**
	 * 将平台活跃度、时间内新增用户数放到list中
	 *
	 * @param list
	 * @param formLiveMap
	 */
	private void setPlatformData(String orgId, List<Map<String, Object>> list, Map<String, Map<String, Object>> formLiveMap, String dateString, List<MeetintDto> mapList) {
		//将平台活跃度、时间内新增用户数放到list中
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = list.get(i);
				map.put("orderno", (i + 1));
				map.put("dateInfo", dateString);
				if (map != null && map.containsKey("orgId") && map.get("orgId") != null) {
					String userOrg = map.get("orgId").toString();
					if (map.get("accountType") != null && StringUtil.isNotEmpty(map.get("accountType").toString())) {
						String accountType = map.get("accountType").toString();
						//企业账号
						if ("0".equals(accountType)) {
							map.put("accountTypeStr", "企业账号");
						} else if ("1".equals(accountType)) {
							//个人账号
							map.put("accountTypeStr", "个人账号");
						}
					}
					//设置会议室使用数
					if (StringUtil.isNotEmpty(userOrg)) {
						TbOrganization tbOrg = organizationManager.getOrganizationById(Integer.parseInt(userOrg));
						if (tbOrg != null && mapList != null && mapList.size() > 0) {
							for (int k = 0; k < mapList.size(); k++) {
								MeetintDto dto = mapList.get(k);
								//如果项目相等，就设置meetCount
								if (userOrg.equals(dto.getOrgId())) {
									map.put("meetCount", dto.getReportnum());
								}
							}
						}
					}
					//平台活跃度
					if (formLiveMap.containsKey(userOrg)) {
						Map<String, Object> liveMap = formLiveMap.get(userOrg);
//							 map.put("meetCount", 0);
						//把liveMap中的值拷贝到map中
						MapUtils.mapCopy(liveMap, map);
					}
				}
			}
		}
	}

	/**
	 * 获取各大平台的活跃度
	 *
	 * @param orgId
	 * @param dateType
	 * @param date
	 * @param endDate
	 * @return
	 */
	private Map<String, Map<String, Object>> getPlatformLiveness(String orgId, int dateType, String date, String endDate) {
		List<Map<String, Object>>        mapList        = orderDinnerDao.getPlatformDataByInfo(orgId, dateType, date, endDate);//数据库中查询到的所有项目相应服务的活跃度
		Map<String, Map<String, Object>> formLiveMap    = new HashMap<String, Map<String, Object>>();
		List<Map<String, Object>>        userActiveList = userDateActiveDao.getUserDateActive(orgId, dateType, date, endDate);
		if (mapList != null && mapList.size() > 0) {
			for (int i = 0; i < mapList.size(); i++) {
				Map<String, Object> map = mapList.get(i);
				if (map != null && map.containsKey("orgId") && map.get("orgId") != null) {
					String liveOrg      = map.get("orgId").toString();
					String code         = map.get("code") == null ? "" : map.get("code").toString();
					String serviceCount = map.get("serviceCount") == null ? "0" : map.get("serviceCount").toString();
					if (formLiveMap.containsKey(liveOrg)) {
						//判断formLiveMap中是否存在key为liveOrg项目的，如果存在，直接获取这个map，往这个map里面塞新的值
						Map<String, Object> formMap = formLiveMap.get(liveOrg);
						formMap.put(code.toLowerCase(), Integer.parseInt(serviceCount));
					} else {
						//如果该formLiveMap不存在key为liveOrg项目的，直接往formLiveMap中put一个新的键为liveOrg项目，值为新map的
						Map<String, Object> formMap = new HashMap<String, Object>();
						formMap.put(code.toLowerCase(), Integer.parseInt(serviceCount));
						formLiveMap.put(liveOrg, formMap);
					}
				}
			}
		}

		if (userActiveList != null && userActiveList.size() > 0) {
			for (int i = 0; i < userActiveList.size(); i++) {
				Map<String, Object> map = userActiveList.get(i);
				if (map != null && map.containsKey("orgId") && map.get("orgId") != null) {
					String liveOrg     = map.get("orgId").toString();
					String activeCount = map.get("activeCount") == null ? "0" : map.get("activeCount").toString();
					if (formLiveMap.containsKey(liveOrg)) {
						//判断formLiveMap中是否存在key为liveOrg项目的，如果存在，直接获取这个map，往这个map里面塞新的值
						Map<String, Object> formMap = formLiveMap.get(liveOrg);
						formMap.put("activeCount", Integer.parseInt(activeCount));
					} else {
						//如果该formLiveMap不存在key为liveOrg项目的，直接往formLiveMap中put一个新的键为liveOrg项目，值为新map的
						Map<String, Object> formMap = new HashMap<String, Object>();
						formMap.put("activeCount", Integer.parseInt(activeCount));
						formLiveMap.put(liveOrg, formMap);
					}
				}
			}
		}
		return formLiveMap;
	}

	@Override
	public List<MeetintDto> getMeetingInfoList(String orgId, int dateType,
											   String date, String endDate) {
		List<MeetintDto> mapList    = new ArrayList<MeetintDto>();
		String           dateString = StringUtil.getDateString(dateType, date, endDate, 2);
		String           year       = "";
		String           quarter    = "";
		String           month      = "";
		String           day        = "";
		String           day2       = "";
		String           reportType = "all";
		String           client     = "";
		String           limit      = Integer.MAX_VALUE + "";
		String           Page       = "1";
		try {
			if (StringUtil.isNotEmpty(orgId)) {
				TbOrganization org = organizationManager.getOrganizationById(Integer.parseInt(orgId));
				if (org != null && StringUtil.isNotEmpty(org.getMettingClient())) {
					client = org.getMettingClient();
				}
				if (!StringUtil.isNotEmpty(client)) {
					return null;
				}
			}

			Map<String, String> map = getQuarter(date);
			if (null != map && map.containsKey("year") && StringUtils.isNotEmpty(map.get("year"))) {
				date = map.get("year");
			}

			if (null != map && map.containsKey("quarter") && StringUtils.isNotEmpty(map.get("quarter"))) {
				endDate = map.get("quarter");

			}
			//1年2季度3月4日
			if (dateType == 1) {
				year = date;
				reportType = "year";
			} else if (dateType == 2) {
				year = date;
				quarter = endDate;
				reportType = "quarter";
			} else if (dateType == 3) {
				year = date;
				month = endDate;
				reportType = "month";
			} else if (dateType == 4) {
				day = date;
				day2 = endDate;
				reportType = "day";
			}
			mapList = getMeetInfo(year, quarter, month, day, day2, reportType, client, limit, Page);
			mapList = setMeetList(mapList, dateString);

		} catch (Exception e) {
			log.error("会议室统计失败：" + e.getMessage());
			e.printStackTrace();
		}
		return mapList;
	}

	public Map<String, String> getQuarter(String date) {
		Map<String, String> map = new HashMap<String, String>();
		if (StringUtil.isNotEmpty(date)) {
			String[] dateArr = date.split("-");
			if (dateArr != null && dateArr.length == 2) {
				map.put("year", dateArr[0]);
				map.put("quarter", dateArr[1]);
			}
		}
		return map;
	}

	/**
	 * 调用会议室接口
	 *
	 * @param year
	 * @param quarter
	 * @param month
	 * @param day
	 * @param day2
	 * @param reportType
	 * @param client
	 * @param limit
	 * @param Page
	 * @return
	 */
	private List<MeetintDto> getMeetInfo(String year, String quarter, String month, String day
			, String day2, String reportType, String client, String limit, String Page) {
		String url = MEETURL + "/Login/GetReportDataByClient";
		String paramentStr = "year=" + year + "&quarter=" + quarter
				+ "&month=" + month + "&day=" + day + "&day2=" + day2
				+ "&reportType=" + reportType + "&client=" + client + "&limit=" + limit
				+ "&Page=" + Page;
		List<MeetintDto> mapList = new ArrayList<MeetintDto>();
		try {
			String res = HttpKit.Post(paramentStr, url);
			System.out.println(res);
			if (StringUtil.isNotEmpty(res)) {
				net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(res);
				if (jsonObj != null) {
					net.sf.json.JSONArray jsonArray = (net.sf.json.JSONArray) jsonObj.get("data");
					if (jsonArray != null) {
						mapList = net.sf.json.JSONArray.toList(jsonArray, new MeetintDto(), new JsonConfig());
					}
				}
			}
		} catch (Exception e) {
			log.error("调用会议室接口失败getMeetInfo:" + e.getMessage());
			e.printStackTrace();
		}
		return mapList;
	}

	private List<MeetintDto> setMeetList(List<MeetintDto> meetList, String dateString) {
		List<MeetintDto> mapList = new ArrayList<MeetintDto>();
		if (meetList != null && meetList.size() > 0) {
			MeetintDto dto = new MeetintDto();
			dto.setOrgName("合计");
			dto.setDateInfo(dateString);
			dto.setOrderno(0);
			int        reportnum     = 0;//预定会议室次数
			BigDecimal usetime       = new BigDecimal("0");//使用时长
			BigDecimal usemoney      = new BigDecimal("0");//预定会议室费用
			BigDecimal freenum       = new BigDecimal("0");//减免时长使用数
			BigDecimal freemoney     = new BigDecimal("0");//减免时长扣减费用
			BigDecimal servicesmoney = new BigDecimal("0");//附加服务费用
			BigDecimal amount        = new BigDecimal("0");//费用
			BigDecimal monthamount   = new BigDecimal("0");//月结费用
			BigDecimal totalamount   = new BigDecimal("0");//总费用
			for (int i = 0; i < meetList.size(); i++) {
				MeetintDto platMap = meetList.get(i);
				if (platMap != null && StringUtil.isNotEmpty(platMap.getClient())) {
					String         client = platMap.getClient();
					TbOrganization org    = organizationManager.getByMettingClient(client);
					if (org != null) {
						platMap.setDateInfo(dateString);
						platMap.setOrderno((i + 1));
						platMap.setOrgName(org.getName());
						platMap.setOrgId(org.getId().toString());
						if (platMap.getReportnum() != null) {
							reportnum = reportnum + platMap.getReportnum();
						}
						usetime = usetime.add(platMap.getUsetime());
						usemoney = usemoney.add(platMap.getUsemoney());
						freenum = freenum.add(platMap.getFreenum());
						freemoney = freemoney.add(platMap.getFreemoney());
						servicesmoney = servicesmoney.add(platMap.getServicesmoney());
						amount = amount.add(platMap.getAmount());
						monthamount = monthamount.add(platMap.getMonthamount());
						totalamount = totalamount.add(platMap.getTotalamount());
						mapList.add(platMap);
					}
				}
			}
			dto.setReportnum(reportnum);
			dto.setUsetime(usetime.setScale(2, BigDecimal.ROUND_HALF_UP));
			dto.setUsemoney(usemoney.setScale(2, BigDecimal.ROUND_HALF_UP));
			dto.setFreenum(freenum.setScale(2, BigDecimal.ROUND_HALF_UP));
			dto.setFreemoney(freemoney.setScale(2, BigDecimal.ROUND_HALF_UP));
			dto.setServicesmoney(servicesmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
			dto.setAmount(totalamount.setScale(2, BigDecimal.ROUND_HALF_UP));
			dto.setMonthamount(monthamount.setScale(2, BigDecimal.ROUND_HALF_UP));
			dto.setTotalamount(totalamount.setScale(2, BigDecimal.ROUND_HALF_UP));
			mapList.add(dto);
			//排序
			Collections.sort(mapList, new Comparator<MeetintDto>() {
				public int compare(MeetintDto o1, MeetintDto o2) {
					Integer name1 = o1.getOrderno();//name1是从你list里面拿出来的一个
					Integer name2 = o2.getOrderno();//name1是从你list里面拿出来的第二个name
					return name1.compareTo(name2);
				}
			});
		}
		return mapList;
	}
}
