package com.palmnest.webapp.controller.dinner;

import com.alibaba.fastjson.JSON;
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.StringUtil;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.DeptDto;
import com.palmnest.model.User;
import com.palmnest.model.dinner.Department;
import com.palmnest.service.dinner.manager.DeptManager;
import com.palmnest.service.dinner.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 java.util.*;

/**
 * @Author 黄笑天
 * @Description 企业部门控制器
 * @Date 2019/1/3 17:30
 **/
@Slf4j
@Controller
@RequestMapping("/admin/dept/*")
public class DeptController {


	@Autowired
	private DeptManager deptManager;
	@Autowired
	private DeptService deptService;

	/**
	 * 新增修改部门信息
	 *
	 * @param request
	 * @return
	 */
//    @RequestMapping(value = "/saveUpdateDept1")
//    @ResponseBody
//    public AppResultDto saveUpdateDept1(HttpServletRequest request){
//    	// 部门id(新增时为空)
//        String id = request.getParameter("id");
//        // 部门名称
//        String name = request.getParameter("name").trim();
//        // 部门简称
//        String shortName = request.getParameter("shortName").trim();
//        // 项目id
//        String orgId = request.getParameter("orgId");
//        // 企业id
//        String virId = request.getParameter("virId");
//        // 部门排序号
//        String orderNum = request.getParameter("orderNum");
//
//        User user = (User) request.getSession().getAttribute("UserCache");
//        Department department = new Department();
//
//        if (StringUtils.isBlank(id)){
//            // 新增时参数校验
//            if (StringUtils.isAnyBlank(name,orgId,virId)){
//                return AppResultUtil.createErrorDto("100","必填参数为空");
//            }
//            log.info("DeptController saveUpdateDept======>name:{},shortName:{},orgId:{},virId:{},orderNum:{}",name,shortName,orgId,virId,orderNum);
//            // 校验统一企业下部门名称不能重复
//            Department dept = deptManager.getDeptByNameAndVirId(Integer.parseInt(virId),name);
//            if (dept != null){
//                return AppResultUtil.createErrorDto("100","部门名称重复!");
//            }
//
//            // 新增
//            department.setCreator(user.getId());
//            department.setCreateTime(new Date());
//            department.setName(name);
////            department.setOrderNum(Integer.parseInt(orderNum));
//            if(StringUtil.isNotEmpty(orderNum)){
//           	 department.setOrderNum(Integer.parseInt(orderNum));
//           }
//            department.setOrgId(Integer.parseInt(orgId));
//            department.setShortName(shortName);
//            department.setVirId(Integer.parseInt(virId));
//            department.setIsEnabled(1);
//
//        }else {
//            // 修改时参数校验
//            if (StringUtils.isAnyBlank(id,name)){
//                return AppResultUtil.createErrorDto("100","必填参数为空");
//            }
//            log.info("DeptController saveUpdateDept======>id:{},name:{},orderNum:{}",id,name,orderNum);
//            // 修改
//            department = deptManager.get(Long.parseLong(id));
//            department.setModifier(user.getId());
//            department.setModifyTime(new Date());
//            department.setName(name);
//            department.setShortName(shortName);
//            if(StringUtil.isNotEmpty(orderNum)){
//            	 department.setOrderNum(Integer.parseInt(orderNum));
//            }
//        }
//
//        try {
//            deptManager.saveUpdateDept(department);
//            return AppResultUtil.createSuccesDto();
//        } catch (Exception e) {
//            log.error("新增/修改部门信息异常!======>" + e.getMessage());
//            return AppResultUtil.createErrorDto("100","操作失败!");
//        }
//
//    }

