package com.palmnest.webapp.controller.backstage;

import com.palmnest.application.Constants;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.dto.OutRetMsg;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.StaffManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 员工绑定Controller
 *
 * @author xlguo
 */
@Slf4j
@Controller
@RequestMapping("/admin/staffBind*")
public class StaffBindController extends BaseFormController {

	@Autowired
	private ScWxuserManager scWxuserManager;
	@Autowired
	private StaffManager    staffManager;
	@Autowired
	private PropertyManager propertyManager;

	/**
	 * 员工微信信息列表查询
	 */
	@RequestMapping(value = "query")
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) {
		initFunctionOperate(request);

		Model                model            = new ExtendedModelMap();
		int                  pageNo           = StringUtils.isNotEmpty(request.getParameter("pageNo")) ? Integer.valueOf(request.getParameter("pageNo")) : 1;
		String               isBinding        = request.getParameter("isBinding");
		String               nickName         = request.getParameter("nickName");
		String               organizationId   = request.getParameter("organizationId");
		List<TbOrganization> organizationList = getUserRelationOrgList(request);
		if (StringUtils.isNotEmpty(isBinding)) {
			model.addAttribute("isBinding", isBinding);
		}
		if (StringUtils.isNotEmpty(nickName)) {
			model.addAttribute("nickName", nickName);
		}
		if (StringUtils.isEmpty(organizationId)) {
			organizationId = getUserRelationOrganizationStr(organizationList);
		} else {
			model.addAttribute("organizationId", organizationId);
		}
		Page p = scWxuserManager.getWxUserList(pageNo, 10, nickName, Constants.AccountType_EMP, isBinding, organizationId);
		model.addAttribute("page", p);
		model.addAttribute("organizationList", organizationList);
		return new ModelAndView("admin/wechatbind/staffbindList", model.asMap());
	}

	/**
	 * 查看微信用户详细信息
	 *
	 * @return
	 */
	@RequestMapping(value = "detail")
	public ModelAndView view(HttpServletRequest request, HttpServletResponse response) {
		Model  model  = new ExtendedModelMap();
		String id     = request.getParameter("id");
		WxUser wxuser = scWxuserManager.get(Integer.parseInt(id));
		model.addAttribute("obj", wxuser);
		return new ModelAndView("admin/wechatbind/wxuserdetail", model.asMap());
	}

	/**
	 * 取消绑定
	 */
	@RequestMapping(value = "unbind")
	public @ResponseBody
	OutRetMsg unbind(HttpServletRequest request, HttpServletResponse response) {
		OutRetMsg outmsg = new OutRetMsg();
		try {
			String   item  = request.getParameter("dataAreaIds");
			String[] items = item.split(";");
			if (!ArrayUtils.isEmpty(items)) {
				Integer[] ids = new Integer[items.length];
				for (int i = 0; i < items.length; i++) {
					ids[i] = Integer.parseInt(items[i]);
				}
				//调用解绑方法
				scWxuserManager.updateBindWxuser(ids);
			}
			outmsg.setErrcode("200");
			outmsg.setErrmsg("success");
		} catch (Exception e) {
			log.error("deleteTemplate  error.{}", LogExceptionStackUtil.LogExceptionStack(e));
			outmsg.setErrcode("500");
			outmsg.setErrmsg("fail");
		}
		return outmsg;
	}

	/**
	 * 查看微信用户详细信息
	 *
	 * @return
	 */
	@RequestMapping(value = "prebind")
	public ModelAndView prebind(HttpServletRequest request, HttpServletResponse response) {
		Model  model          = new ExtendedModelMap();
		String id             = request.getParameter("id");
		String organizationId = request.getParameter("organizationId");
		if (StringUtils.isEmpty(id) || StringUtils.isEmpty(organizationId)) {
			throw new RuntimeException("参数无效");
		}
		try {
			int pageNo = StringUtils.isNotEmpty(request.getParameter("pageNo")) ? Integer.valueOf(request.getParameter("pageNo")) : 1;

			StringBuffer strSQL    = new StringBuffer("");
			String       staffName = request.getParameter("staffName");
			String       staffNo   = request.getParameter("staffNo");
			if (StringUtils.isNotEmpty(staffName)) {
				strSQL.append(" and t1.name like '%" + staffName + "%'");
				model.addAttribute("staffName", staffName);
			}
			if (StringUtils.isNotEmpty(staffNo)) {
				strSQL.append(" and t1.staffNo like '%" + staffNo + "%'");
				model.addAttribute("staffNo", staffNo);
			}
			//查询员工集合
			Page   page   = staffManager.queryStaffListByOrganization(pageNo, strSQL.toString(), organizationId);
			WxUser wxuser = scWxuserManager.get(Integer.parseInt(id));

			model.addAttribute("page", page);
			model.addAttribute("obj", wxuser);
			model.addAttribute("organizationId", organizationId);
			model.addAttribute("funcid", request.getParameter("funcid"));
		} catch (NumberFormatException e) {
			throw new RuntimeException("参数无效");
		}
		return new ModelAndView("admin/wechatbind/bindstaff", model.asMap());
	}

	/**
	 * 绑定
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/bindstaff*")
	public String delete(HttpServletRequest request,
						 HttpServletResponse response) {
		String wxuserid = request.getParameter("wxuserid");
		String staffid  = request.getParameter("staffid");
		String funcid   = request.getParameter("funcid");

		//保存绑定信息
		WxUser wxuser = scWxuserManager.get(Integer.parseInt(wxuserid));
		wxuser.setUserId(Integer.parseInt(staffid));
		wxuser.setIsBinding(Constants.BINDING);
		scWxuserManager.updateModel(wxuser);

		return "redirect:/admin/staffBind/query?funcid=" + funcid;
	}

}
