<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/3/10
 * Time: 下午2:33
 */

namespace area;
require_once(BASE_ROOT_PATH . '/helper/util_helper.php');

class area_check
{
    protected $mItems;
    protected $mAreaIds;
    protected $mNameToProvid;
    protected $mod_area;

    public function __construct($table = 'area')
    {
        $this->mod_area = Model($table);
        $this->mItems = [];
        $this->mAreaIds = [];
        $this->mNameToProvid = [];

        $this->init();
    }
    protected function sub_areas($parent_id)
    {
        $items = $this->mod_area
            ->where(array('area_parent_id' => $parent_id,'enable' => 1))
            ->field('area_id,area_parent_id,area_deep,area_name')
            ->order('area_parent_id ASC,area_id ASC,area_name ASC')
            ->limit(false)
            ->select();
        return $items;
    }

    protected function init()
    {
        $items = $this->sub_areas(0);
        foreach ($items as $item)
        {
            $area_id = intval($item['area_id']);
            $area_name = trim($item['area_name']);
            if($area_id >= 32) continue; //海外地区不处理了。

            $this->mItems[$area_id] = $item;
            $this->mAreaIds[$area_id] = [];
            $this->mNameToProvid[$area_name] = $area_id;

            $this->load($area_id);
        }
    }

    protected function load($parent_id)
    {
        $items = $this->sub_areas($parent_id);
        foreach ($items as $item)
        {
            $area_id = intval($item['area_id']);
            $this->mItems[$area_id] = $item;
            $this->mAreaIds[$area_id] = [];
            $this->mAreaIds[$parent_id][] = $area_id;

            $this->load($area_id);
        }
    }

    protected function next($ids)
    {
        $result = [];
        foreach ($ids as $id) {
            $subs = $this->mAreaIds[$id];
            $result = array_merge($result,$subs);
        }
        return $result;
    }

    public function export()
    {
        $items = $this->sub_areas(0);
        $provins = [];
        foreach ($items as $item) {
            $area_id = intval($item['area_id']);
            if($area_id >= 32) continue; //海外地区不处理了。
            $provins[] = $area_id;
        }
        $areas = $provins;
        $citys = $this->next($provins);
        $areas = array_merge($areas,$citys);

        $contrys = $this->next($citys);
        $areas = array_merge($areas,$contrys);

        $result = [];
        foreach ($areas as $id)
        {
            $item = [];
            $item['aid'] = $this->mItems[$id]['area_id'];
            $item['pid'] = $this->mItems[$id]['area_parent_id'];
            $item['n'] = $this->mItems[$id]['area_name'];
            $item['d'] = $this->mItems[$id]['area_deep'];
            $result[] = $item;
        }

        return $result;
    }
}