<?php

/**
 * Created by PhpStorm.
 * User: joe
 * Date: 17-2-4
 * Time: 下午5:13
 */
class Users extends CI_Controller {

    public $user;

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

    function index() {
        $data['cities'] = $this->city->get();
        $this->load->view('admin/users/list', $data);
    }

    function table() {
        $search = $this->input->get_post('search');
        $this->load->library('Datatables');

        $action = <<<ETO
<div class="btn-group btn-group-sm">
    <a href="#"  class="btn btn-default editUser" title="编辑">
        <i class="fa fa-edit"></i>
    </a>
    <a href="#"  class="btn btn-default deleteUser" title="编辑">
        <i class="fa fa-trash"></i>
    </a>
    <a href="#"  class="btn btn-default editUser" title="重置密码">
        <i class="fa fa-refresh"></i>
    </a>
</div>
ETO;

        if ($search['value']) {
            $this->datatables->like('users.name', $search['value']);
        }

        $this->datatables->select("users.id,users.name,users.level,city.name as city_name", false)->from('users')->join('city', 'city.id=users.city', 'left')->add_column('DT_RowId', '$1', 'id')->add_column('action', $action);

        echo $this->datatables->generate();
    }

    function get($id) {
        $this->db->join('city', 'city.id=users.city', 'left');
        $user = $this->users->get(null, 'users.id,users.name,users.level,users.city,city.name as city_name', 'users.id=' . $id);
        show_json($user);
    }

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

        $password = $this->input->post('password');

        if ($password) {
            $user['password'] = md5($password);
        } else if (!$user['id'] && !$password) {
            $user['password'] = md5('123');
        }

        if (!$user['id']) {
            $u=$this->users->get('','id',['name'=>$user['name']]);
            if ($u) {
                show_json(['error'=>'用户名已存在，请更改。']);
                return;
            }
        } else {
            $u=$this->users->get($user['id']);
            if (!$password) $user['password']=$u['password'];
        }

        $this->db->replace('users',$user);
        show_json(['success'=>'保存成功。']);
    }

    function delete() {
        $id=$this->input->post('id');
    }

}