package cn.timer.api.controller.zzgl;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;

import cn.timer.api.bean.yggl.YgglMainEmp;
import cn.timer.api.bean.zzgl.ZzglAuth;
import cn.timer.api.bean.zzgl.ZzglBmgwM;
import cn.timer.api.config.annotation.CurrentUser;
import cn.timer.api.config.annotation.UserBean;
import cn.timer.api.dao.zzgl.ZzglBmgwMMapper;
import cn.timer.api.dao.zzgl.ZzglLogDgjlMapper;
import cn.timer.api.dto.zzgl.LogDgjlsDto;
import cn.timer.api.dto.zzgl.LogDgjlsQueryDto;
import cn.timer.api.dto.zzgl.UpEmpDeptDto;
import cn.timer.api.utils.Result;
import cn.timer.api.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "2.组织管理")
@RestController
@Transactional
@RequestMapping(value = "/zzgl", produces = { "application/json" })
public class ZzglController {

	@Autowired
	ZzglBmgwMMapper zzglBmgwMMapper;

	@Autowired
	ZzglLogDgjlMapper zzglLogDgjlMapper;

	/**
	 * 架构树/架构图/导出
	 * 
	 * @param
	 * @return
	 */
	@GetMapping(value = "/deptlist")
	@ApiOperation(value = "获取部门岗位", httpMethod = "GET", notes = "接口发布说明")
	public Result<List<ZzglBmgwM>> selectlistdept(@CurrentUser UserBean userBean) {
		Integer orgCode = userBean.getOrgCode();
		List<ZzglBmgwM> zzglBmgwMs = new LambdaQueryChainWrapper<ZzglBmgwM>(zzglBmgwMMapper)
				.eq(ZzglBmgwM::getOrgCode, orgCode).list();
		return ResultUtil.data(zzglBmgwMs);
	}

	/**
	 * 岗位成员
	 * 
	 * @param 部门岗位id
	 * @return
	 */
	@GetMapping(value = "/otherlistent/{id}")
	@ApiOperation(value = "获取岗位成员列表", httpMethod = "GET", notes = "接口发布说明")
	public Result<List<YgglMainEmp>> selectOtherlistent(@CurrentUser UserBean userBean, @PathVariable Integer id) {
		Integer orgCode = userBean.getOrgCode();
		ArrayList<Integer> list = new ArrayList<Integer>();
		List<ZzglBmgwM> zzglBmgwMs = new LambdaQueryChainWrapper<ZzglBmgwM>(zzglBmgwMMapper)
				.eq(ZzglBmgwM::getOrgCode, orgCode).list();
		list.add(id);
		ZzglBmgwM.getDepts(list, id, zzglBmgwMs);

		ZzglBmgwM messsage = ZzglBmgwM.builder().build().selectOne(new QueryWrapper<ZzglBmgwM>().eq("id", id));
		Integer lead = messsage.getLeader(); // 获取部门或岗位领导id

		if (list == null || list.size() == 0) {
			return ResultUtil.error("部门信息不存在,请先添加部门!");
		} else {
			LambdaQueryWrapper<YgglMainEmp> ygglMainEmpsLambdaQueryWrapper = new LambdaQueryWrapper<>();
			ygglMainEmpsLambdaQueryWrapper
					.select(YgglMainEmp::getId, YgglMainEmp::getEmpNum, YgglMainEmp::getName, YgglMainEmp::getPhone,
							YgglMainEmp::getBmgwId)
					.eq(YgglMainEmp::getOrgCode, orgCode).and(i -> i.in(YgglMainEmp::getBmgwId, list.toArray()))
					.last(lead != null, "order by if (emp_num='" + lead + "',0,1)");
			List<YgglMainEmp> ygglMainEmps = YgglMainEmp.builder().build().selectList(ygglMainEmpsLambdaQueryWrapper);
			return ResultUtil.data(ygglMainEmps);
		}
	}

