/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/8/22
 */
package org.springblade.modules.business.project.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.flowable.idm.engine.impl.persistence.entity.UserEntity;
import org.flowable.spring.security.UserDto;
import org.springblade.constant.BusinessConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.launch.constant.AppConstant;
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.business.project.base.entity.ProjectInfoEntity;
import org.springblade.modules.business.project.servicePerson.entity.ServicePersonEntity;
import org.springblade.modules.business.project.servicePerson.service.IProjectServicePersonService;
import org.springblade.modules.business.project.servicePerson.vo.OrgPersonContactVO;
import org.springblade.modules.business.project.servicePerson.vo.ServicePersonVO;
import org.springblade.modules.business.project.servicePerson.wrapper.ProjectServicePersonWrapper;
import org.springblade.modules.business.rtu.base.dto.RtuInfoDTO;
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.springframework.util.DigestUtils;
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/project/person")
@AllArgsConstructor
@Api(value = "项目运维人员管理", tags = "项目运维人员管理")
public class ProjectServicePersonController extends BladeController {
	private final IProjectServicePersonService servicePersonService;
	private final IUserService userService;
	private final IDeptService deptService;

	@GetMapping("/org/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "personName", value = "人员名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "contactPhone", value = "联系电话", paramType = "query", dataType = "string"),
	})
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页")
	public R<IPage<ServicePersonVO>> orgPersonList(@ApiIgnore ServicePersonEntity personEntity, Query query) {
		BladeUser user = AuthUtil.getUser();
		personEntity.setOrgId(null);
		if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_ORG_SERVICE_PERSON.equals(user.getRoleName())) {
			personEntity.setOrgId(Func.toLong(user.getDeptId()));
		}
		IPage<ServicePersonVO> pages = servicePersonService.selectPage(Condition.getPage(query), personEntity);
		return R.data(pages);
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入servicePersonEntity")
	public R<ServicePersonVO> detail(ServicePersonEntity servicePersonEntity) {
		ServicePersonEntity detail = servicePersonService.getOne(Condition.getQueryWrapper(servicePersonEntity));
		return R.data(ProjectServicePersonWrapper.build().entityVO(detail));
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入servicePersonEntity")
	public R save(@RequestBody ServicePersonEntity servicePersonEntity) {
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>query().lambda();
		wrapper.eq(User::getAccount, servicePersonEntity.getUserAccount());
		wrapper.eq(User::getIsDeleted, 0);
		List<User> list = userService.list(wrapper);
		if (null != list && list.size() > 0) {
			return R.fail("帐号已经存在");
		}
		User u = new User();
		u.setAccount(servicePersonEntity.getUserAccount());
		u.setPhone(servicePersonEntity.getContactPhone());
		u.setEmail(servicePersonEntity.getMail());
		u.setName(servicePersonEntity.getPersonName());
		u.setRealName(servicePersonEntity.getPersonName());
		u.setPassword(DigestUtil.encrypt(servicePersonEntity.getUserAccount() + BusinessConstant.ACCOUNT_PW_SUFFIX));
		BladeUser user = AuthUtil.getUser();
		u.setDeptId(user.getDeptId());
		//u.setDeptId(Func.toStr(servicePersonEntity.getOrgId()));
		u.setRoleId(BusinessConstant.ROLE_ORG_SERVICE_PERSON_ID);
		u.setPostId(BusinessConstant.SERVICE_PERSON_POST_ID);
		u.setUserType(1);
		userService.save(u);
		servicePersonEntity.setUserId(u.getId());
		servicePersonEntity.setOrgId(Func.toLong(user.getDeptId()));
		return R.status(servicePersonService.save(servicePersonEntity));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入servicePersonEntity")
	public R update(@RequestBody ServicePersonEntity servicePersonEntity) {
		if (Objects.isNull(servicePersonEntity.getUserId())) {
			return R.fail("用户ID不能为空！");
		}
		User u = userService.getById(servicePersonEntity.getUserId());
		u.setPhone(servicePersonEntity.getContactPhone());
		u.setName(servicePersonEntity.getPersonName());
		u.setEmail(servicePersonEntity.getMail());
		u.setRealName(servicePersonEntity.getPersonName());
		userService.updateById(u);
		return R.status(servicePersonService.updateById(servicePersonEntity));
	}

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

	/**
	 * 机构树
	 *
	 * @return
	 */
	@GetMapping("/org/dict")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情")
	public R<List<Dept>> orgTree() {
		BladeUser user = AuthUtil.getUser();
		List<Dept> list = new ArrayList<>();
		if (BusinessConstant.ROLE_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_SUPER_ADMIN.equals(user.getRoleName())) {
			List<Dept> root = this.deptService.getDeptChild(0L);
			list = this.deptService.getDeptChild(root.get(0).getId());
		} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_ORG_SERVICE_PERSON.equals(user.getRoleName())) {
			Dept root = this.deptService.getById(Func.toLong(user.getDeptId()));
			list.add(root);
		}
		return R.data(list);
	}

	@GetMapping("/contact")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "通讯录")
	public R<List<OrgPersonContactVO>> contact() {
		BladeUser user = AuthUtil.getUser();
		List<Dept> root = this.deptService.getDeptChild(Func.toLong(user.getDeptId()));
		List<OrgPersonContactVO> list = new LinkedList<>();
		for (Dept dept : root) {
			OrgPersonContactVO contactVO = new OrgPersonContactVO();
			contactVO.setId(dept.getId());
			contactVO.setOrgName(dept.getDeptName());
			ServicePersonEntity personEntity = new ServicePersonEntity();
			personEntity.setOrgId(contactVO.getId());
			List<ServicePersonVO> personVOList = this.servicePersonService.selectAllList(personEntity);
			contactVO.setServicePersonVOList(personVOList);
			list.add(contactVO);
		}
		return R.data(list);
	}
}
