<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace App\Http\Controllers\Auth;

use App\Services\Auth\DepartmentService;
use App\Http\Controllers\Base;
use App\Support\Tree;
use Illuminate\Support\Arr;

class Department extends Base{

	/**
	 * @title 部门数据
	 */
	public function index(DepartmentService $service){
		$data = $service->getDepartmentList(request());

		$sortData = Arr::keyBy($data, 'partent_id');

		$this->data['data'] = (new Tree())->listToTree($data->toArray(), 'id', 'parent_id', 'children');
		return $this->data;
	}

	/**
	 * @title 添加部门
	 *
	 * @param DepartmentService $service
	 * @return void
	 */
	public function add(DepartmentService $service){
		try {
			$service->createDepartment(request());
			$this->data['message']  = '添加成功！';
		} catch (\Exception $e) {
			$this->data['code'] = 0;
			$this->data['message']  = $e->getMessage();
		}
		return $this->data;
	}

	/**
	 * @title 修改部门
	 *
	 * @param DepartmentService $service
	 * @return void
	 */
	public function edit(DepartmentService $service){
		try {
			$service->updateDepartment(request());
			$this->data['message']  = '修改成功！';
		} catch (\Exception $e) {
			$this->data['code'] = 0;
			$this->data['message']  = $e->getMessage();
		}
		return $this->data;
	}

	/**
	 * @title 删除部门
	 *
	 * @param DepartmentService $service
	 * @return void
	 */
	public function delete(DepartmentService $service){
		try {
			$service->deleteDepartment(request());
			$this->data['message']  = '删除成功！';
		} catch (\Exception $e) {
			$this->data['code'] = 0;
			$this->data['message']  = $e->getMessage();
		}
		return $this->data;
	}
}
