<?php

namespace DAO;


use Redis\Db8\AddressRedisModel;

class AreaModel extends \DAO\AbstractModel {



    /**
     * 表名
     *
     * @var string
     */
    protected $_tableName = 'han_area';

    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'area_id';
    public function init(){

    }

    public function getOne($where,$field = \Our\NameConst::allField){
        $this->setDb($this->dbName);
        if(is_array($where)){
            $where = $this->db->getSqlWhereByArray($where);
        }
        return $this->db->select($field)->from($this->_tableName)->where($where)->fetchOne();
    }

    public function getOneFormCache($where,$field= \Our\NameConst::allField){
        \Our\RedisHelper::cachedFunction(\Redis\Db8\AddressRedisModel::getInstance(),array(&$this, 'getOne'),array($where,$field),\Our\ApiConst::oneDaySecond);
    }

    public function getOneById($areaId,$field){
        $this->setDb($this->dbName);
        return $this->db->select($field)->from($this->_tableName)->where(array('area_id'=>$areaId))->fetchOne();
    }

    public function getAll(){
        $this->setDb($this->dbName);
        $areaList =  $this->db->select(\Our\NameConst::allField)->from($this->_tableName)->fetchAll();
        $result = array();
        foreach($areaList as $area){
            $result[$area['area_parent_id']][] = $area;
        }
        return $result;
    }

    public function update($where, $data){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        return $this->db->update($this->_tableName)->where($where)->rows($data)->execute();
    }


    public function getList($limit){
        $this->setDb($this->dbName);
        $this->db->select(\Our\NameConst::allField)->from($this->_tableName);
        if($limit){
            $this->db->limit($limit[0],$limit[1]);
        }
        $areaList =  $this->db->fetchAll();
        return $areaList;
    }

    public function writeToFile(){
        $this->setDb($this->dbName);
        $where = array('area_deep'=>array('neq',3));
        $where= $this->db->getSqlWhereByArray($where);
        $areaList =  $this->db->select(\Our\NameConst::allField)->from($this->_tableName)->where($where)->order('area_deep','asc')->fetchAll();
        $where = array('area_deep'=>3);
        $areaSubList =  $this->db->select(\Our\NameConst::allField)->from($this->_tableName)->where($where)->limit(0,3000)->order('area_id','asc')->fetchAll();
        var_dump(count($areaSubList));
        $proInfoList = array();
        foreach($areaList as $area){
            if($area['area_deep']==1){
                $proInfoList[$area['area_id']]['area_name'] = $area['area_name'];
            }else{
                $city = array();
                $city['city_name'] = $area['area_name'];
                $city['city_id'] = $area['area_id'];
                $proInfoList[$area['area_parent_id']]['list'][] = $city;
            }
        }
        $newAreaList = array();
        foreach($areaSubList as $area){
            $newAreaList[$area['area_parent_id']][]= $area['area_name'];
        }
        $returnList = array();
        $proList = array();
        foreach($proInfoList as $proInfo){
            $return = array();
            $return['name'] = $proInfo['area_name'];
            $return['city'] = array();
            if($proInfo['list']){
                foreach($proInfo['list'] as $city){
                    $newCity= array();
                    $newCity['name'] = $city['city_name'];
                    $newCity['area'] = $newAreaList[$city['city_id']]?$newAreaList[$city['city_id']]:array();
                    var_dump($newCity);
                    array_push($return['city'],$newCity);
                }
            }
            $returnList[] = $return;
        }
        \Our\Log::getInstance()->write(json_encode($returnList),'/data/log/appcity');
        return $returnList;

    }

    public function getCityListWithoutCounty(){
        $addressRedis = AddressRedisModel::getInstance();
        $cityList = $addressRedis->find('cityListWithoutCounty');
        if($cityList){
            return $cityList;
        }
        $areaList = $this->getAllCityList(true);
        $addressRedis->update('allCityListWithoutCounty',$areaList);
        $cityListInitial = array();
        $cityInitialList = array();
        $cityPinyinList = array();
        foreach($areaList as $area){
            if(isset($area['initial'])&&$area['initial']&&!($cityInitialList&&in_array($area['initial'],$cityInitialList))){
                $cityInitialList[] = $area['initial'];
            }
            $cityListInitial[$area['initial']][] =$area['area_name'] ;
            $cityPinyinList[$area['initial']][] = array('name'=>$area['area_name'],'pinyin'=>$area['pinyin']);
        }
        $list = array();
        foreach($cityInitialList as $inital){
            $initalCity['initial'] = $inital;
            $initalCity['list'] = $cityListInitial[$inital];
            $initalCity['pinyinList'] = $cityPinyinList[$inital];
            $list[] = $initalCity;
        }
        $addressRedis->update('cityListWithoutCounty',$list);
        return $list;
    }

    public function getCityList(){
        $addressRedis = AddressRedisModel::getInstance();
        $cityList = $addressRedis->find('cityList');
        if($cityList){
            return $cityList;
        }
        $areaList = $this->getAllCityList();
        $addressRedis->update('allCityList',$areaList);
        $cityListInitial = array();
        $cityInitialList = array();
        foreach($areaList as $area){
            if(isset($area['initial'])&&$area['initial']&&!($cityInitialList&&in_array($area['initial'],$cityInitialList))){
                $cityInitialList[] = $area['initial'];
            }

            $cityListInitial[$area['initial']][] = $area['area_name'];
            $cityPinyinList[$area['initial']][] = array('name'=>$area['area_name'],'pinyin'=>$area['pinyin']);
        }
        $list = array();
        foreach($cityInitialList as $inital){
            $initalCity['initial'] = $inital;
            $initalCity['list'] = $cityListInitial[$inital];
            $initalCity['pinyinList'] = $cityPinyinList[$inital];
            $list[] = $initalCity;
         }
        $addressRedis->update('cityList',$list);
        return $list;
    }

    public function getAllCityList($withoutCounty=false){
        $this->setDb($this->dbName);
        $sql  = "  SELECT t1.area_name,t1.pinyin, LEFT(t1.pinyin,1) as initial FROM han_area t1 ";
        $sql .= "  where t1.is_city=1 ";
        if($withoutCounty){
            $sql .= " and t1.area_name not like '%县'";
        }
        $sql .= " ORDER BY t1.area_deep,t1.pinyin  ASC ";
        $area_list = $this->db->query($sql)->rows;
        return $area_list;

    }


    /**
     * 类实例
     *
     * @var \DAO\UserModel
     */
    private static $_instance = null;

    /**
     * 获取类实例
     *
     * @return \DAO\UserModel
     */
    public static function getInstance($dbName = \Our\DbNameConst::salveDBConnectName) {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self($dbName);
        }

        return self::$_instance;
    }

}
