<?php

/**
 * Created by PhpStorm.
 * User: joe
 * Date: 17-1-18
 * Time: 下午5:17
 */
class Category  extends CI_Controller {

    public $user;

    function __construct() {
        parent::__construct();
        $this->load->model('users_model', 'users');
        $this->load->model('category_model', 'category');
        $this->user=$this->session->EXM_USER;
        if ($this->user['level'] < 7) {
            show_error('您没有权限访问此模块。');
        }
    }

    function index() {
        $data['categories'] =$this->category->get(null,'*');
        $this->load->view('admin/category/list',$data);
    }

    function edit() {
        $category=[
            'id' => $this->input->post('id')?:0,
            'name' => $this->input->post('name'),
            'parent_id' => $this->input->post('parent')
        ];

        $this->db->replace('category',$category);
        echo '保存成功';
    }

    function select($id) {
        if (!$id) {
            show_json(['error'=>'未选择科目。']);
        } else {
            $category['category']=$this->category->get($id);
            if ($category['category']['parent_id']==0) {
                $category['parent']=['id'=>0,'name'=>'根目录'];
            } else {
                $category['parent'] = $this->category->get($category['category']['parent_id']);
            }
            show_json($category);
        }
    }

    function delete($id) {
        if (!$id) {
            show_json(['error'=>'没有选择要删除的科目.']);
        } else {
            $sub=$this->category->get(null,'id',['parent_id'=>$id]);
            if ($sub) {
                show_json(['error'=>'此科目下还有子节点，请删除子节点后重试.']);
                return;
            }
            $this->db->where('id',$id)->delete('category');
            show_json(['success'=>'删除科目成功。']);
        }
    }

}