/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.community.staff.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.sun.corba.se.impl.copyobject.JavaStreamObjectCopierImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang3.StringUtils;
import org.springblade.attence.rule.entity.Rule;
import org.springblade.attence.rule.service.IRuleService;
import org.springblade.attence.ruleperson.service.IRulePersonService;
import org.springblade.common.Constants;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.enterprise.entity.Enterprise;
import org.springblade.community.enterprise.service.IEnterpriseService;
import org.springblade.community.enterprisedept.entity.EnterpriseDept;
import org.springblade.community.enterprisedept.service.IEnterpriseDeptService;
import org.springblade.community.houseuser.entity.Houseuser;
import org.springblade.community.houseuser.service.IHouseuserService;
import org.springblade.community.repeater.entity.Repeater;
import org.springblade.community.repeater.service.IRepeaterService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.community.staff.dto.EnterpriseStaffDTO;
import org.springblade.community.staff.entity.EnterpriseStaff;
import org.springblade.community.staff.service.IEnterpriseStaffService;
import org.springblade.community.staff.vo.EnterpriseStaffVO;
import org.springblade.community.staff.wrapper.EnterpriseStaffWrapper;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.mq.enums.Instruct;
import org.springblade.mq.service.MsgPublishService;
import org.springblade.openinterface.facedevice.qinlin.beans.QinLinApiResultBean;
import org.springblade.openinterface.facedevice.qinlin.util.QinLinHttpUtil;
import org.springblade.openinterface.facedevice.qinlin.util.ZHHttpUtil;
import org.springblade.openinterface.facedevice.qinlin.vo.QLinUser;
import org.springblade.smartapplication.facedevice.entity.FaceDevice;
import org.springblade.smartapplication.facedevice.service.IFaceDeviceService;
import org.springblade.system.orgposition.entity.OrgPosition;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springblade.third.doordevice.dto.DeviceDTO;
import org.springblade.third.doordevice.dto.UserDeviceDTO;
import org.springblade.utils.AESPlus;
import org.springblade.utils.entity.TreeEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 控制器
 *
 * @author BladeX
 * @since 2020-12-11
 */
@RestController
@AllArgsConstructor
@RequestMapping("community/enterprisestaff")
@Api(value = "", tags = "员工信息")
@Slf4j
public class EnterpriseStaffController extends BladeController {

	private IEnterpriseStaffService enterpriseStaffService;
	private IEnterpriseDeptService enterpriseDeptService;
	private IEnterpriseService enterpriseService;
	private IDeptService deptService;
	private IOrgPositionService orgPositionService;
	private IAgencyService agencyService;
	private IResidentialService residentialService;
	private IRuleService ruleService;
	private IRulePersonService rulePersonService;

