/*
 *
 *      Copyright (c) 2018-2025, hnqz 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 pig4cloud.com 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: hnqz
 *
 */

package com.qunzhixinxi.hnqz.admin.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDeptRelation;
import com.qunzhixinxi.hnqz.admin.entity.WmDaAgent;
import com.qunzhixinxi.hnqz.admin.entity.WmDaDrugEnt;
import com.qunzhixinxi.hnqz.admin.service.SysDeptRelationService;
import com.qunzhixinxi.hnqz.admin.service.SysDeptService;
import com.qunzhixinxi.hnqz.admin.service.WmDaAgentService;
import com.qunzhixinxi.hnqz.admin.service.WmDaDrugEntService;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.log.annotation.SysLog;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 前端控制器
 * </p>
 *
 * @author hnqz
 * @since 2018-01-20
 */
@RestController
@AllArgsConstructor
@RequestMapping("/dept")
@Api(value = "dept", tags = "部门管理模块")
public class SysDeptController {

	private final SysDeptRelationService relationService;

	private final SysDeptService sysDeptService;

	private final WmDaDrugEntService wmDaDrugEntService;

	private final WmDaAgentService wmDaAgentService;

	/**
	 * 通过ID查询
	 * @param id ID
	 * @return SysDept
	 */
	@GetMapping("/{id}")
	public R getById(@PathVariable Integer id) {
		return R.ok(sysDeptService.getById(id));
	}

	/**
	 * 返回树形菜单集合
	 * @return 树形菜单
	 */
	@GetMapping(value = "/tree")
	public R getTree(SysDept sysDept) {
		return R.ok(sysDeptService.selectTree(sysDept));
	}


	/**
	 * 返回树形菜单集合
	 * @return 树形菜单
	 */
	@GetMapping(value = "/treeAddUser")
	public R getTreeAddUser(SysDept sysDept) {
		return R.ok(sysDeptService.selectTreeAddUser(sysDept));
	}
	/**
	 * 添加
	 * @param sysDept 实体
	 * @return success/false
	 */
	@SysLog("添加部门")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_dept_add')")
	public R save(@Valid @RequestBody SysDept sysDept) {
		int level=sysDept.getLevel();
		SysDept selDept=new SysDept();
		if(level==2)
		{
			selDept.setLevel1Id(sysDept.getLevel1Id());
		}else if(level==3)
		{
			if(null!=sysDept.getParentId())
			{
				SysDept le2=sysDeptService.getById(sysDept.getParentId());
				if(null!=le2)
				{
					sysDept.setLevel1Id(le2.getLevel1Id());
					sysDept.setLevel1Name(le2.getLevel1Name());
					selDept.setLevel1Id(le2.getLevel1Id());
				}
			}
			selDept.setLevel2Id(sysDept.getLevel2Id());
		}else if(level==4)
		{
			if(null!=sysDept.getParentId())
			{
				SysDept le3=sysDeptService.getById(sysDept.getParentId());
				if(null!=le3)
				{
					sysDept.setLevel2Id(le3.getLevel2Id());
					sysDept.setLevel2Name(le3.getLevel2Name());
					selDept.setLevel1Id(le3.getLevel1Id());
				}

				if(null!=le3.getParentId())
				{
					SysDept le2=sysDeptService.getById(le3.getParentId());
					if(null!=le2)
					{
						sysDept.setLevel1Id(le2.getLevel1Id());
						sysDept.setLevel1Name(le2.getLevel1Name());
					}
				}
			}


			selDept.setLevel3Id(sysDept.getLevel3Id());
		}else{
			return R.failed("不允许录入的组织机构");
		}

		if(null==sysDept.getDeptId())
		{
			return R.failed("组织机构信息只能选择，不能手工输入");
		}

		List<SysDept> list=sysDeptService.list(Wrappers.query(selDept));
		if(list.size()>0)
		{
			return R.failed("机构信息已录入组织架构");
		}else {
			Integer deptId=sysDeptService.saveDept(sysDept);
			if(deptId>0)
			{
				if(level==2)
				{
					WmDaDrugEnt wmDaDrugEnt= wmDaDrugEntService.getById(sysDept.getLevel1Id());
					if(null!=wmDaDrugEnt)
					{
						wmDaDrugEnt.setDeptId(deptId+"");
						wmDaDrugEntService.updateById(wmDaDrugEnt);
					}
				}else if(level==3)
				{
					WmDaAgent wmDaAgent= wmDaAgentService.getById(sysDept.getLevel2Id());
					if(null!=wmDaAgent)
					{
						wmDaAgent.setDeptId(deptId+"");
						wmDaAgentService.updateById(wmDaAgent);
					}
				}else if(level==4)
				{
					WmDaAgent wmDaAgent= wmDaAgentService.getById(sysDept.getLevel3Id());
					if(null!=wmDaAgent)
					{
						wmDaAgent.setDeptId(deptId+"");
						wmDaAgentService.updateById(wmDaAgent);
					}
				}
			}
			return R.ok(deptId>0?true:false);
		}
	}

