package com.palmnest.webapp.controller.backstage;

import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.dto.OutTreeDTO;
import com.palmnest.model.Element;
import com.palmnest.model.Staff;
import com.palmnest.model.TbCompany;
import com.palmnest.service.estateserve.AppUserManager;
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 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.*;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 物业员工信息管理
 *
 * @author yubing
 * @since 2017-05-12
 */

@Controller
@RequestMapping("/admin/staff*")
public class StaffController extends BaseFormController {

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

	//初始化数据字典
	public void initElementGroup(Model model) {
		List<Element> userSexGroup     = this.getElementGroupManager().getElementsByGroupName("userSexGroup");    //性别
		List<Element> staffPostGroup   = this.getElementGroupManager().getElementsByGroupName("staffPostGroup");//职位
		List<Element> staffStatusGroup = this.getElementGroupManager().getElementsByGroupName("staffStatusGroup");//状态
		model.addAttribute("userSexGroup", userSexGroup);
		model.addAttribute("staffPostGroup", staffPostGroup);
		model.addAttribute("staffStatusGroup", staffStatusGroup);
		model.addAttribute("imageServer", FileUploadUtils.getVisitPrefix());
	}

	/**
	 * 员工列表查询
	 */
	@RequestMapping(value = "/list")
	public ModelAndView handleRequest(HttpServletRequest request,
									  HttpServletResponse response) throws Exception {
		initFunctionOperate(request);

		//运营中心
		List<TbCompany> companys = getUserRelationCompanyList(request);

		Model        model          = new ExtendedModelMap();
		StringBuffer strSQL         = new StringBuffer();
		String       pageNo         = request.getParameter("pageNo");
		String       companyId      = request.getParameter("companyId");
		String       organizationId = request.getParameter("organizationId");
		String       keyword        = request.getParameter("keyword");
		String       staffStatus    = request.getParameter("staffStatus");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isNotBlank(keyword)) {
			//电话号码、姓名、工号
			strSQL.append(" AND t1.userMobile LIKE '%" + keyword + "%' or t1.staffNo LIKE '%" + keyword + "%' or t1.`name` LIKE '%" + keyword + "%'");
			model.addAttribute("keyword", keyword);
		}
		if (StringUtils.isNotBlank(organizationId)) {
			strSQL.append(" AND t2.organizationId=" + organizationId);
			model.addAttribute("organizationId", organizationId);
		}
		if (StringUtils.isNotBlank(staffStatus)) {
			strSQL.append(" AND t1.status='" + staffStatus + "'");
			model.addAttribute("staffStatus", staffStatus);
		}

		if (StringUtils.isNotBlank(companyId)) {
			strSQL.append(" AND t1.companyId=" + companyId);
			model.addAttribute("companyId", companyId);
		} else {
			strSQL.append(" AND t1.companyId in(" + getUserRelationCompanyIdsStr(request) + ")");
		}
		Page page = staffManager.queryStaffList(Integer.parseInt(pageNo), strSQL.toString());
		model.addAttribute("page", page);
		model.addAttribute("companys", companys);

		initElementGroup(model);
		return new ModelAndView("admin/staffList", model.asMap());
	}

	/**
	 * 员工新增/修改
	 */
	@RequestMapping(value = "/form")
	public ModelAndView form(@ModelAttribute("staff") Staff staff, HttpServletRequest request,
							 HttpServletResponse response) throws Exception {
		Model  model   = new ExtendedModelMap();
		String actType = request.getParameter("actType");
		if ("save".equals(actType)) {
			boolean checkFlag = true;

			staff.setIsEnabled("1");
			String staffNo = staff.getStaffNo();
			//修改
			if (staff.getId() != null) {
				//验证工号的唯一性
				Staff containsStaff = staffManager.getStaffByStaffNoOrStaffId(staffNo, staff.getId() + "");
				if (containsStaff != null) {
					model.addAttribute("errormsg", "更新失败，工号重复！");
					checkFlag = false;
				} else {
					staff.setModifier(request.getRemoteUser());
					staff.setModifyTime(new Date());
					staffManager.updateModel(staff);
					model.addAttribute("errormsg", "更新成功");
				}
			}
			//新增
			else {
				//验证工号的唯一性
				Staff containsStaff = staffManager.getStaffByStaffNoOrStaffId(staffNo, "");
				if (containsStaff != null) {
					model.addAttribute("errormsg", "新增保存失败，工号重复！");
					checkFlag = false;
				} else {
					staff.setCreator(request.getRemoteUser());
					staff.setCreateTime(new Date());
					staffManager.saveModel(staff);
					model.addAttribute("errormsg", "保存成功");
				}
			}
			if (checkFlag) {
				//删除关联的楼栋、项目组织信息
				String buildIds = request.getParameter("buildIds");
				staffManager.assignStaffRelationBuild(buildIds, staff.getId());
			}
		} else {
			String staffId = request.getParameter("staffId");
			if (StringUtils.isNotEmpty(staffId)) {
				model.addAttribute("staff", staffManager.get(Integer.parseInt(staffId)));
			}
		}
		initElementGroup(model);
		model.addAttribute("funcid", request.getParameter("funcid"));
		model.addAttribute("companyList", getUserRelationCompanyList(request));
		return new ModelAndView("admin/staffForm", model.asMap());
	}

	/**
	 * 查询项目组织架构信息
	 *
	 * @param request
	 * @param response List<OutTreeDTO>
	 */
	@RequestMapping(value = "/getOrganizationBuildTree", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> getOrganizationBuildTree(HttpServletRequest request,
											  HttpServletResponse response) {
		String deptId  = request.getParameter("deptId");
		String staffId = request.getParameter("staffId");
		if (StringUtils.isNotBlank(staffId)) {
			return staffManager.getStaffRelationBuildTree(Integer.valueOf(staffId), Integer.valueOf(deptId));
		} else {
			return staffManager.getStaffRelationBuildTree(null, Integer.valueOf(deptId));
		}
	}

	/**
	 * 删除员工信息
	 */
	@RequestMapping(value = "/delete/{id}&{funcid}")
	public String delete(@PathVariable int id, @PathVariable long funcid, HttpServletRequest request) {
		Staff staff = staffManager.get(id);
		staff.setModifier(request.getRemoteUser());
		staff.setModifyTime(new Date());
		staff.setIsEnabled(ElementConstant.YESORNO_0);
		staffManager.deleteStaff(staff);
		return "redirect:/admin/staff/list?funcid=" + funcid;
	}
}