	private MsgPublishService msgPublishService;
	private IRepeaterService repeaterService;
	private IFaceDeviceService faceDeviceService;
	private QinLinHttpUtil qinLinHttpUtil;
	private BladeLogger logger;
	private ZHHttpUtil zhHttpUtil;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入enterpriseStaff")
	public R<EnterpriseStaffVO> detail(EnterpriseStaffDTO enterpriseStaff) {
		EnterpriseStaff detail = enterpriseStaffService.getById(enterpriseStaff.getId());
		return detail != null ? R.data(EnterpriseStaffWrapper.build(agencyService, residentialService).entityVO(detail, enterpriseStaff.getIsEdit())) : R.fail("没有用户信息");
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入enterpriseStaff")
	public R<IPage<EnterpriseStaffVO>> list(@RequestParam Map<String, Object> enterpriseStaff, Query query, BladeUser bladeUser) {
		//只支持一个企业（一个机构只能绑定一个企业）
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		Dept dept = deptService.getById(deptIds[0]);
		// 部门类型就是机构类型, 公司就是企业，1应该表示园区的企业
		if (dept.getDeptCategory() == 1) {
			OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, dept.getId()));
			if (orgPosition == null) {
				return R.data(null);
			}
			String[] enterpriseIds = orgPosition.getEnterpriseIds().split(",");
			LambdaQueryWrapper<EnterpriseStaff> wrapper = Condition.getQueryWrapper(enterpriseStaff, EnterpriseStaff.class).orderByDesc("create_time").lambda();
			IPage<EnterpriseStaff> page = enterpriseStaffService.page(Condition.getPage(query), wrapper.eq(EnterpriseStaff::getEnterpriseId, enterpriseIds[0]));
			return R.data(EnterpriseStaffWrapper.build(agencyService, residentialService).pageVO(page));
		} else {
//			LambdaQueryWrapper<EnterpriseStaff> wrapper = Condition.getQueryWrapper(enterpriseStaff, EnterpriseStaff.class).lambda();
			IPage<EnterpriseStaff> pages = enterpriseStaffService.page(Condition.getPage(query), Condition.getQueryWrapper(enterpriseStaff, EnterpriseStaff.class).orderByDesc("create_time"));
			return R.data(EnterpriseStaffWrapper.build(agencyService, residentialService).pageVO(pages));
//			return R.data(null);
		}
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入enterpriseStaff")
	public R<IPage<EnterpriseStaffVO>> page(EnterpriseStaffVO enterpriseStaff, Query query) {
		IPage<EnterpriseStaffVO> pages = enterpriseStaffService.selectEnterpriseStaffPage(Condition.getPage(query), enterpriseStaff);
		System.out.println(enterpriseStaff.toString());
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入enterpriseStaff")
	public R save(@Valid @RequestBody EnterpriseStaff enterpriseStaff) {
		return R.status(enterpriseStaffService.save(enterpriseStaff));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入enterpriseStaff")
	public R update(@Valid @RequestBody EnterpriseStaff enterpriseStaff) {
		return R.status(enterpriseStaffService.updateById(enterpriseStaff));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入enterpriseStaff")
	public R submit(@Valid @RequestBody EnterpriseStaff enterpriseStaff) {
		return enterpriseStaffService.staffSubmit(enterpriseStaff);
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> idList = Func.toLongList(ids);
		boolean b = enterpriseStaffService.deleteLogic(Func.toLongList(ids));
		if (b) {
			idList.forEach(id -> {
				QLinUser qLinUser = new QLinUser();
				qLinUser.setUserId(id.toString());
				QinLinApiResultBean qinLinApiResultBean = qinLinHttpUtil.deleteUser(qLinUser);
				if (qinLinApiResultBean.getCode().equals(0)) {
					logger.info("qinLinDeleteUser", JsonUtil.toJson(qLinUser));
				} else {
					logger.error("qinLinDeleteUser", JsonUtil.toJson(qLinUser));
				}
			});
			return R.status(true);
		} else {
			return R.fail("删除失败");
		}
	}

	/******************************************小程序调用接口****************************************88*/
	/**
	 * 获取企业员工
	 */
	@GetMapping("/getEnterpriseList")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "小程序分页", notes = "传入enterpriseStaff")
	public R<IPage<EnterpriseStaffVO>> list(EnterpriseStaff enterpriseStaff, Query query) {
		IPage<EnterpriseStaff> wxpage = enterpriseStaffService.page(Condition.getPage(query), Condition.getQueryWrapper(enterpriseStaff).lambda().orderByDesc(EnterpriseStaff::getCreateTime));
		return R.data(EnterpriseStaffWrapper.build(agencyService, residentialService).pageVO(wxpage));
	}


	/**
	 * 下发人脸和人员信息到红外测温系统和设备
	 */
	@PostMapping("/pushUserFace")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "新增或修改", notes = "传入enterprise")
	public R pushUserFace(@Valid @RequestBody EnterpriseStaff enterpriseStaff) {

		if (enterpriseStaff.getAgencyId() == null) {
			Assert.notNull(null, "找不到对应上级归属！！！");
		}

		Repeater repeater = new Repeater();
		repeater.setAgencyId(enterpriseStaff.getAgencyId());
		Repeater one = repeaterService.getOne(Condition.getQueryWrapper(repeater));
		if(one != null){
			msgPublishService.publish(enterpriseStaff, one.getCode(), Instruct.ADD_USER);
		}
		QLinUser qLinUser = new QLinUser();
		qLinUser.setUserId(enterpriseStaff.getId().toString());
		if (StringUtil.isNotBlank(enterpriseStaff.getFace())) {
			qLinUser.setFaceUrl(enterpriseStaff.getFace());
		} else {
			return R.status(true);
		}
		Long agencyId = enterpriseStaff.getAgencyId();
		Long residentialId = enterpriseStaff.getResidentialId();
		Agency agency = this.agencyService.getById(agencyId);
		Residential residential = this.residentialService.getById(residentialId);
		String agencyPos = agency.getOrgPosition();
		String residentialPos = residential.getOrgPosition();
		List<FaceDevice> faceDeviceList = faceDeviceService.selectByAgencyOrXqOrUnitPositionList(agencyPos, residentialPos, null);
		if (faceDeviceList == null || faceDeviceList.size() <= 0) {
			return R.fail("人脸下发门禁失败，未找到人脸设备");
		}
		List<FaceDevice> zhDeviceList = new ArrayList<>();
		List<FaceDevice> qinLinDeviceList = new ArrayList<>();
		log.info("===========查询到的设备======================");
		log.info(JsonUtil.toJson(faceDeviceList));
		for (int i = 0; i < faceDeviceList.size(); i++) {
			FaceDevice faceDevice = faceDeviceList.get(i);
			if (faceDevice.getDeviceFactory() != null && faceDevice.getDeviceFactory().equals("zongheng")) {
				zhDeviceList.add(faceDevice);
			} else {
				qinLinDeviceList.add(faceDevice);
			}
		}
		if (zhDeviceList.size() > 0) {
			List<DeviceDTO> deviceDTOList = zhDeviceList.stream().map(item -> {
				DeviceDTO deviceDTO = new DeviceDTO();
				deviceDTO.setSerialNum(item.getMacAddress());
				deviceDTO.setFactory(item.getDeviceFactory());
				return deviceDTO;
			}).collect(Collectors.toList());
			UserDeviceDTO userDeviceDTO = new UserDeviceDTO();
			userDeviceDTO.setDeviceList(deviceDTOList);
			userDeviceDTO.setUserId(enterpriseStaff.getId().toString());
			userDeviceDTO.setUserFaceUrl(enterpriseStaff.getFace());
			userDeviceDTO.setUserName(enterpriseStaff.getRealName());
			log.info("========封装的设备==============");
			log.info(JSONUtil.toJsonStr(userDeviceDTO));
			return zhHttpUtil.addUser(userDeviceDTO);
		}
		String deviceIds = qinLinDeviceList.stream().map(FaceDevice::getMacAddress).collect(Collectors.joining(","));
		if (StringUtil.isNotBlank(deviceIds)) {
			qLinUser.setDeviceIds(deviceIds);
			QinLinApiResultBean qinLinApiResultBean = qinLinHttpUtil.addUser(qLinUser);
			if (qinLinApiResultBean.getCode().equals(0)) {
				return R.status(true);
			} else {
				return R.fail("人脸下发门禁失败");
			}
		}

		return R.status(true);

	}

	/**
	 * 禁用人脸
	 */
	@PostMapping("/deleteUserFace")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "禁用人脸", notes = "传入enterprise")
	public R deleteUserFace(@Valid @RequestBody EnterpriseStaff enterpriseStaff) {

		if (enterpriseStaff.getAgencyId() == null) {
			Assert.notNull(null, "找不到对应上级归属！！！");
		}
		QLinUser qLinUser = new QLinUser();
		qLinUser.setUserId(enterpriseStaff.toString());
		try{
			QinLinApiResultBean qinLinApiResultBean = qinLinHttpUtil.deleteUser(qLinUser);
		}catch (Exception e){
			e.printStackTrace();
		}
		Long agencyId = enterpriseStaff.getAgencyId();
		Long residentialId = enterpriseStaff.getResidentialId();
		Agency agency = this.agencyService.getById(agencyId);
		Residential residential = this.residentialService.getById(residentialId);
		String agencyPos = agency.getOrgPosition();
		String residentialPos = residential.getOrgPosition();
		List<FaceDevice> faceDeviceList = faceDeviceService.selectByAgencyOrXqOrUnitPositionList(agencyPos, residentialPos, null);
		if (faceDeviceList == null || faceDeviceList.size() <= 0) {
			return R.fail("人脸下发门禁失败，未找到人脸设备");
		}
		for (int i = 0; i < faceDeviceList.size(); i++) {
			FaceDevice faceDevice = faceDeviceList.get(i);
			if (faceDevice.getDeviceFactory() != null && faceDevice.getDeviceFactory().equals("zongheng")) {
				UserDeviceDTO userDeviceDTO = new UserDeviceDTO();;
				userDeviceDTO.setUserId(enterpriseStaff.getId().toString());
				zhHttpUtil.deleteUser(userDeviceDTO, faceDevice.getMacAddress());
			}
		}
		return R.status(true);
	}

