<?php

/**
 * Created by PhpStorm.
 * User: joe
 * Date: 17-1-20
 * Time: 上午10:02
 */
class Type extends CI_Controller {

    public $user;

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

    function index() {
        $this->load->view('admin/type');
    }

    function table() {
        $this->load->library('Datatables');
        $action = <<<ETO
<div class="btn-group btn-group-sm">
    <a href="#"  class="btn btn-default editType" title="编辑题型">
        <i class="fa fa-edit"></i>
    </a>
    <a href="#" class="btn btn-default deleteType" title="删除题型">
        <i class="fa fa-trash"></i>
    </a>
</div>
ETO;

        $this->datatables->select("id,name,type", false)
            ->from('types')
            ->add_column('DT_RowId', '$1', 'id')
            ->add_column('action', $action);
        echo $this->datatables->generate();
    }

    function select($id) {
        if (!$id) {
            show_json(['error' => '未选择要编辑的类型']);
        } else {
            $type = $this->type->get($id);
            show_json($type);
        }
    }

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

        if (!$type['name']) {
            show_json(['error' => '您没有输入分组名称。']);
        } else {
            $this->db->replace('types', $type);
            show_json(['success' => '保存题型 ' . $type['name'] . ' 成功。']);
        }
    }

}