	/**
	 * 删除
	 * @param id ID
	 * @return success/false
	 */
	@SysLog("删除部门")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('sys_dept_del')")
	public R removeById(@PathVariable Integer id) {
		return R.ok(sysDeptService.removeDeptById(id));
	}

	/**
	 * 编辑
	 * @param sysDept 实体
	 * @return success/false
	 */
	@SysLog("编辑部门")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys_dept_edit')")
	public R update(@Valid @RequestBody SysDept sysDept) {
		sysDept.setUpdateTime(LocalDateTime.now());
		return R.ok(sysDeptService.updateDeptById(sysDept));
	}

	/**
	 * 查收子级列表
	 * @return 返回子级
	 */
	@GetMapping(value = "/getDescendantList/{deptId}")
	public R getDescendantList(@PathVariable Integer deptId) {
		return R.ok(
				relationService.list(Wrappers.<SysDeptRelation>lambdaQuery().eq(SysDeptRelation::getAncestor, deptId)));
	}



	/**
	 * 修改个人信息
	 * @return success/false
	 */
	@SysLog("查询用户列表")
	@GetMapping("/list")
	public R listUserInfo(SysDept sysDept) {

		List<SysDept> list=sysDeptService.list();
		List<Map<String,String>> answerList=new ArrayList<>();
		if(list.size()>0)
		{
			for(SysDept sysUser:list) {
				Map<String, String> map = new HashMap<>();
				map.put("dept_id",sysUser.getDeptId()+"");
				map.put("name",sysUser.getName()+"");
				answerList.add(map);
			}

		}
		return R.ok(answerList);
	}


	/**
	 * 修改个人信息
	 * @return success/false
	 */
	@SysLog("查询用户列表")
	@GetMapping("/listScope")
	public R listScope(SysDept sysDept) {

		List<SysDept> list=sysDeptService.listScope(sysDept);
		List<Map<String,String>> answerList=new ArrayList<>();
		if(list.size()>0)
		{
			for(SysDept sysUser:list) {
				Map<String, String> map = new HashMap<>();
				map.put("deptId",sysUser.getDeptId()+"");
				map.put("name",sysUser.getName()+"");
				answerList.add(map);
			}

		}
		return R.ok(answerList);
	}

	@SysLog("查询用户列表")
	@GetMapping("/selectDeptByName")
	public R selectDeptByName(SysDept sysDept) {

		List<SysDept> list=sysDeptService.selectDeptByName(sysDept);
		List<Map<String,String>> answerList=new ArrayList<>();
		if(list.size()>0)
		{
			for(SysDept sysUser:list) {
				Map<String, String> map = new HashMap<>();
				map.put("deptId",sysUser.getDeptId()+"");
				map.put("name",sysUser.getName()+"");
				answerList.add(map);
			}

		}
		return R.ok(answerList);
	}




