<?php

namespace app\model;

use think\Model;

class Regions extends Model
{
    /**
     * 根据code或parent_code获取省市区
     *
     * @param $code
     * @param string $parent_code
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getRegions($code, $parent_code = '', $type = 1){
        if ($code) {
            $where = 'code = '.$code;
        } elseif ($parent_code) {
            $where = 'parentCode = '.$parent_code;
        } else {
            $type = $type ? $type:1;
            $where = 'type = '.$type;
        }
        $fields = 'code,parentCode,name';

        if ($code) {
            $data = $this->field($fields)->where($where)->find();
            $data = $data->getData();
        } else {
            $data = $this->field($fields)->where($where)->select();
        }

        return $data;
    }

    /**
     * 根据省市区名字，查找对应的code
     *
     * @param $province
     * @param string $city
     * @param string $disc
     * @return mixed
     */
    public function getRegionsCodeByName($province, $city = '', $disc = '') {
        if ($province) {
            $result['province_code'] = $this->where('parentCode',100000)
                ->where('name','LIKE',$province.'%')->value('code');

            if ($result['province_code'] && $city) {

                $result['city_code'] = $this->where('parentCode',$result['province_code'])
                    ->where('name','LIKE',$city.'%')->value('code');
                if ($disc) {
                    $result['disc_code'] = $this->where('parentCode',$result['city_code'])
                        ->where('name','LIKE',$disc.'%')->value('code');
                }
            }
        }

        return $result;
    }
}
