package com.palmnest.webapp.controller.dinner;

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.ExcelUtils;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.DeptAddressDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.AppUserInputDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.application.dto.output.IntegralRecodeDto;
import com.palmnest.model.User;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.dinner.service.ConsumerUserService;
import com.palmnest.service.dinner.service.DeptService;
import com.palmnest.service.dinner.service.IntegralRecodeInfoService;
import com.palmnest.service.dinner.service.PlaceAnOrderService;
import com.palmnest.service.notice.service.PushSendService;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.washcar.service.ElementGroupService;
import com.palmnest.webapp.controller.BaseFormController;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

/**
 * 订餐用户
 * 订餐管理  新增账号
 *
 * @author 雷晓亮
 */
@Slf4j
@Controller
@RequestMapping("/admin/appUser/*")
public class ConsumerUserController extends BaseFormController {

	
	@Autowired
	private PlaceAnOrderService placeAnOrderService;
	
	@Autowired
	private ConsumerUserService       consumerUserService;
	@Autowired
	private ElementGroupService       elementGroupService;
	@Autowired
	private IntegralRecodeInfoService integralRecodeInfoService;
	@Autowired
	private PropertyManager           propertyManager;
	@Autowired
	private DeptService               deptService;
	@Autowired
	private PushSendService           pushSendService;

