<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\api\controller;

use app\api\ApiController;
use app\api\middleware\Auth;
use app\user\validate\DepartmentCheck;
use think\exception\ValidateException;
use think\facade\Request;
use think\facade\Db;

class UserDepartment extends ApiController
{

    protected $middleware = [
    	Auth::class => ['except' => []]
    ];

    //获取部门架构
    public function index()
    {
        $this->checkAuth();
        $param = get_params();
        if (!empty($param['tree']) && $param['tree'] == 1) {
            $list = set_recursion(get_department());
            foreach($list as $k=>$v) {
                $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $list[$k]['update_time'] = date('Y-m-d H:i:s', $v['update_time']);
            }
        } else {
            $cate = Db::name('Department')
            ->field('d.*,a.name as leader')
            ->alias('d')
            ->join('Admin a', 'a.id = d.leader_id', 'LEFT')
            ->order('d.sort desc,d.id asc')
            ->select()->toArray();
            foreach($cate as $k=>$v) {
                $cate[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $cate[$k]['update_time'] = date('Y-m-d H:i:s', $v['update_time']);
            }
            $list = generateTree($cate);
        }
        $this->apiSuccess('获取成功', $list);	
    }

    //添加部门
    public function add()
    {
        $this->checkAuth();
        $param = get_params();
        if (!empty($param['id']) && $param['id'] > 0) {
            try {
                validate(DepartmentCheck::class)->scene('edit')->check($param);
            } catch (ValidateException $e) {
                $this->apiError($e->getError());
            }
            $param['update_time'] = time();
            $department_array = get_department_son($param['id']);
            if (in_array($param['pid'], $department_array)) {
                $this->apiError('上级部门不能是该部门本身或其下属部门');
            } else {
                Db::name('Department')->strict(false)->field(true)->update($param);
                add_log('edit', $param['id'], $param);
                $this->apiSuccess('操作成功');	
            }
        } else {
            try {
                validate(DepartmentCheck::class)->scene('add')->check($param);
            } catch (ValidateException $e) {
                $this->apiError($e->getError());
            }
            $did = Db::name('Department')->strict(false)->field(true)->insertGetId($param);
            add_log('add', $did, $param);
            $this->apiSuccess('操作成功');	
        }
        
    }

    //删除
    public function delete()
    {
        $this->checkAuth();
        $id = get_params("id");
        if (empty($id)) {
            $this->apiError('部门id不能为空');
        }
        $count = Db::name('Department')->where([['pid', '=', $id], ['status', '>=', 0]])->count();
        if ($count > 0) {
            $this->apiError('该部门下还有子部门,无法删除');
        }
        $users = Db::name('Admin')->where([['did', '=', $id], ['status', '>=', 0]])->count();
        if ($users > 0) {
            $this->apiError('该部门下还有员工,无法删除');
        }
        if (Db::name('Department')->delete($id) !== false) {
            add_log('delete', $id);
            $this->apiSuccess('删除部门成功');
        } else {
            $this->apiError('删除失败');
        }
    }
}