<?php

namespace app\controller\api;

use app\repository\DictionaryRepository;
use think\facade\Db;
use app\model\Area as AreaModel;
/**
 * Area
 *
 * Class Business
 * @package app\controller\api
 */
class Area extends Base
{
    protected $noNeedLogin = [
        'index',"getProvinceDictionaryCity"
    ];

    /**
     * 根据上级行政代码 获取下级
     * */
    public function index()
    {
        $pcode = input("areaId/d",86);
        $filter = input("filter",false);
        return  json(AreaModel::getByPCode($pcode,$filter));
    }

    /**
     * 获取
     * */
    public function getProvinceDictionaryCity()
    {
        $province = AreaModel::getByPCode(86,true);
        $provinceCode = array_column($province->toArray(),null,"code");
        $provinceCodeArray = array_keys($provinceCode);

        $city       =  AreaModel::getByPCodes($provinceCodeArray,true);
        $city       = array_column($city,null,"code");


        $items = DictionaryRepository::getInstance()->getAllBusinessCircleList();
        $items->each(function ($item)use($city) {
            $areaText = '';
            if (!empty($item['province_text'])) {
                $areaText = $item['province_text'].'·';
            }
            if (!empty($item['city_text']) && $item['city_text'] != '市辖区') {
                $areaText .=  $item['city_text'].'·';
            }
            if (!empty($item['county_text'])) {
                $areaText .=  $item['county_text'];
            }

            $item['name_text'] = $item['name'];
            if (!empty($areaText)) {
                $item['name_text'] = $item['name'] . '「'.$areaText.'」';
            }
            return $item;
        });
        foreach ($items->toArray() as $item){
            if(isset($city[$item["city"]])){
                $city[$item["city"]]["children"][]=$item;
            }
        }

        foreach ($city as $item){
            if (isset($provinceCode[$item["pcode"]])){
                $provinceCode[$item["pcode"]]["children"][] =$item;
            }
        }
        return $this->json(0,"success",array_values($provinceCode));
    }
}