<?php

/**
 * Created by PhpStorm.
 * User: joe
 * Date: 17-1-20
 * Time: 上午9:39
 */
class City 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('您没有权限访问此模块。');
        }
    }

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

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

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

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

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