	/**
	 * 新增修改部门
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/saveUpdateDept")
	@ResponseBody
	public AppResultDto saveUpdateDept(HttpServletRequest request) {
		// 部门id(新增时为空)
		String id = request.getParameter("id");

		// 部门名称
		String name = request.getParameter("name");
		// 部门简称
		String shortName = request.getParameter("shortName");
		// 项目id
		String orgId = request.getParameter("orgId");
		// 企业id
		String virId = request.getParameter("virId");
		// 部门排序号
		String orderNum = request.getParameter("orderNum");
		// 部门List
		String deptListJson = request.getParameter("deptListJson");
		String userId       = "";
		try {
			User          user     = (User) request.getSession().getAttribute("UserCache");
			List<DeptDto> deptList = new ArrayList<DeptDto>();
			if (user != null) {
				userId = user.getId().toString();
			}
			//修改部门
			if (StringUtil.isNotEmpty(id)) {
				// 修改时参数校验
				if (StringUtils.isAnyBlank(id, name)) {
					return AppResultUtil.createErrorDto("100", "必填参数为空");
				}
				log.info("DeptController saveUpdateDept======>id:{},name:{},orderNum:{}", id, name, orderNum);
				//是否重复 0未重复1重复
				int isRepeat = deptService.isRepeatByDept(orgId, virId, name, id);
				log.info("DeptController saveUpdateDept======>isRepeat:{}", isRepeat);
				if (isRepeat == 1) {
					return AppResultUtil.createErrorDto("100", "该企业下有相同部门名称");
				}
				// 修改
				Department department = deptManager.get(Long.parseLong(id));
				department.setModifier(user.getId());
				department.setModifyTime(new Date());
				department.setName(name);
				department.setShortName(shortName);
				orderNum = orderNum.trim();
				if (StringUtil.isNotEmpty(orderNum)) {
					department.setOrderNum(Integer.parseInt(orderNum));
				}
				deptManager.saveUpdateDept(department);
				return AppResultUtil.createSuccesDto();
			} else if (StringUtil.isNotEmpty(deptListJson)) {
				//新增部门
				deptList = JSON.parseArray(deptListJson, DeptDto.class);
				int          count = 0;
				List<String> list  = new ArrayList<String>();
				if (deptList != null && deptList.size() > 0) {
					for (int i = 0; i < deptList.size(); i++) {
						DeptDto dto = deptList.get(i);
						if (dto != null) {
							list.add(dto.getName());
							int isRepeat = deptService.isRepeatByDept(orgId, virId, dto.getName(), "");
							if (isRepeat == 1) {
								count++;
							}
						}
					}
					HashSet<String> hashSet = new HashSet<String>(list);
					if (count > 0 || list.size() != hashSet.size()) {
						return AppResultUtil.createErrorDto("100", "保存的部门名称重复");
					}
					String res = deptService.saveDeptList(orgId, virId, userId, deptList);
					if ("SUCCESS".equals(res)) {
						return AppResultUtil.createSuccesDto();
					} else {
						log.error("保存部门失败:" + res);
						return AppResultUtil.createErrorDto("100", "保存部门失败");
					}
				}
				return AppResultUtil.createErrorDto("100", "保存的部门数不能为空");
			}
		} catch (Exception e) {
			log.error("新增/修改部门信息异常!======>" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "操作失败!");
		}
		return AppResultUtil.createSuccesDto();
	}

	/**
	 * 删除部门
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/delDept")
	@ResponseBody
	public AppResultDto delDept(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (StringUtils.isAnyBlank(id)) {
			return AppResultUtil.createErrorDto("100", "必填参数为空");
		}
		String userId = "";
		User   user   = (User) request.getSession().getAttribute("UserCache");
		if (user != null) {
			userId = user.getId().toString();
		}
		Department department = deptManager.get(Long.parseLong(id));
		department.setIsEnabled(0);

		try {
			department.setModifyTime(new Date());
			if (StringUtil.isNotEmpty(userId)) {
				department.setModifier(Long.parseLong(userId));
			}
//            deptManager.updateModel(department);
			deptManager.delDept(department);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("删除部门信息异常!======>" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "操作失败!");
		}
	}

	/**
	 * 获取部门详情
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deptInfo")
	@ResponseBody
	public AppResultDto deptInfo(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (StringUtils.isAnyBlank(id)) {
			return AppResultUtil.createErrorDto("100", "必填参数为空");
		}
		return AppResultUtil.createSuccesDto(deptManager.getDeptInfo(Long.parseLong(id)));
	}

	/**
	 * 查询部门列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deptList")
	@ResponseBody
	public WebPageResultDto deptList(HttpServletRequest request) {

		String virId    = request.getParameter("virId");
		String deptId   = request.getParameter("deptId");
		String pageSize = request.getParameter("pageSize");
		String pageNo   = request.getParameter("pageNo");
		String orgId    = request.getParameter("orgId");

		log.info("DeptConreoller deptList =========>virId:{},deptId:{},pageSize:{},pageNo:{},orgId:{}", virId, deptId, pageSize, pageNo, orgId);

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

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

		HashMap<String, String> map = new HashMap<String, String>();
		map.put("orgId", orgId);
		map.put("virId", virId);
		map.put("deptId", deptId);

		try {
			Page             pagenation = deptManager.deptList(Integer.parseInt(pageNo), Integer.parseInt(pageSize), map);
			WebPageResultDto dto        = new WebPageResultDto("200", "成功", pagenation.getItems());
			dto.setCount(pagenation.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.error("查询部门列表失败 deptList ===>" + e.getMessage());
			return new WebPageResultDto("100", "查询部门列表失败", null);
		}

	}

	/**
	 * 导入部门
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/importDept")
	@ResponseBody
	public AppResultDto importDept(@RequestParam("excelFile") MultipartFile excelFile, HttpServletRequest request, String orgId, String virId) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		if (StringUtils.isAnyBlank(orgId, virId)) {
			return AppResultUtil.createErrorDto("100", "必填参数为空");
		}
		try {
			return deptService.importDept(orgId, virId, userId, excelFile.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("导入部门失败:" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "导入部门失败");
		}
	}

	/**
	 * 判断该项目该企业下的部门名字是否重复
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/isRepeatByDept")
	@ResponseBody
	public AppResultDto isRepeatByDept(HttpServletRequest request, String orgId, String virId, String name, String id) {
		if (StringUtils.isAnyBlank(orgId, virId, name)) {
			return AppResultUtil.createErrorDto("100", "必填参数为空");
		}
		//是否重复 0未重复1重复
		int isRepeat = deptService.isRepeatByDept(orgId, virId, name, id);
		return AppResultUtil.createSuccesDto(isRepeat);
	}
}