	/**
	 * 获取企业
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "getVirInfo")
	@ResponseBody
	public AppResultDto getVirInfo(String orgId) {
		if (StringUtils.isEmpty(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目不允许为空");
		}
		return consumerUserService.getVirInfo(orgId);
	}

	/**
	 * 保存订餐用户信息 +修改用户信息成功
	 *
	 * @param appUserInputDto
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "saveUpdateUserInfo")
	@ResponseBody
	public AppResultDto saveAppUserInfo(AppUserInputDto appUserInputDto, MultipartHttpServletRequest request, HttpServletResponse response) {

		if (appUserInputDto != null) {

//			if(StringUtils.isEmpty(dinnerUserInputDto.getLoginName())){
//				return AppResultUtil.createErrorDto("100", "登录名不能为空");
//			}

			if (StringUtils.isEmpty(appUserInputDto.getMobilePhone())) {
				return AppResultUtil.createErrorDto("100", "手机号码不允许为空");
			}

//			if(appUserInputDto.getUserType()==0){
//				return AppResultUtil.createErrorDto("100", "用户类型不允许为空");
//			}

			if (StringUtils.isEmpty(appUserInputDto.getOrgId())) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}

		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		String result = "";

		// 人脸图片处理
		// tb_userimageinfo表中该用户对应的图片id串
		String imageUrlids = request.getParameter("imageUrlids");
		// 删除图片id串
		String removeUrlids = request.getParameter("removeUrlids");
		// 添加图片路径
		String addimgUrls = request.getParameter("addimgUrls");

		try {
			result = consumerUserService.saveUpdateUserInfo(appUserInputDto, userId, addimgUrls, imageUrlids, removeUrlids);
			if ("success".equals(result) || "true".equals(result)) {
				return AppResultUtil.createCommonDto(AppConstants.SUCCESS_CODE, "保存用户信息成功", "");
			} else if ("isExist".equals(result)) {
				return AppResultUtil.createErrorDto("100", "该账号已存在");
			} else if ("integral".equals(result)) {
				return AppResultUtil.createErrorDto("100", "积分余额必须大于等于0");
			} else {
				return AppResultUtil.createErrorDto("100", "操作失败");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "操作用户信息失败:" + e.getMessage());
		}
	}

	/**
	 * 修改订餐用户信息
	 *
	 * @param appUserInputDto
	 */
	@RequestMapping(value = "updateUserInfo")
	@ResponseBody
	public AppResultDto updateUserInfo(AppUserInputDto appUserInputDto, HttpServletRequest request, HttpServletResponse response) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		boolean result = false;
		try {
			result = consumerUserService.updateUserInfo(appUserInputDto, userId);
			if (result) {
				return AppResultUtil.createCommonDto(AppConstants.SUCCESS_CODE, "修改用户信息成功", "");
			} else {
				return AppResultUtil.createErrorDto("100", "修改失败");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "操作用户信息失败:" + e.getMessage());
		}
	}

	/**
	 * 导入用户信息
	 *
	 * @param excelFile
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "importUserInfo")
	@ResponseBody
	public AppResultDto importUserInfo(@RequestParam("excelFile") MultipartFile excelFile, HttpServletRequest request, HttpServletResponse response) throws Exception {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		String orgId  = request.getParameter("orgId");
		String virId  = request.getParameter("virId");
		String orgIds = getUserManageOrgIds(user);
		if (StringUtils.isEmpty(orgId)) {
			if (StringUtils.isNotEmpty(orgIds)) {
				String[] orgs = orgIds.split(";");
				if (orgs != null && orgs.length > 0) {
					orgId = orgIds.split(";")[0];
				}
			} else {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}
//		if(StringUtils.isEmpty(virId)) {
//			return AppResultUtil.createErrorDto("100", "企业不允许为空");
//		}
		AppResultDto dto = consumerUserService.importUserInfo(orgId, virId, excelFile.getInputStream(), userId);
		return dto;
	}

	/**
	 * 获取用户列表
	 *
	 * @param request
	 * @param dept
	 * @param mobile
	 * @param userName
	 * @param roleType
	 * @param orgId
	 * @param pageSize
	 * @param pageNo
	 * @return
	 */
	@RequestMapping(value = "getConsumerList")
	@ResponseBody
	public WebPageResultDto getConsumerList(HttpServletRequest request, String dept, String mobile, String userName,
											String roleType, String orgId, Integer pushState,int pageSize, int pageNo, Integer isEnabled) {

//		if (StringUtils.isBlank(orgId)){
//			return new 	WebPageResultDto(AppConstants.ERROR_CODE,"项目id为空","");
//		}
//
//		TbOrganization organization = propertyManager.getTbOrganizationById(Integer.parseInt(orgId));

		String              virtualArchId = request.getParameter("virtualArchId");
		Map<String, Object> paramets      = new HashMap<String, Object>();
		paramets.put("orgId", orgId);
		paramets.put("userName", userName);
		paramets.put("roleType", roleType);
		paramets.put("dept", dept);
		paramets.put("mobile", mobile);
		paramets.put("virtualArchId", virtualArchId);
		paramets.put("isEnabled", 1);
		paramets.put("status", 1);
		paramets.put("pushState", pushState);
		Page             page   = consumerUserService.findList(paramets, pageSize, pageNo);
		WebPageResultDto webDto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "", page.getItems());
		webDto.setCount(page.getTotalCount());
		return webDto;
	}
	
	
	/**
	 * 获取指定用户的所有积分记录
	 *
	 * @param orgId
	 * @param wxUserId
	 * @return
	 */
	@RequestMapping(value = "getAllIntegralRecodeList")
	@ResponseBody
	public WebPageResultDto getAllIntegralRecodeList(String orgId, String mobile,Integer type,String beginTime,String endTime,int pageSize, int pageNo) {
		
		
		Map<String, Object> paramets      = new HashMap<String, Object>();
		paramets.put("orgId", orgId);
		paramets.put("mobile", mobile);
		paramets.put("type", type);
		paramets.put("beginTime", beginTime);
		paramets.put("endTime", endTime);
		
		return placeAnOrderService.getAllIntegralRecodeList(paramets,pageSize, pageNo);
	}
	
	
	
	/**
	 * 导出指定用户的所有积分记录
	 *
	 * @param orgId
	 * @param wxUserId
	 * @return
	 * @throws IOException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	@RequestMapping(value = "getAllIntegralRecodeListExcel")
	@ResponseBody
	public WebPageResultDto getAllIntegralRecodeListExcel(String orgId, String mobile,Integer type,String beginTime,String endTime,int pageSize, int pageNo) throws IOException, IllegalArgumentException, IllegalAccessException {
		
		
		Map<String, Object> paramets      = new HashMap<String, Object>();
		paramets.put("orgId", orgId);
		paramets.put("mobile", mobile);
		paramets.put("type", type);
		paramets.put("beginTime", beginTime);
		paramets.put("endTime", endTime);
		
		List<IntegralRecodeDto>  list   = consumerUserService.getAllIntegralRecodeList(paramets);
		
		List<Map<String, Object>> lisMap = new ArrayList<Map<String,Object>>();
		for(IntegralRecodeDto dto:list){
			Field[] fields  = dto.getClass().getDeclaredFields();
			Map<String, Object> map = new HashMap<String, Object>();
			for(Field field : fields){
				field.setAccessible(true);
				map.put(field.getName(), field.get(dto));
	        }
			lisMap.add(map);
		}
	
		
		return consumerUserService.getAllIntegralRecodeListExcel(lisMap);
	}
	
	
	/**
	 * 获取用户列表
	 *
	 * @param request
	 * @param dept
	 * @param mobile
	 * @param userName
	 * @param roleType
	 * @param orgId
	 * @param pageSize
	 * @param pageNo
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "getConsumerListExcel")
	@ResponseBody
	public WebPageResultDto getConsumerListExcel(HttpServletRequest request, String dept, String mobile, String userName,
											String roleType, String orgId, int pageSize, int pageNo, Integer isEnabled) throws IOException {

//		if (StringUtils.isBlank(orgId)){
//			return new 	WebPageResultDto(AppConstants.ERROR_CODE,"项目id为空","");
//		}
//
//		TbOrganization organization = propertyManager.getTbOrganizationById(Integer.parseInt(orgId));

		String              virtualArchId = request.getParameter("virtualArchId");
		Map<String, Object> paramets      = new HashMap<String, Object>();
		paramets.put("orgId", orgId);
		paramets.put("userName", userName);
		paramets.put("roleType", roleType);
		paramets.put("dept", dept);
		paramets.put("mobile", mobile);
		paramets.put("virtualArchId", virtualArchId);
		paramets.put("isEnabled", 1);
		paramets.put("status", 1);
		List<Map<String,Object>>  list   = consumerUserService.findListForReport(paramets);
		
		
		return consumerUserService.findListReportExcel(list);
		

		
	}	

	
	

	/**
	 * 获取员工通行列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getEmployeeList")
	@ResponseBody
	public WebPageResultDto getEmployeeList(HttpServletRequest request) {

		String orgId         = request.getParameter("orgId");
		String virtualArchId = request.getParameter("virtualArchId");
		String mobile        = request.getParameter("mobile");
		String userName      = request.getParameter("userName");
		String pageSize      = request.getParameter("pageSize");
		String pageNo        = request.getParameter("pageNo");
		// 是否分配权限组 0-未分配 1-已分配 不传或者空 全部
		String hasPermGroup = request.getParameter("hasPermGroup");

		if (StringUtils.isBlank(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "10";
		}

		if (StringUtils.isBlank(orgId)) {
			return new WebPageResultDto(AppConstants.ERROR_CODE, "项目id为空", "");
		}

		TbOrganization organization = propertyManager.getTbOrganizationById(Integer.parseInt(orgId));

		Map<String, Object> paramets = new HashMap<String, Object>();
		paramets.put("orgId", orgId);
		paramets.put("userName", userName);
		paramets.put("mobile", mobile);
		paramets.put("virtualArchId", virtualArchId);
		paramets.put("hasPermGroup", hasPermGroup);

		Page             page   = consumerUserService.findEmployeeList(paramets, Integer.parseInt(pageSize), Integer.parseInt(pageNo));
		WebPageResultDto webDto = new WebPageResultDto(AppConstants.SUCCESS_CODE, organization.getPassType().toString(), page.getItems());
		webDto.setCount(page.getTotalCount());
		return webDto;
	}

	/**
	 * 禁用、启用、删除用户
	 *
	 * @param request
	 * @param id
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "updateConsumer")
	@ResponseBody
	public AppResultDto updateConsumer(HttpServletRequest request, Integer id, int type) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		if (null == id) {
			return AppResultUtil.createErrorDto("100", "id不能为空");
		}
		return consumerUserService.updateConsumer(id, type, userId);
	}

	/**
	 * 获取用户详情
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "getConsumerInfo")
	@ResponseBody
	public AppResultDto getConsumerInfo(Integer id) {
		if (null != id) {
			return consumerUserService.findById(id);
		}
		return AppResultUtil.createErrorDto("100", "账号必选");
	}

	/**
	 * 获取部门的接口
	 *
	 * @param orgId
	 * @param virId
	 * @return
	 */
	@RequestMapping(value = "getDept")
	@ResponseBody
	public AppResultDto getDept(String orgId, String virId) {
		List<DeptAddressDto> dtoList = deptService.getAllDept(orgId, virId, "");
		return AppResultUtil.createSuccesDto(dtoList);
	}

	/**
	 * 获取部门或地址
	 *
	 * @return
	 */
	@RequestMapping(value = "getDeptAndAddress")
	@ResponseBody
	public AppResultDto getDeptAndAddress(String orgId, int type) {
		if (StringUtils.isEmpty(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目不允许为空");
		}
		//获取地址
		if (type == 2) {
//			List<Element> addressList=elementGroupService.getElementsByGroupName("dinnerAddress");
			List<ElementDto> addressDtoList = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "dinnerAddress");
			Collections.sort(addressDtoList, new Comparator<ElementDto>() {
				@Override
				public int compare(ElementDto o1, ElementDto o2) {
					String name1 = o1.getId().toString();
					String name2 = o2.getId().toString();
					return name1.compareTo(name2);
				}
			});
			return AppResultUtil.createSuccesDto(addressDtoList);
		}
		return AppResultUtil.createSuccesDto();
	}

	/**
	 * 操作日志
	 *
	 * @param request
	 * @param orgId
	 * @param opName
	 * @param opType
	 * @param beginTime
	 * @param endTime
	 * @param pageSize
	 * @param pageNo
	 * @return
	 */
	@RequestMapping(value = "getIntgraleList")
	@ResponseBody
	public WebPageResultDto getIntgraleList(HttpServletRequest request, String orgId, String opName, int opType, String beginTime, String endTime, int pageSize, int pageNo) {
		User user = (User) request.getSession().getAttribute("UserCache");
		if (StringUtils.isEmpty(orgId)) {
			orgId = getUserManageOrgIds(user);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orgId", orgId);
		map.put("opName", opName);
		map.put("opType", opType);
		map.put("beginTime", beginTime);
		map.put("endTime", endTime);
		Page             page   = integralRecodeInfoService.findList(map, pageSize, pageNo);
		WebPageResultDto webDto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
		webDto.setCount(page.getTotalCount());
		return webDto;
	}

	/**
	 * 获取该项目下充值设置
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "getRechargeSet")
	@ResponseBody
	public AppResultDto getRechargeSet(String orgId) {
		if (!StringUtil.isNotEmpty(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目不允许为空");
		}
		return null;
	}

	/**
	 * 获取工号
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "getUserNumber")
	@ResponseBody
	public AppResultDto getUserNumber(String id) {
		return consumerUserService.getUserNumber(id);
	}

	/**
	 * 发送短信\邮件
	 *
	 * @param userIds
	 * @param content
	 * @return
	 */
	@RequestMapping(value = "sendMessagePush")
	@ResponseBody
	public AppResultDto sendMessagePush(HttpServletRequest request, Integer type, String orgId, String userIds, String content, String emailCentent, String sendEmailId, String title, String filePaths) {
		User user = (User) request.getSession().getAttribute("UserCache");
		if (!StringUtil.isNotEmpty(userIds) || !StringUtil.isNotEmpty(content) || !StringUtil.isNotEmpty(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目、目标用户、内容为必填项");
		}
		String userId = "";
		if (user != null) {
			userId = user.getId().toString();
		}
		if (type == 1) {
			//短信
			return pushSendService.sendMessage(orgId, userId, userIds, content);
		} else if (type == 2) {
			//邮箱
			if (!StringUtil.isNotEmpty(userIds)) {
				return AppResultUtil.createErrorDto("100", "发送邮箱必填");
			}
			return pushSendService.sendEmail(orgId, userId, userIds, content, sendEmailId, title, filePaths, emailCentent);
		}
		return AppResultUtil.createErrorDto("100", "发送类型错误");
	}

	/**
	 * 获取通行方式
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "getPassType")
	@ResponseBody
	public AppResultDto getPassType(String orgId) {
		
		String passType = "-1";
		if (!StringUtil.isNotEmpty(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目不允许为空");
		}
		try {
			TbOrganization org = propertyManager.getTbOrganizationById(Integer.parseInt(orgId));
			if (org != null) {
				passType = org.getPassType();
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取通行方式异常");
		}
		//0无1face++2令令开门
		return AppResultUtil.createSuccesDto(passType);
	}


	/**
	 * 导入用户信息
	 *
	 * @param excelFile
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "importUserAddress")
	@ResponseBody
	public AppResultDto importUserAddress(@RequestParam("excelFile") MultipartFile excelFile, HttpServletRequest request, HttpServletResponse response) throws Exception {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		String orgId  = request.getParameter("orgId");
		String orgIds = getUserManageOrgIds(user);
		if (StringUtils.isEmpty(orgId)) {
			if (StringUtils.isNotEmpty(orgIds)) {
				String[] orgs = orgIds.split(";");
				if (orgs != null && orgs.length > 0) {
					orgId = orgIds.split(";")[0];
				}
			} else {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}
		AppResultDto dto = consumerUserService.importUserAddress(orgId, excelFile.getInputStream(), userId);
		return dto;
	}


}