<?php
namespace app\admin\controller;

use app\admin\model\DepartmentModel;
use app\admin\validate\DepartmentValidate;
use think\Request;

class Department extends Base
{
    public function index(){
        $data = $this->getDepartmentList();
        $this->assign('data',$data);
        return $this->fetch('index');
    }

    public function create(){
        $data = $this->getDepartmentList();
        $this->assign('data',$data);
        return $this->fetch('add');
    }

    public function edit($id){
        $department = DepartmentModel::find($id);
        $data = $this->getDepartmentList();
        $this->assign('data',$data);
        $this->assign('department',$department);
        return $this->fetch('edit');
    }

    public function store(Request $request){
        $id = $request->post('id') + 0;
        //更新操作
        if($id){
            $depart = DepartmentModel::find($id);
            $depart->name = $request->post('name');
            $depart->pid = $request->post('pid');
            $depart->sort = $request->post('sort');
            if($depart->save()){
                return jsonSuc('更新成功!');
            } else {
                return jsonErr('更新失败');
            }
        } else {
            $validate = new DepartmentValidate;
            if(!($validate->check($request->post()))){
                return jsonErr($validate->getError());
            }

            $depart = new DepartmentModel([
                'name' => $request->post('name'),
                'pid' => $request->post('pid'),
                'sort' => $request->post('sort')
            ]);
            if($depart->save()){
                return jsonSuc('部门新增成功');
            } else {
                return jsonErr('部门新增失败，请重试');
            }
        }
    }

    public function delete(Request $request){
        $id =  $request->post('id');
        $department = DepartmentModel::find($id)->toArray();
        if(!$department){
            return jsonErr('参数错误,要删除的资源不存在');
        }

        //递归取出下面所有部门的id
        $departments = DepartmentModel::select()->toArray();
        $data = getTree($departments,$department['id']);
        $data[] = $department;

        foreach ($data as $item) {
            $ids[] = $item['id'];
        }

        if(DepartmentModel::destroy($ids)){
            return jsonSuc('删除部门成功');
        } else {
            return jsonErr('删除失败');
        }
    }

    private function getDepartmentList(){
        $data = DepartmentModel::order('sort desc,id asc')->select();
        $data = getTree($data);
        foreach ($data as &$value){
            $value['name'] = str_repeat('--', $value['level']).$value['name'];
        }
        return $data;
    }
}