	/**
	 * 获取调岗记录(weng)
	 * 
	 * @param 部门岗位id
	 * @return
	 */
	@PostMapping(value = "/listdgjl")
	@ApiOperation(value = "获取调岗记录(weng)", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> selectlistdgjl(@CurrentUser UserBean userBean,
			@RequestBody LogDgjlsQueryDto logDgjlsQueryDto) {
		Integer orgCode = userBean.getOrgCode();
		ArrayList<Integer> list = new ArrayList<Integer>();
		List<ZzglBmgwM> zzglBmgwMs = new LambdaQueryChainWrapper<ZzglBmgwM>(zzglBmgwMMapper)
				.eq(ZzglBmgwM::getOrgCode, orgCode).list();
		list.add(logDgjlsQueryDto.getDeptId());
		ZzglBmgwM.getDepts(list, logDgjlsQueryDto.getDeptId(), zzglBmgwMs);

		if (list == null || list.size() == 0) {
			return ResultUtil.error("部门信息不存在,请先添加部门!");
		} else {

			logDgjlsQueryDto.setDeptIdList(list);
			logDgjlsQueryDto.setOrgCode(orgCode);

			IPage<LogDgjlsDto> page = new Page<LogDgjlsDto>(
					logDgjlsQueryDto.getCurrentPage() == null ? 1 : logDgjlsQueryDto.getCurrentPage(),
					logDgjlsQueryDto.getTotalPage() == null ? 10 : logDgjlsQueryDto.getTotalPage());
			List<LogDgjlsDto> logDgjlDtos = zzglLogDgjlMapper.selectListdgjls(page, logDgjlsQueryDto);
			return ResultUtil.data(page, logDgjlDtos, "查询成功");
		}
	}

	/**
	 * 未设置岗位的成员
	 * 
	 * @return
	 */
	@GetMapping(value = "/listent")
	@ApiOperation(value = "未设置岗位的成员", httpMethod = "GET", notes = "接口发布说明")
	public Result<List<YgglMainEmp>> selectlistent(@CurrentUser UserBean userBean) {
		Integer orgCode = userBean.getOrgCode();

		LambdaQueryWrapper<YgglMainEmp> ygglMainEmpsLambdaQueryWrapper = new LambdaQueryWrapper<>();
		ygglMainEmpsLambdaQueryWrapper
				.select(YgglMainEmp::getId, YgglMainEmp::getEmpNum, YgglMainEmp::getName, YgglMainEmp::getPhone)
				.eq(YgglMainEmp::getOrgCode, orgCode)
				.and(i -> i.isNull(YgglMainEmp::getBmgwId).or().eq(YgglMainEmp::getBmgwId, 0));
		// .and(lqw -> lqw.notIn(id != null,
		// YgglMainEmp::getBmgwId,Arrays.asList(id)).or().isNull(YgglMainEmp::getBmgwId))
		List<YgglMainEmp> ygglMainEmps = YgglMainEmp.builder().build().selectList(ygglMainEmpsLambdaQueryWrapper);
		// List<ZzglBmgwMEmpDto> zzglBmgwMEmpDtos =
		// zzglBmgwMMapper.selectOtherListByOrgCode(orgCode,id);
		return ResultUtil.data(ygglMainEmps);
	}

	/**
	 * 添加/修改部门
	 * 
	 * @param
	 * @return
	 */
	@PostMapping(value = "/dept")
	@ApiOperation(value = "添加/修改部门", httpMethod = "POST", notes = "接口发布说明")
	public Result<ZzglBmgwM> adddept(@CurrentUser UserBean userBean, @RequestBody ZzglBmgwM zzglBmgwM) {
		Boolean a = zzglBmgwM.getId() == null;
		if (a && zzglBmgwM.getType() == null)
			zzglBmgwM.setType((Integer) 0);
		zzglBmgwM.setOrgCode(userBean.getOrgCode());
		zzglBmgwM.insertOrUpdate();
		if (a)
			return ResultUtil.data(zzglBmgwM);
		return ResultUtil.success();
	}

	/**
	 * 删除部门岗位
	 * 
	 * @param 部门岗位ids [1,2,3,4]
	 * @return
	 */
	@DeleteMapping(value = "/dept")
	@ApiOperation(value = "删除部门岗位", httpMethod = "DELETE", notes = "接口发布说明")
	public Result<Integer> deldepts(@CurrentUser UserBean userBean, @RequestBody List<Integer> ids) {
		YgglMainEmp ygglMainEmp = YgglMainEmp.builder().build();
		UpdateWrapper<YgglMainEmp> updateWrapper = new UpdateWrapper<YgglMainEmp>();
		updateWrapper.set("bmgw_id", null).in("bmgw_id", ids);
		zzglLogDgjlMapper.insertbydeldept(ids, userBean.getEmpNum());
		ygglMainEmp.update(updateWrapper);
		zzglBmgwMMapper.deleteBatchIds(ids);

		return ResultUtil.success();
	}

	/**
	 * 批量修改/删除员工部门
	 * 
	 * @param 部门岗位id
	 * @return
	 */
	@PostMapping(value = "/empdept")
	@ApiOperation(value = "批量修改/删除员工部门", httpMethod = "POST", notes = "接口发布说明")
	public Result<Void> updatelistempdept(@CurrentUser UserBean userBean, @RequestBody UpEmpDeptDto upEmpDeptDto) {
		Integer dpetId = upEmpDeptDto.getDpetId();
		List<Integer> empNums = upEmpDeptDto.getEmpNum();
		YgglMainEmp ygglMainEmp = YgglMainEmp.builder().build();
		// zzglLogDgjlMapper
		UpdateWrapper<YgglMainEmp> updateWrapper = new UpdateWrapper<YgglMainEmp>();
		updateWrapper.set("bmgw_id", dpetId).eq("org_code", userBean.getOrgCode()).in("emp_num", empNums);
		zzglLogDgjlMapper.insertbyaddemp(empNums, userBean.getEmpNum(), dpetId, userBean.getOrgCode(),
				dpetId == null || dpetId == 0 ? "岗位删除员工" : upEmpDeptDto.getIsdg() == null ? "岗位添加员工" : "员工调岗");
		ygglMainEmp.update(updateWrapper);
		// zzglLogDgjlMapper.insert
		return ResultUtil.success();
	}
	//修改/删除员工部门(供审批管理使用)
	public void updatelistempdeptforspgl (Integer empNum,Integer orgCode, UpEmpDeptDto upEmpDeptDto) {
		Integer dpetId = upEmpDeptDto.getDpetId();
		List<Integer> empNums = new ArrayList<Integer>();
		empNums.add(empNum);
		YgglMainEmp ygglMainEmp = YgglMainEmp.builder().build();
		// zzglLogDgjlMapper
		UpdateWrapper<YgglMainEmp> updateWrapper = new UpdateWrapper<YgglMainEmp>();
		updateWrapper.set("bmgw_id", dpetId).eq("org_code", orgCode).in("emp_num", empNum);
		zzglLogDgjlMapper.insertbyaddemp(empNums, empNum, dpetId, orgCode,
				dpetId == null || dpetId == 0 ? "岗位删除员工" : upEmpDeptDto.getIsdg() == null ? "岗位添加员工" : "员工调岗");
		ygglMainEmp.update(updateWrapper);
		// zzglLogDgjlMapper.insert
	}
	
	/**
	 * 岗位权限
	 * 
	 * @param 部门岗位id
	 * @return
	 */
	@GetMapping(value = "/auth/{id}")
	@ApiOperation(value = "获取岗位岗位权限", httpMethod = "GET", notes = "接口发布说明")
	public Result<List<ZzglAuth>> auth(@CurrentUser UserBean userBean, @PathVariable Integer id) {
		Integer orgCode = userBean.getOrgCode();
		ArrayList<Integer> list = new ArrayList<Integer>();
		List<ZzglBmgwM> zzglBmgwMs = new LambdaQueryChainWrapper<ZzglBmgwM>(zzglBmgwMMapper)
				.eq(ZzglBmgwM::getOrgCode, orgCode).list();
				ZzglBmgwM.getupDepts(list, id, zzglBmgwMs);
		if (list == null || list.size() == 0) {
			return ResultUtil.error("部门信息不存在,请先添加部门!");
		} else {
			LambdaQueryWrapper<ZzglAuth> wp = new LambdaQueryWrapper<>();
			wp.select(ZzglAuth::getMenuId, ZzglAuth::getBmgwId).eq(ZzglAuth::getOrgCode, orgCode)
					.and(i -> i.in(ZzglAuth::getBmgwId, list.toArray()));
			List<ZzglAuth> zas = ZzglAuth.builder().build().selectList(wp);
			return ResultUtil.data(zas);
		}
	}

	/**
	 * 批量修改/删除岗位权限
	 * 
	 * @param 部门岗位id
	 * @param 菜单ids
	 * @return
	 */
	@PostMapping(value = "/auth/{id}")
	@ApiOperation(value = "批量修改/删除岗位权限", httpMethod = "POST", notes = "接口发布说明")
	public Result<Void> auth(@CurrentUser UserBean userBean, @PathVariable Integer id, @RequestBody List<String> ids) {
		Integer orgCode = userBean.getOrgCode();
		ZzglAuth.builder().build().delete(
				new QueryWrapper<ZzglAuth>().lambda().eq(ZzglAuth::getOrgCode, orgCode).eq(ZzglAuth::getBmgwId, id));
		ids.forEach(o -> {
			ZzglAuth za = ZzglAuth.builder().build();
			za.setBmgwId(id);
			za.setOrgCode(orgCode);
			za.setMenuId(o);
			za.insert();
		});
		return ResultUtil.success();
	}
}