<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
/**
 * 地区接口
 */
class Area extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function area_list(){
        $pid = input('pid',0);

        $list = Db::name('shopro_area')->field('id,pid,name,level')->where('pid',$pid)->order('id asc')->select();

        $this->success('success',$list);
    }

    //给ios用的
    //一个接口全部数据都给到
    public function area_json(){
        $list   = Db::name('shopro_area')->field('id,pid,name,level')->order('id asc')->select();

        //按级拆分
        $list_1 = [];
        $list_2 = [];
        $list_3 = [];
        foreach($list as $key => $value){
            if($value['level'] == 1){
                $list_1[] = $value;
            }
            if($value['level'] == 2){
                $list_2[] = $value;
            }
            if($value['level'] == 3){
                $list_3[] = $value;
            }
        }

        //三级并到市级
        foreach($list_2 as $k2 => $v2){
            foreach($list_3 as $k3 => $v3){
                if($v2['id'] == $v3['pid']){
                    $list_2[$k2]['child'][] = $v3;
                }
            }
        }

        //市级并到省级
        foreach($list_1 as $k1 => $v1){
            foreach($list_2 as $k2 => $v2){
                if($v1['id'] == $v2['pid']){
                    $list_1[$k1]['child'][] = $v2;
                }
            }
        }

        $this->success('success',$list_1);

    }

}
