<?php

namespace Area\Src;

use Dever;

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

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

	/**
     * 获取地区数据
     *
     * @return mixed
     */
    public function get()
    {
        # 联动总数
        $level_total = Dever::input('level_total', 3);

        # 当前联动级别
        $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'] = '城市选择';
            } else {
                $default['name'] = '地区选择';
            }
        } else {
            $default = $this->default;
        }

        # 三级联动
        if ($level_num == 1) {
            $data = Dever::db('area/province')->getAll();
        } elseif ($level_num == 2) {
            $data = Dever::db('area/city')->getAll(array('province_id' => $level_id));
        } else {
            $data = Dever::db('area/county')->getAll(array('city_id' => $level_id));
        }

        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;
    }

    /**
     * 获取所有地区数据：json格式，生成js文件
     *
     * @return mixed
     */
    public function createJson()
    {
        $path = Dever::data() . 'upload/';
        $create = Dever::input('create', 1);
        $type = Dever::input('type', 'js');
        if ($type == 'klist') {
            $file = $path . 'city.' . $type . '.js';
        } else {
            $file = $path . 'city.' . $type;
        }
        
        if (!is_file($file)) {
            $create = 2;
        }
        if ($create == 2) {
            $array = array
            (
                array
                (
                    'value' => "-1",
                    'name' => '请选择',
                ),
            );

            $klist = Dever::db('area/province')->getAll();

            if ($type == 'klist') {
                $province = $klist;
            } else {
                $province = array_merge($array, $klist);
            }
            

            $province_data = array();
            $city_data = array();
            $county_data = array();

            foreach ($province as $k => $v) {
                $province_data[$k]['name'] = $v['name'];
                $province_data[$k]['id'] = $v['value'];

                if ($v['value'] <= 0) {
                    continue;
                }

                $klist[$k]['text'] = $v['name'];
                $klist[$k]['value'] = $v['value'];
                $klist[$k]['children'] = Dever::db('area/city')->getAll(array('province_id' => $v['value']));

                if ($type == 'klist') {
                    $city = $klist[$k]['children'];
                } else {
                    $city = array_merge($array, $klist[$k]['children']);
                }

                foreach ($city as $k1 => $v1) {
                    $city_data[$v['value']][$k1]['province'] = $v['name'];
                    $city_data[$v['value']][$k1]['name'] = $v1['name'];
                    $city_data[$v['value']][$k1]['id'] = $v1['value'];

                    if ($v1['value'] <= 0) {
                        continue;
                    }

                    $klist[$k]['children'][$k1]['text'] = $v1['name'];
                    $klist[$k]['children'][$k1]['value'] = $v1['value'];
                    $klist[$k]['children'][$k1]['children'] = Dever::db('area/county')->getAll(array('city_id' => $v1['value']));

                    if ($type == 'klist') {
                        $county = $klist[$k]['children'][$k1]['children'];
                    } else {
                        $county = array_merge($array, $klist[$k]['children'][$k1]['children']);
                    }

                    foreach ($county as $k2 => $v2) {
                        $klist[$k]['children'][$k1]['children'][$k2]['text'] = $v2['name'];
                        $klist[$k]['children'][$k1]['children'][$k2]['value'] = $v2['value'];

                        $county_data[$v1['value']][$k2]['city'] = $v1['name'];
                        $county_data[$v1['value']][$k2]['name'] = $v2['name'];
                        $county_data[$v1['value']][$k2]['id'] = $v2['value'];
                    }
                }
            }

            if ($type == 'klist') {
                 $content = 'var cities = ' . Dever::json_encode($klist) . ';';
            } elseif ($type == 'js') {
                $content = 'var provinces = ' . Dever::json_encode($province_data) . ';';
                $content .= 'var citys = ' . Dever::json_encode($city_data) . ';';
                $content .= 'var areas = ' . Dever::json_encode($county_data) . ';';
            } elseif ($type == 'plist') {
                $content = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>' . "\r\n";

                foreach ($province_data as $k => $v) {
                    $content .= '    <dict>
        <key>province</key>
        <string>'.$v['name'].'</string>
        <key>citys</key>
        <array>';

                    if (isset($city_data[$v['id']])) {
                        foreach ($city_data[$v['id']] as $k1 => $v1) {
                            $content .= "\r\n" . '            <dict>
                <key>city</key>
                <string>'.$v1['name'].'</string>
                <key>districts</key>
                <array>';

                            if (isset($county_data[$v1['id']])) {
                                foreach ($county_data[$v1['id']] as $k2 => $v2) {
                                    $content .= "\r\n" . '                    <string>'.$v2['name'].'</string>';
                                }

                                $content .= "\r\n                ";
                            }

                            $content .= '</array>' . "\r\n" . '            </dict>';
                        }

                        $content .= "\r\n        ";
                    }
                    

                    $content .= '</array>' . "\r\n" . '    </dict>' . "\r\n";
                }

                


                $content .= '</array>' . "\r\n" . '</plist>';
            }


            file_put_contents($file, $content);
        }

        $assets = Dever::config('host')->uploadRes;
        return str_replace($path, $assets, $file);
    }

    /**
     * 获取详细信息
     *
     * @return mixed
     */
    public function getInfo($area, $col = 'id')
    {
        if ($area) {
            $area = explode(',', $area);
            $result = array();
            foreach ($area as $k => $v) {
                if ($k == 0) {
                    $result[$k] = $this->getName('province', $v, true, $col);
                } elseif ($k == 1) {
                    $result[$k] = $this->getName('city', $v, true, $col);
                    if ($col == 'id' && isset($result[1]['name']) && $result[0]['name'] == $result[1]['name']) {
                        unset($result[1]);
                    }
                } elseif ($k == 2) {
                    $result[$k] = $this->getName('county', $v, true, $col);
                }
            }
            return $result;
        }
        return array();
    }

    /**
     * 根据地区id转成名称
     *
     * @return mixed
     */
    public function string($area, $im = ',')
    {
        if ($area) {
            $area = explode(',', $area);
            $result = array();
            foreach ($area as $k => $v) {
                if ($k == 0) {
                    $result[$k] = $this->getName('province', $v);
                } elseif ($k == 1) {
                    $result[$k] = $this->getName('city', $v);
                    if ($result[0] == $result[1]) {
                        unset($result[1]);
                    }
                } elseif ($k == 2) {
                    $result[$k] = $this->getName('county', $v);
                }
            }
            return implode($im, $result);
        }
        return '';
    }


    private function getName($table, $value, $state = false, $col = 'id')
    {
        $name = '不限';
        if (($col == 'id' && $value > 0) || ($col != 'id' && $value)) {
            $where[$col] = $value;
            $data = Dever::db('area/' . $table)->one($where);
            if ($state) {
                return $data;
            }
            if ($data) {
                $name = $data['name'];
            }
        }
        return $name;
    }

    # 获取6位地区编码
    public function code($id)
    {
        $id = substr($id, 0, 6);
        $id = str_pad($id, 6, '0', STR_PAD_RIGHT);
        return $id;
    }

    public function getProvince()
    {
        return Dever::db('area/province')->getAll();
    }

    public function getCity($province_id)
    {
        return Dever::db('area/city')->getAll(array('province_id' => $province_id));
    }
}
