<?php

namespace Shop\Lib;

use Dever;

class Area
{
    private $default = array
    (
        'value' => -1,
        'name' => '不限',
    );

    private $search_default = array
    (
        'value' => -1,
        'name' => '地区选择',
    );

    /**
     * 获取地区数据
     *
     * @return mixed
     */
    public function get_api()
    {
        # 联动总数，默认到县区
        $level_total = Dever::input('level_total', 5);

        # 当前联动级别
        $level_num = Dever::input('level_num');

        # 一般为id
        $level_id = Dever::input('level_id');

        # 是否是搜索列表页
        $level_search = Dever::input('level_search');
        if ($level_search) {
            $default = $this->search_default;
            if ($level_num == 1) {
                $default['name'] = '省份选择';
            } elseif ($level_num == 2) {
                $default['name'] = '城市选择';
            } elseif ($level_num == 3) {
                $default['name'] = '县区选择';
            } elseif ($level_num == 4) {
                $default['name'] = '街道选择';
            } else {
                $default['name'] = '门店选择';
            }
        } else {
            $default = $this->default;
        }

        if ($level_id < 0) {
            Dever::alert('error');
        }

        # 四级联动
        if ($level_num == 1) {
            $t = 'area/province';
            $data = Dever::db($t)->getAll();
        } elseif ($level_num == 2) {
            $t = 'area/city';
            $data = Dever::db($t)->getAll(array('province_id' => $level_id));
        } elseif ($level_num == 3) {
            $t = 'area/county';
            $data = Dever::db($t)->getAll(array('city_id' => $level_id));
        } elseif ($level_num == 4) {
            $t = 'area/town';
            $data = Dever::db($t)->getAll(array('county_id' => $level_id));
        } elseif ($level_num == 5) {
            if ($level_id > 0) {
                $data = Dever::db('shop/info')->getAll(array('town' => $level_id));
            } else {
                $data = false;
            }
        }

        if (!$data) {
            Dever::alert('error');
        }

        if ($level_search || $level_num >= 1) {
            array_unshift($data, $default);
        }

        $result['level_total'] = $level_total;
        $result['list'] = $data;
        return $result;
    }
}