<?php
/**
 * 地区数据模型(中国)
 * Created by PhpStorm.
 * User: QianNiao-C
 * Date: 2019/10/26
 * Time: 10:07
 */

namespace JinDouYun\Model\SysAreaChina;


use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Cache\SysAreaChinaCache;
use JinDouYun\Dao\SysAreaChina\DSysAreaChina;

class MSysAreaChina
{
    private $objDSysAreaChina;

    /**@var array 省市区 */
    private static $depth = [
        'province' => 1, //省份
        'city'     => 2, //市
        'area'     => 3, //区
    ];

    public function __construct()
    {
        $this->objDSysAreaChina = new DSysAreaChina('default');
    }

    /**
     * 获取所有省
     * @return ResultWrapper
     */
    public function getAllProvince()
    {
        $dbResult = $this->objDSysAreaChina->select(['depth' => self::$depth['province']], '*');

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDSysAreaChina->error(), ErrorCode::$dberror);
        }

        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取指定省下的所有市
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getAllCityByProvinceCode($selectParams)
    {

        $selectParams['depth'] = self::$depth['city'];
        $dbResult = $this->objDSysAreaChina->select($selectParams, '*');

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDSysAreaChina->error(), ErrorCode::$dberror);
        }

        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取指定市下的所有区
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getAllAreaByCityCode($selectParams)
    {

        $selectParams['depth'] = self::$depth['area'];
        $dbResult = $this->objDSysAreaChina->select($selectParams, '*');

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDSysAreaChina->error(), ErrorCode::$dberror);
        }

        return ResultWrapper::success($dbResult);
    }

    /**
     * 通过code=>名称
     * @param $params
     * @return array
     */
    public function getNameByCode($params)
    {
        $objSysAreaChinaCache = new SysAreaChinaCache();
        $allNameData = [];
        $notCacheCodes = [];
        foreach ($params as $k => $v) {
            $result = $this->objDSysAreaChina->get(['code'=>$v], 'name,code');
            if(empty($result)){
                $allNameData[$v] =  '';
                $notCacheCodes[] = $v;
            }else{
                $allNameData[$v] = $result['name'];
            }
        }

        $notCacheCodes = array_filter($notCacheCodes);
        // 如果缓存取不出来，走数据库
        if(!empty($notCacheCodes)){
            $dbResult = $this->objDSysAreaChina->select(['code'=>$notCacheCodes], 'name,code');
            if ($dbResult === false) {
                return $allNameData;
            }

            if(!empty($dbResult)){
                foreach ($dbResult as $key => $value){
                    $allNameData[$value['code']] = $value['name'];
                    $objSysAreaChinaCache->cacheCodeRelationName($value['name'], $value['code']);
                }
            }
        }

        return $allNameData;
    }


    /********************************************通过地区名称获取code******************************************/
    /**
     * @param $params
     * @return ResultWrapper
     */
    public function getCodeByName($params)
    {
        //参数为省市区名称
        $data['provinceName'] = isset($params['provinceName']) ? $params['provinceName'] : false; //省
        $data['cityName'] = isset($params['cityName']) ? $params['cityName'] : false;     //市
        $data['districtName'] = isset($params['districtName']) ? $params['districtName'] : false; //区
        $selectKey = '';
        $selectKeyArray = [];
        foreach($data as $key => $value){
            if($value === false){
                return ResultWrapper::fail('获取地区'.$key.'参数为空', ErrorCode::$paramError);
            }
            $selectKey = $selectKey.$value;
            $selectKeyArray[$key] = md5($selectKey);
        }
        if(empty($data)){
            return ResultWrapper::fail('获取地区参数为空', ErrorCode::$paramError);
        }
        $objSysAreaChinaCache = new SysAreaChinaCache();
        //获取缓存
        $returnData = [];
        $emptyData = [];
        foreach($data as $key => $value){
            $cacheResult = $objSysAreaChinaCache->getCache($selectKeyArray[$key]);
            if($cacheResult){
                $returnData[strstr($key, 'Name', true).'Code'] = $cacheResult;
            }else{
                $emptyData[$key] = $value;
            }
        }
        if(count($returnData) == count($data)){
            return ResultWrapper::success($returnData);
        }
        //如果缓存没有
        //查询数据库
        $sql = 0;
        $returnData = [];
        foreach($data as $key => $value){
            $sonSql = !empty($sql) ? "(".$sql.")" : $sql;
            $sql = "select code from ".$this->objDSysAreaChina->get_Table()." where `name` = '".$value."' and pcode = ".$sonSql;
            //file_put_contents('/www/wwwroot/logs/apiqnys.liuniukj.com/MSysAreaChina_error.log', date('Y-m-d H:i:s') . '错误信息|sql错误 ：' . $sql . PHP_EOL, FILE_APPEND);
            $dbResult = $this->objDSysAreaChina->query($sql);
            if($dbResult === false){
                return ResultWrapper::fail($this->objDSysAreaChina->error(), ErrorCode::$paramError);
            }
            if(!empty($dbResult)){
                $areaData = array_shift($dbResult);
                $returnData[strstr($key, 'Name', true).'Code'] = $areaData['code'];

                if(!empty($emptyData) && isset($emptyData[$key])){
                    //缓存地区
                    $result = $objSysAreaChinaCache->setCache($selectKeyArray[$key], $areaData['code']);
                    if(!$result){
                        return ResultWrapper::fail('缓存失败', ErrorCode::$paramError);
                    }
                }
            }else{
                //这里都是匹配不到的省市区(todo)
                $objSysAreaChinaCache->setNotArea($value);
                $returnData[strstr($key, 'Name', true).'Code'] = 0;
            }
        }
        if(count($returnData) != count($data)){
            return ResultWrapper::fail('地区不存在', ErrorCode::$paramError);
        }
        return ResultWrapper::success($returnData);
    }

}