package com.palmnest.webapp.controller.dinner.wechat;

import cn.jiguang.common.utils.StringUtils;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.dto.input.ConsumerInputDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.model.Element;
import com.palmnest.model.User;
import com.palmnest.model.dinner.Consumer;
import com.palmnest.service.dinner.service.ConsumerUserService;
import com.palmnest.service.estateserve.ScWxuserManager;
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.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 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("/wechat/dinner/*")
public class WechatConsumerController extends BaseFormController {


	@Autowired
	private ScWxuserManager     scWxuserManager;
	@Autowired
	private ConsumerUserService consumerUserService;
	@Autowired
	private ElementGroupService elementGroupService;

	/**
	 * 判断微信用户是否登录过
	 *
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "getConsumerByOpenId")
	@ResponseBody
	public AppResultDto getConsumerByOpenId(String openId, String orgId) {

		if (StringUtils.isEmpty(orgId)) {
			orgId = getWxUserOrgId(openId);
			if (StringUtils.isEmpty(orgId)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}

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

		Consumer cust = consumerUserService.getConsumerByOpenId(orgId, openId);

		if (cust != null) {
			return AppResultUtil.createSuccesDto(cust);
		} else {
			return AppResultUtil.createErrorDto("100", "抱歉，您没有登录，请先登录！");
		}

	}

	/**
	 * 登录
	 *
	 * @param loginName
	 * @param password
	 * @param openId
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "login")
	@ResponseBody
	public AppResultDto login(String mobile, String code, String openId, String orgId) {

		if (StringUtils.isEmpty(orgId)) {
			orgId = getWxUserOrgId(openId);
			if (StringUtils.isEmpty(orgId)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}

		if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(code)) {
			return AppResultUtil.createErrorDto("100", "登录账号和验证码不能为空");
		}

		return consumerUserService.login(mobile, code, openId, orgId);
	}

	/**
	 * 退出登录
	 *
	 * @param openId
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "exitLogin")
	@ResponseBody
	public AppResultDto exitLogin(String openId, String orgId) {

		if (StringUtils.isEmpty(orgId)) {
			orgId = getWxUserOrgId(openId);
			if (StringUtils.isEmpty(orgId)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}

		String res = consumerUserService.exitLogin(openId, orgId);

		if ("SUCCESS".equals(res)) {
			return AppResultUtil.createSuccesDto();
		} else {
			return AppResultUtil.createErrorDto("100", "退出登录失败");
		}
	}

	/**
	 * 修改用户信息
	 *
	 * @param dto
	 * @return
	 */
	@RequestMapping(value = "updateConsumer")
	@ResponseBody
	public AppResultDto updateConsumer(ConsumerInputDto dto) {

		if (StringUtils.isEmpty(dto.getId())) {
			return AppResultUtil.createErrorDto("100", "登录用户id不能为空");
		}

		String res = consumerUserService.updateConsumer(dto);

		if ("SUCCESS".equals(res)) {
			return AppResultUtil.createSuccesDto();
		} else {
			return AppResultUtil.createErrorDto("100", "修改用户信息失败");
		}
	}

	/**
	 * 修改密码
	 *
	 * @param id
	 * @param openId
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 */
	@RequestMapping(value = "updatePassword")
	@ResponseBody
	public AppResultDto updatePassword(String id, String openId, String oldPassword, String newPassword) {

		if (StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword)) {
			return AppResultUtil.createErrorDto("100", "新/旧密码不允许为空");
		}

		String res = consumerUserService.updatePassword(id, openId, oldPassword, newPassword);

		if ("SUCCESS".equals(res)) {
			return AppResultUtil.createSuccesDto();
		} else {
			if (StringUtils.isNotEmpty(res)) {
				return AppResultUtil.createErrorDto("100", res);
			}
			return AppResultUtil.createErrorDto("100", "修改密码失败");
		}
	}

	/**
	 * 获取部门或地址
	 *
	 * @return
	 */
	@RequestMapping(value = "getDeptAndAddress")
	@ResponseBody
	public AppResultDto getDeptAndAddress(int type) {

		if (1 == type) {
			//获取部门
			List<Element>    deptList    = elementGroupService.getElementsByGroupName("dinnerDept");
			List<ElementDto> deptDtoList = elementGroupService.convert(deptList);
			Collections.sort(deptDtoList, 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(deptDtoList);

		} else if (2 == type) {

			//获取地址
			List<Element>    addressList    = elementGroupService.getElementsByGroupName("dinnerAddress");
			List<ElementDto> addressDtoList = elementGroupService.convert(addressList);
			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 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;
	}


}
