/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 运维系统
 * 创建日期:2022/8/22
 */
package org.springblade.modules.baseinfo.servicePerson.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springblade.constant.BusinessConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.baseinfo.servicePerson.service.IServicePersonService;
import org.springblade.modules.baseinfo.servicePerson.vo.OrgPersonContactVO;
import org.springblade.modules.baseinfo.servicePerson.vo.ServicePersonVO;
import org.springblade.modules.baseinfo.servicePerson.wrapper.ServicePersonWrapper;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.UserVO;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/***
 * Date:2022/8/22
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@RequestMapping("galaxy-business/serviceperson")
@AllArgsConstructor
@Api(value = "项目运维人员管理", tags = "项目运维人员管理")
public class ServicePersonController extends BladeController {
	private final IServicePersonService servicePersonService;
	private final IUserService userService;
	private final IDeptService deptService;

	@GetMapping("/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "realName", value = "人员名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "phone", value = "联系电话", paramType = "query", dataType = "string"),
	})
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "分页")
	public R<IPage<UserVO>> orgPersonList(@ApiIgnore User userEntity, Query query) {
		BladeUser user = AuthUtil.getUser();
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			LambdaQueryWrapper<Dept> deptLambdaQueryWrapper = Wrappers.<Dept>query().lambda();
			deptLambdaQueryWrapper.eq(Dept::getIsDeleted, 0);
			deptLambdaQueryWrapper.eq(Dept::getParentId, Func.toLong(user.getDeptId()));
			List<Dept> deptList = deptService.list(deptLambdaQueryWrapper);
			if (null == deptList || deptList.size() == 0) {
				return R.data(null);
			}
			ArrayList<Long> deptIds = new ArrayList<>();
			for (Dept dept : deptList) {
				deptIds.add(dept.getId());
			}
			LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
			wrapper.eq(User::getIsDeleted, 0);
			wrapper.in(User::getDeptId, deptIds);
			if (userEntity.getRealName() != null) {
				wrapper.like(User::getRealName, userEntity.getRealName());
			}
			if (userEntity.getPhone() != null) {
				wrapper.like(User::getPhone, userEntity.getPhone());
			}
			IPage<User> pages = userService.page(Condition.getPage(query), wrapper);
			return R.data(ServicePersonWrapper.build().pageVO(pages));
		} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
			LambdaQueryWrapper<Dept> deptLambdaQueryWrapper = Wrappers.<Dept>query().lambda();
			deptLambdaQueryWrapper.eq(Dept::getIsDeleted, 0);
			deptLambdaQueryWrapper.eq(Dept::getParentId, Func.toLong(user.getDeptId()));
			List<Dept> deptList = deptService.list(deptLambdaQueryWrapper);
			if (null == deptList || deptList.size() == 0) {
				return R.data(null);
			}
			ArrayList<Long> deptIds = new ArrayList<>();
			for (Dept dept : deptList) {
				deptIds.add(dept.getId());
			}
			LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
			wrapper.eq(User::getIsDeleted, 0);
			wrapper.in(User::getDeptId, deptIds);
			wrapper.eq(User::getPostId, BusinessConstant.POST_ADMIN_ID);
			if (userEntity.getRealName() != null) {
				wrapper.like(User::getRealName, userEntity.getRealName());
			}
			if (userEntity.getPhone() != null) {
				wrapper.like(User::getPhone, userEntity.getPhone());
			}
			IPage<User> pages = userService.page(Condition.getPage(query), wrapper);
			return R.data(ServicePersonWrapper.build().pageVO(pages));
		} else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName())) {
			LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
			wrapper.eq(User::getIsDeleted, 0);
			wrapper.eq(User::getDeptId, Func.toLong(user.getDeptId()));
			wrapper.eq(User::getPostId, BusinessConstant.POST_SERVICE_PERSON_ID);
			if (userEntity.getRealName() != null) {
				wrapper.like(User::getRealName, userEntity.getRealName());
			}
			if (userEntity.getPhone() != null) {
				wrapper.like(User::getPhone, userEntity.getPhone());
			}
			IPage<User> pages = userService.page(Condition.getPage(query), wrapper);
			return R.data(ServicePersonWrapper.build().pageVO(pages));
		}
		return R.data(null);
	}


	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "列表")
	public R<List<User>> list() {
		BladeUser user = AuthUtil.getUser();
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
		wrapper.eq(User::getIsDeleted, 0);
		wrapper.eq(User::getDeptId, Func.toLong(user.getDeptId()));
		List<User> lists = userService.list(wrapper);
		return R.data(lists);
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "详情", notes = "传入 User")
	public R<User> detail(User user) {
		User detail = userService.getById(user.getId());
		return R.data(detail);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入 User")
	public R save(@RequestBody User userEntity) {
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
		wrapper.eq(User::getAccount, userEntity.getAccount());
		wrapper.eq(User::getIsDeleted, 0);
		List<User> list = userService.list(wrapper);
		if (null != list && list.size() > 0) {
			return R.fail("帐号已经存在");
		}
		userEntity.setName(userEntity.getRealName());
		userEntity.setPassword(DigestUtil.encrypt(userEntity.getAccount() + BusinessConstant.ACCOUNT_PW_SUFFIX));
		BladeUser user = AuthUtil.getUser();
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			userEntity.setRoleId(BusinessConstant.ROLE_ORG_ADMIN_ID);
			userEntity.setPostId(BusinessConstant.POST_ADMIN_ID);
		} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
			userEntity.setRoleId(BusinessConstant.ROLE_COMPANY_ADMIN_ID);
			userEntity.setPostId(BusinessConstant.POST_ADMIN_ID);
		} else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName())) {
			userEntity.setRoleId(BusinessConstant.ROLE_COMPANY_SERVICE_PERSON_ID);
			userEntity.setPostId(BusinessConstant.POST_SERVICE_PERSON_ID);
			userEntity.setDeptId(user.getDeptId());
		} else {
			return R.fail("用户创建错误！");
		}
		userEntity.setUserType(1);
		return R.status(userService.save(userEntity));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入 User")
	public R update(@RequestBody User user) {
		if (Objects.isNull(user.getId())) {
			return R.fail("用户ID不能为空！");
		}
		return R.status(userService.updateById(user));
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入 ids")
	public R remove(@ApiParam(value = "主键集合") @RequestParam String ids) {
		List<Long> list = Func.toLongList(ids);
		if (null != list && list.size() > 0) {
			for (Long id : list) {
				userService.removeById(id);
			}
		}
		return R.status(true);
	}

	/**
	 * 用户联系表
	 * @return
	 */
	@GetMapping("/contact")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "通讯录")
	public R<List<OrgPersonContactVO>> contact() {
		BladeUser user = AuthUtil.getUser();
		List<OrgPersonContactVO> list = new LinkedList<>();
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>query().lambda();
			wrapper.eq(Dept::getIsDeleted, 0);
			wrapper.eq(Dept::getParentId, Func.toLong(user.getDeptId()));
			List<Dept> root = this.deptService.list(wrapper);
			for (Dept dept : root) {
				OrgPersonContactVO contactVO = new OrgPersonContactVO();
				contactVO.setId(dept.getId());
				contactVO.setOrgName(dept.getDeptName());
				LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.<User>query().lambda();
				userLambdaQueryWrapper.eq(User::getIsDeleted, 0);
				userLambdaQueryWrapper.eq(User::getDeptId, Func.toStr(dept.getId()));
				List<User> userList = this.userService.list(userLambdaQueryWrapper);
				List<ServicePersonVO> personVOList = new LinkedList<>();
				for (User u : userList) {
					ServicePersonVO vo = new ServicePersonVO();
					vo.setId(u.getId());
					vo.setPersonName(u.getRealName());
					vo.setContactPhone(u.getPhone());
					personVOList.add(vo);
				}
				contactVO.setServicePersonVOList(personVOList);
				list.add(contactVO);
			}
		} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
			LambdaQueryWrapper<Dept> wrapper = Wrappers.<Dept>query().lambda();
			wrapper.eq(Dept::getIsDeleted, 0);
			wrapper.eq(Dept::getParentId, Func.toLong(user.getDeptId()));
			List<Dept> root = this.deptService.list(wrapper);
			for (Dept dept : root) {
				OrgPersonContactVO contactVO = new OrgPersonContactVO();
				contactVO.setId(dept.getId());
				contactVO.setOrgName(dept.getDeptName());
				LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.<User>query().lambda();
				userLambdaQueryWrapper.eq(User::getIsDeleted, 0);
				userLambdaQueryWrapper.eq(User::getDeptId, Func.toStr(dept.getId()));
				List<User> userList = this.userService.list(userLambdaQueryWrapper);
				List<ServicePersonVO> personVOList = new LinkedList<>();
				for (User u : userList) {
					ServicePersonVO vo = new ServicePersonVO();
					vo.setId(u.getId());
					vo.setPersonName(u.getRealName());
					vo.setContactPhone(u.getPhone());
					personVOList.add(vo);
				}
				contactVO.setServicePersonVOList(personVOList);
				list.add(contactVO);
			}
		} else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
			OrgPersonContactVO contactVO = new OrgPersonContactVO();
			contactVO.setId(Func.toLong(user.getDeptId()));
			Dept dept = this.deptService.getById(contactVO.getId());
			contactVO.setOrgName(dept.getDeptName());
			LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.<User>query().lambda();
			userLambdaQueryWrapper.eq(User::getIsDeleted, 0);
			userLambdaQueryWrapper.eq(User::getDeptId, Func.toStr(dept.getId()));
			List<User> userList = this.userService.list(userLambdaQueryWrapper);
			List<ServicePersonVO> personVOList = new LinkedList<>();
			for (User u : userList) {
				ServicePersonVO vo = new ServicePersonVO();
				vo.setId(u.getId());
				vo.setPersonName(u.getRealName());
				vo.setContactPhone(u.getPhone());
				personVOList.add(vo);
			}
			contactVO.setServicePersonVOList(personVOList);

			list.add(contactVO);
		}
		return R.data(list);
	}
}