	/**
	 * 修改个人信息
	 * @return success/false
	 */
	@SysLog("获取组织架构完整名称")
	@GetMapping("/getDeptBuildNameById")
	public R getDeptBuildNameById(String deptId,String type) {

		SysDept sysDept=sysDeptService.getById(deptId);
		String buildName="";
		if("user".equals(type))
		{

		}else if("agent".equals(type))
		{
			if(null!=sysDept) {
				sysDept = sysDeptService.getById(sysDept.getParentId());
			}
		}

		if(null!=sysDept&&sysDept.getLevel()==3)
		{

			if(null!=sysDept.getLevel1Id()&&!"".equals(sysDept.getLevel1Id()))
			{
				WmDaDrugEnt wmDaDrugEnt=wmDaDrugEntService.getById(sysDept.getLevel1Id());
				if(null!=wmDaDrugEnt)
				{
					if(!"".equals(buildName))
					{
						buildName=buildName+"-"+wmDaDrugEnt.getEntname();
					}else{
						buildName=wmDaDrugEnt.getEntname();
					}
				}
			}


			if(null!=sysDept.getLevel2Id()&&!"".equals(sysDept.getLevel2Id()))
			{
				WmDaAgent wmDaAgent=wmDaAgentService.getById(sysDept.getLevel2Id());
				if(null!=wmDaAgent)
				{
					if(!"".equals(buildName))
					{
						buildName=buildName+"-"+wmDaAgent.getGsmc();
					}else{
						buildName=wmDaAgent.getGsmc();
					}
				}
			}


		}

		if(null!=sysDept&&sysDept.getLevel()==2)
		{
			if(null!=sysDept.getLevel1Id()&&!"".equals(sysDept.getLevel1Id()))
			{
				WmDaDrugEnt wmDaDrugEnt=wmDaDrugEntService.getById(sysDept.getLevel1Id());
				if(null!=wmDaDrugEnt)
				{
					if(!"".equals(buildName))
					{
						buildName=buildName+"-"+wmDaDrugEnt.getEntname();
					}else{
						buildName=wmDaDrugEnt.getEntname();
					}
				}
			}
		}
		return R.ok(buildName);
	}

	@GetMapping("/page" )
	public R getSysDeptPage(SysDept sysDept) {
		return R.ok(sysDeptService.list());
	}

	@GetMapping("/selectSysDeptList" )
	public R selectSysDeptList(Page page, SysDept sysDept) {
		return R.ok(relationService.selectSysDeptList(page,sysDept));
	}

	/**
	 * 查询关联服务企业列表
	 * @return
	 */
	@GetMapping("/getAllParentDept")
	public R getAllParentDept() {
		SysDept sysDept=new SysDept();
		sysDept.setDeptId(SecurityUtils.getUser().getDeptId());
		List<SysDept> list=sysDeptService.getAllParentDept(sysDept);
		return R.ok(list);
	}

	/**
	 * 查询服务上级
	 * @return list
	 */
	@GetMapping("/getParentDept")
	public R getParentDept() {
		SysDept sysDept=new SysDept();
		sysDept.setDeptId(SecurityUtils.getUser().getDeptId());
		List list=sysDeptService.getParentDept(sysDept);
		return R.ok(list);
	}

	/**
	 * 查询服务上级
	 * @return list
	 */
	@GetMapping("/getChildDept")
	public R getChildDept() {
		SysDept sysDept=new SysDept();
		sysDept.setDeptId(SecurityUtils.getUser().getDeptId());
		List list=sysDeptService.getChildDept(sysDept);
		return R.ok(list);
	}


	/**
	 *  Integer类型deptId -> name
	 *  自定义sql 包含停用的机构
	 * @return list
	 */
	@GetMapping("/convertToName")
	public R convertToName() {
		return R.ok(sysDeptService.convertToName());
	}
}
