package cn.hmsoft.frame.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hmsoft.frame.data.dao.FrameDeptDao;
import cn.hmsoft.frame.data.model.FrameDept;
import cn.hmsoft.frame.data.model.FrameOptr;
import cn.hmsoft.frame.util.FrameAssertUtil;

/***************************
 * 部门操作类
 * 
 * @author zxq
 * @create 2019-06-24 18:23:26
 * @version 2.0.0
 * @email: revisit@126.com
 * @Company: www.hmsoft.cn
 */
@Service
public class FrameDeptService extends FrameService {

	@Autowired
	private FrameDeptDao daoDept;

	public void addDept(FrameDept dept) {
		FrameAssertUtil.isNotEmpty(dept.getDept_name(), "部门名称不允许为空");
		dept.setDept_name(dept.getDept_name().trim());
		if (dept.getDept_pid() - 0 == 0)
			dept.setDept_level(1);
		else {
			FrameDept pDept = this.daoDept.find(dept.getDept_pid());
			dept.setDept_level(pDept.getDept_level() != null ? pDept.getDept_level() + 1 : 1);
		}
		FrameDept tr = this.daoDept.find("dept_name", dept.getDept_name());
		FrameAssertUtil.isNull(tr, "部门名称 " + dept.getDept_name() + " 已经存在，请重新输入");
		this.daoDept.insert(dept);
	}

	public void editDept(FrameDept dept) {
		FrameAssertUtil.isNotEmpty(dept.getDept_name(), "部门名称不允许为空");
		FrameDept tr = this.daoDept.find("dept_name", dept.getDept_name());
		if (dept.getDept_pid() == null) {
			dept.setDept_pid(-1);
		}
		FrameAssertUtil.isNotEqual(dept.getDept_id(), dept.getDept_pid(), "上级部门不能为自己");
		/*
		 * if (tr != null) FrameAssertUtil.isEqual(tr.getDept_id(), dept.getDept_id(),
		 * "部门名称 " + dept.getDept_name() + " 已经存在，请重新输入");
		 */
		if (dept.getDept_pid() > 0) {
			FrameDept tr2 = this.daoDept.find("dept_pid", dept.getDept_pid());
			FrameAssertUtil.isNotNull(tr, "上级部门 " + tr.getDept_pid() + " 不存在，请重新输入");
			FrameAssertUtil.isNotEqual(dept.getDept_id(), tr2.getDept_pid(), "上级不能不能的父部门不能为当前部门");

			dept.setDept_level(tr2.getDept_level() != null ? tr2.getDept_level() + 1 : 1);
		} else {
			dept.setDept_level(1);
		}
		this.daoDept.update(dept);
	}

	public void deleteDept(int dept_id) {
		int count = this.daoDept.count(FrameOptr.class, "optr_dept", dept_id);
		FrameAssertUtil.moreThen(1, count, "还有操作员属于该部门，不允许删除此部门");
		count = this.daoDept.count(FrameDept.class, "dept_pid", dept_id);
		FrameAssertUtil.moreThen(1, count, "该部门还存在子部门，不允许删除此部门");
		// 删除部门表
		this.daoDept.delete(dept_id);
	}

}
