<?php

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

    public $user;

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

    function index() {
        $data['groups']=$this->group->get(null,'id,name');
        $data['users'] = $this->users->get(null,'id,name','level<7');
        $this->load->view('admin/group/list',$data);
    }

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

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

    function add($id=null) {
        $data=[];
        if ($id) {
            $data['group']=$this->group->get($id);
        }
        $this->load->view('admin/group/add',$data);
    }

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

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

    function select($id=null) {
        if ($id) {
            $group=$this->group->get($id,'users');
            echo json_encode($group);
        } else {
            $group = $this->input->post('group');
            if (!$group) {
                echo '请选择分组后再保存。';
                return;
            }
            $users = $this->input->post('users');
            $select=[];
            foreach ($users as $user) {
                $select[]['id']=$user;
            }
            $this->db->set('users', json_encode($select))->where('id', $group)->update('group');
            echo "保存成功。";
        }
    }

    function delete($id) {
        if (!$id) {
            echo '';
        } else {

        }
    }

}