	/**
	 * (批量) 下发人脸和人员信息到红外测温系统和设备
	 */
	@PostMapping("/pushUserFaceBatch")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "新增或修改", notes = "传入enterprise")
	public R pushUserFaceBatch(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		//针对超管管理-对于不同适配器下的员工人脸信息下发同时操作
		List<List<EnterpriseStaff>> staffList = new ArrayList<>();
		List<String> keyList = new ArrayList<>();

		List<Long> longs = Func.toLongList(ids);
		longs.forEach(item -> {
			EnterpriseStaff staff = enterpriseStaffService.getById(item);
			if (staff != null && StringUtils.isNotBlank(staff.getFace()) && staff.getAgencyId() != null) {
				Repeater repeater = new Repeater();
				repeater.setAgencyId(staff.getAgencyId());
				Repeater one = repeaterService.getOne(Condition.getQueryWrapper(repeater));
				if (one != null) {
					String routingKey = one.getCode();
					if (keyList.contains(routingKey)) {
						int index = keyList.indexOf(routingKey);
						List<EnterpriseStaff> list = staffList.get(index);
						list.add(staff);

					} else {
						keyList.add(one.getCode());
						List<EnterpriseStaff> list = new ArrayList<>();
						list.add(staff);
						staffList.add(list);
					}
				}

			}
		});

//		msgPublishService.publish(list,"000001", Instruct.ADD_USER_BATCH);

		for (int i = 0; i < keyList.size(); i++) {
			String key = keyList.get(i);
			msgPublishService.publish(staffList.get(i), key, Instruct.ADD_USER_BATCH);
		}

		//下发到人脸门禁设备
		for (int i = 0; i < longs.size(); i++) {
			Long id = longs.get(i);
			EnterpriseStaff staff = this.enterpriseStaffService.getById(id);
			if (StringUtil.isBlank(staff.getFace())) {
				continue;
			}
			Long agencyId = staff.getAgencyId();
			Long residentialId = staff.getResidentialId();
			Agency agency = this.agencyService.getById(agencyId);
			Residential residential = this.residentialService.getById(residentialId);
			String agencyPos = agency.getOrgPosition();
			String residentialPos = residential.getOrgPosition();
			List<FaceDevice> faceDeviceList = faceDeviceService.selectByAgencyOrXqOrUnitPositionList(agencyPos, residentialPos, null);
			if (faceDeviceList == null || faceDeviceList.size() <= 0) {
				logger.warn("pushUserFaceBatch", "no qinLin faceDevice --> staff id = " + id);
				continue;
			}
			String deviceIds = faceDeviceList.stream().map(FaceDevice::getMacAddress).collect(Collectors.joining(","));
			if (StringUtil.isBlank(deviceIds)) {
				logger.warn("pushUserFaceBatch", "qinLin faceDevices no mac --> staff id = " + id);
				continue;
			}
			QLinUser qLinUser = new QLinUser();
			qLinUser.setUserId(id.toString());
			qLinUser.setFaceUrl(staff.getFace());
			qLinUser.setDeviceIds(deviceIds);
			QinLinApiResultBean qinLinApiResultBean = qinLinHttpUtil.addUser(qLinUser);
			if (qinLinApiResultBean.getCode().equals(0)) {
				continue;
			} else {
				logger.warn("pushUserFaceBatch", "invoke qinLin addUser fail -->" + JsonUtil.toJson(qLinUser));
			}
		}

		return R.status(true);
	}


	/**
	 * 园区小程序登录接口
	 *
	 * @param enterpriseStaffDTO
	 * @return
	 */
	@PostMapping(value = "/app/login")
	public R<List<EnterpriseStaffVO>> login(@RequestBody EnterpriseStaffDTO enterpriseStaffDTO) {
		List<EnterpriseStaff> enterpriseStaffs = new ArrayList<>();
		if (enterpriseStaffDTO.getLoginType() == 0){//员工登录：根据手机号获取
			enterpriseStaffs = this.enterpriseStaffService.getBaseMapper().selectList(new QueryWrapper<>(new EnterpriseStaff()).lambda()
				.eq(EnterpriseStaff::getPhone, enterpriseStaffDTO.getPhone()));
		}else if(enterpriseStaffDTO.getLoginType() == 1){//企业登录：根据企业id,企业账号，企业密码获取
			enterpriseStaffs = this.enterpriseStaffService.getBaseMapper().selectList(new QueryWrapper<>(new EnterpriseStaff()).lambda()
				.eq(EnterpriseStaff::getEnterpriseId, enterpriseStaffDTO.getEnterpriseId())
				.eq(EnterpriseStaff::getIsEnterpriseManager, 1)
				.eq(EnterpriseStaff::getEnterpriseAccount, enterpriseStaffDTO.getEnterpriseAccount())
				.eq(EnterpriseStaff::getEnterprisePassword, enterpriseStaffDTO.getEnterprisePassword()));
		}else if(enterpriseStaffDTO.getLoginType() == 2){//管理员登录：根据园区id，园区管理员账号，园区管理员密码获取
			enterpriseStaffs = this.enterpriseStaffService.getBaseMapper().selectList(new QueryWrapper<>(new EnterpriseStaff()).lambda()
				.eq(EnterpriseStaff::getAgencyId,enterpriseStaffDTO.getAgencyId())
				.eq(EnterpriseStaff::getIsAgencyManager,1)
				.eq(EnterpriseStaff::getAgencyAccount,enterpriseStaffDTO.getAgencyAccount())
				.eq(EnterpriseStaff::getAgencyPassword,enterpriseStaffDTO.getAgencyPassword()));
		}

		return R.data(EnterpriseStaffWrapper.build(agencyService,residentialService).listVO(enterpriseStaffs));
	}

	/**
	 * 园区小程序修改密码接口
	 *
	 * @param loginType 0-员工登录（员工无需修改密码）  1-企业登录  2-管理员登录
	 * @param account   账号
	 * @param oldPassword 旧密码
	 * @param newPassword 新密码
	 * @return
	 */
	@PostMapping(value = "/app/updatePassword")
	public R updatePassword(@RequestParam Integer loginType,@RequestParam String account,@RequestParam String oldPassword,@RequestParam String newPassword) {

		if(loginType == 1){//企业管理员修改密码
			List<EnterpriseStaff> enterpriseStaffs = enterpriseStaffService.getBaseMapper().selectList(new QueryWrapper<>(new EnterpriseStaff()).lambda()
				.eq(EnterpriseStaff::getEnterpriseAccount, account)
				.eq(EnterpriseStaff::getEnterprisePassword, oldPassword));

			if(enterpriseStaffs.size() == 0){
				return R.data("旧密码不正确");
			}else {
				EnterpriseStaff enterpriseStaff = enterpriseStaffs.get(0);
				enterpriseStaff.setEnterprisePassword(newPassword);
				return R.data(enterpriseStaffService.updateById(enterpriseStaff));
			}
		}else if(loginType == 2){//园区管理员修改密码
			List<EnterpriseStaff> enterpriseStaffs = enterpriseStaffService.getBaseMapper().selectList(new QueryWrapper<>(new EnterpriseStaff()).lambda()
				.eq(EnterpriseStaff::getAgencyAccount, account)
				.eq(EnterpriseStaff::getAgencyPassword, oldPassword));

			if(enterpriseStaffs.size() == 0){
				return R.data("旧密码不正确");
			}else {
				EnterpriseStaff enterpriseStaff = enterpriseStaffs.get(0);
				enterpriseStaff.setAgencyPassword(newPassword);
				return R.data(enterpriseStaffService.updateById(enterpriseStaff));
			}
		}

		return R.data("登录方式不对：1-企业登录 2-管理员登录");
	}


	/**
	 * 园区小程序访客提交访客记录后获取具有审核该记录权限的管理员列表
	 *
	 * @param agencyId 园区id
	 * @param enterpriseId   企业id
	 * @return
	 */
	@GetMapping(value = "/app/getManagerList")
	public R<List<String>> getManagerList(@RequestParam(required = false) Long agencyId,@RequestParam(required = false) String enterpriseId) {
		if(agencyId != null){//获取园区管理员openid集合
			List<EnterpriseStaff> enterpriseStaffs = enterpriseStaffService.getBaseMapper().selectList(new QueryWrapper<>(new EnterpriseStaff()).lambda()
				.eq(EnterpriseStaff::getAgencyId, agencyId)
				.eq(EnterpriseStaff::getIsAgencyManager, 1));
			List<String> openIdList = enterpriseStaffs.stream().map(EnterpriseStaff::getOpenId).collect(Collectors.toList());
			return R.data(openIdList);
		}

		if(enterpriseId != null){
			List<EnterpriseStaff> enterpriseStaffs = enterpriseStaffService.getBaseMapper().selectList(new QueryWrapper<>(new EnterpriseStaff()).lambda()
				.eq(EnterpriseStaff::getEnterpriseId, enterpriseId)
				.eq(EnterpriseStaff::getIsEnterpriseManager, 1));
			List<String> openIdList = enterpriseStaffs.stream().map(EnterpriseStaff::getOpenId).collect(Collectors.toList());
			return R.data(openIdList);
		}
	return  R.data(null);
	}


	/**
	 * 树形
	 * @param enterpriseStaff
	 * @return
	 */
	@GetMapping("/tree")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "树形", notes = "传入enterpriseStaff")
	public R<TreeEntity> tree(EnterpriseStaffDTO enterpriseStaff){

		TreeEntity treeEntity = new TreeEntity();
		treeEntity.setType(0);
		Enterprise enterprise = this.enterpriseService.getById(enterpriseStaff.getEnterpriseId());
		//获取当前企业-除去当前打卡规则
		List<Rule> rules = this.ruleService.list(Condition.getQueryWrapper(new Rule()).lambda().eq(Rule::getOwnerId, enterpriseStaff.getEnterpriseId()));
		List<Long> ruleIds = rules.stream().map(Rule::getId).collect(Collectors.toList());
		if (enterpriseStaff.getRuleId() != null){
			ruleIds.remove(enterpriseStaff.getRuleId());
		}
		//根据打卡规则获取员工
		List<Long> rulePersonIds = this.rulePersonService.listByRuleIds(ruleIds);


		treeEntity.setId(enterprise.getId());
		treeEntity.setName(enterprise.getEnterpriseName());
		List<EnterpriseDept> deptList = this.enterpriseDeptService.list(Condition.getQueryWrapper(new EnterpriseDept()).lambda()
			.eq(EnterpriseDept::getEnterpriseId, enterprise.getId()));
		treeEntity.setHasChildren(deptList.size() > 0);
		deptList.forEach(dept -> {
			TreeEntity deptEntity = new TreeEntity();
			deptEntity.setType(1);
			deptEntity.setId(dept.getId());
			deptEntity.setName(dept.getName());
			deptEntity.setPId(dept.getEnterpriseId());
			List<EnterpriseStaff> staffList = this.enterpriseStaffService.list(Condition.getQueryWrapper(new EnterpriseStaff()).lambda()
				.eq(EnterpriseStaff::getDeptId, dept.getId()));
			deptEntity.setHasChildren(staffList.size() > 0);
			staffList.forEach(staff -> {
				TreeEntity staffEntity = new TreeEntity();
				staffEntity.setType(2);
				staffEntity.setId(staff.getId());
				staffEntity.setName(staff.getRealName());
				staffEntity.setPId(staff.getDeptId());
				staffEntity.setHasChildren(false);
				if (enterpriseStaff.getAttenceType() == 0 && rulePersonIds.contains(staff.getId())){
					staffEntity.setDisabled(true);
				}
				deptEntity.getChildren().add(staffEntity);
			});
			treeEntity.getChildren().add(deptEntity);
		});
		return R.data(treeEntity);
	}
}
