<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\Department as DepartmentModel;
use app\admin\validate\DepartmentValidate;
use app\admin\model\Admin;
use think\facade\Db;

/**
 * @apiDefine header
 * @apiHeader {String} Authorization Bearer token
 */
class Department extends BaseController
{

    //获取部门列表
    public function list()
    {
        $params = $this->request->param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 15;
        $where = [];
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', "%{$params['name']}%"];
        }
        if (isset($params['status']) ) {
            $where[] = ['status', '=',$params['status']];
        }
        $count = DepartmentModel::where($where)->count();
        $list = DepartmentModel::where($where)
            ->order('parent_id','asc')
            ->order('weight','desc')
            ->limit($limit)
            ->page($page)
            ->select();
        return $this->success([
            'list' => $list,
            'count' => $count,
        ]);
    }

    
    //获取部门树形结构
    public function tree()
    {
        $list = DepartmentModel::where('status', 1)
            ->order('parent_id', 'asc')
            ->order('weight', 'desc')
            ->select();   
        $list = linear_to_tree($list);
        return $this->success($list);
    }

    //新增或编辑部门
    public function update()
    {
        try { 
            $params = (new DepartmentValidate)->post()->goCheck('edit');
            $id = $this->request->param('id',0);
            $name = $params['name'];
            $parent_id = $params['parent_id'] ?? 0;
            $weight = $params['weight'] ?? 1;
            $status = $params['status'] ?? 1;
            if ($id) {
                $department = DepartmentModel::where('id', $id)->find();
                if (!$department) {
                    return $this->error('部门不存在');
                }
            } else {
                $department = new DepartmentModel();
            }
            $department->name = $name;
            $department->parent_id = $parent_id;
            $department->weight = $weight;
            $department->status = $status;
            $department->remark = $params['remark'] ?? '';
            $department->save();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($department);
    }

    //设置部门状态
    public function setStatus()
    {
        $params = (new DepartmentValidate)->goCheck('id');
        $id = $params['id'];
        $department = DepartmentModel::where('id', $id)->find();
        if (!$department) {
            return $this->error('部门不存在');
        }
        $department->status = $department->status == 0 ? 1 : 0;
        $department->save();
        return $this->success($department);
    }

    public function delete() { 
        try {
            
            $params = (new DepartmentValidate)->goCheck('id');
            $id = $params['id'];
            $department = DepartmentModel::where('id', $id)->find();
            if (!$department) {
                return $this->error('部门不存在');
            }
            
            DB::startTrans();

            //查询所有下级部门
            $tree = DepartmentModel::getChildrenTree($id);

            //获取所有下级的ID
            $ids = DepartmentModel::getChildrenIds($tree);
            $ids[] = $id;
            $exists = Admin::whereIn('department_id', $ids)->count();
            if ($exists) {
                return $this->error('该部门下有用户，不能删除');
            }
            DepartmentModel::whereIn('id', $ids)->delete();
            $department->delete();
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success([], '删除成功');
    }
    
}
