<?php

namespace DAO\Order;
use Our\ApiConst;
use Our\ArrayConst;
use Our\DbNameConst;
use Our\NameConst;


/**
 * 用户数据层
 */
class DAddressModel extends \DAO\AbstractModel {

    private $addressRedisService;

    private $myAddressPrefix = 'address_id';


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

    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'address_id';

    public function init(){
        $this->addressRedisService = \Redis\Db8\AddressRedisModel::getInstance();
    }

    /**
     * 根据按照地址ID进行查找单个地址
     *
     * @param int $userId
     * @return array
     */
    public function find($addressId) {
        $redis = \Redis\Db8\AddressRedisModel::getInstance();
        $address  = $this->addressRedisService->find($addressId);
        if (!$address) {
            $address  = $this->db->from($this->_tableName)->where(array('address_id'=>$addressId))->fetchOne();
            if ($address) {
                $this->addressRedisService->update($addressId, $address);
            }
        }
        return $address;
    }
    /**
     * 获取单条数据
     * @param $where
     * @return array
     */
    public function getOneByWhereWithField($where,$field='*'){
        $this->setDb($this->dbName);
        $address = $this->db->from($this->_tableName)->select($field)->where($where)->fetchOne();
        return $address;
    }

    public function getAddressByAddressId($addressId,$field='*'){
        $this->setDb($this->dbName);
        $where['address_id']=$addressId;
        $address=$this->getOneByWhereWithField($where,$field);
        return $address;
    }
   //获得店铺默认地址
    public function getAddressByStoreId($storeId,$field='*'){
        $this->setDb($this->dbName);
        $where['store_id']=$storeId;
        $where['is_default']=ApiConst::one;
        $address=$this->getOneByWhereWithField($where,$field);
        return $address;
    }

    public function findByWhereWithColumns($where,$columns){
        if($where['address_id']){
            $address = $this->find($where['address_id']);
            if($where['member_id']&&$address){
                if($where['member_id']==$address['member_id']){
                    $newAddress = array();
                    foreach($address as $key=>$value){
                        if(in_array($key,$columns)){
                            $newAddress[$key] = $value;
                        }
                    }
                    return $newAddress;
                }
                return false;
            }
        }
        $address  = $this->getOneByWhereWithField($where,$columns);
        return $address;
    }

    public function findByWhere($where){
        $this->setDb($this->dbName);
        $daddress  = $this->db->from($this->_tableName)->where($where)->fetchOne();
        return $daddress;
    }

    public function selectByMemberId($member_id,$column=array('*'),$order = array('is_default'=>'desc','address_id'=>'desc')){
        $this->setDb($this->dbName);
        $where['member_id']=$member_id;
        $addressKey = $this->myAddressPrefix.$member_id;
        $addresses = $this->addressRedisService->get($addressKey);
        if(!$addresses){
            $this->db->select($column)->from($this->_tableName)->where($where);
            if($order){
                foreach($order as $key=>$value){
                    $this->db->order($key,$value);
                }
            }
            $addresses = $this->db->fetchAll();
            //$addresses = $this->addressMysql->fetchAll($column,$where,$order);
            $this->addressRedisService->set($addressKey,$addresses);
        }
        return $addresses;
    }

    public function selectByWhere($where,$columns = '*',$order = array('is_default'=> 'desc','address_id' => 'desc'),$limit=0){
        $this->setDb($this->dbName);
        $this->db->select($columns)->from($this->_tableName)->where($where);
        if($order){
            foreach($order as $key=>$value){
                $this->db->order($key,$value);
            }
        }
        if($limit>0){
            $this->db->limit($limit);
        }
        $addresses = $this->db->fetchAll();
        return $addresses;
    }

    //对主库进行操作
    public function updateBySql($sql){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $res=$this->db->update($this->_tableName)->query($sql);
        return $res;
    }

    public function insert($data){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $result = $this->db->insert($this->_tableName)->rows($data)->execute();

        if($result){
            $memberId = $data['member_id'];
            $addressKey = $this->myAddressPrefix.$memberId;
            $this->addressRedisService->del($addressKey);
        }
        return $result ;
    }

    public function update($data,$where){

        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $result=$this->db->update($this->_tableName)->rows($data)->where($where)->execute();
        if($result){
            $memberId = $data['member_id'];
            $addressKey = $this->myAddressPrefix.$memberId;
            $this->addressRedisService->del($addressKey);
        }
        return $result;
    }

    public function del($where){
        $this->setDb(\Our\DbNameConst::masterDBConnectName);
        $result  = $this->db->delete($this->_tableName)->where($where)->execute();
        return $result;
    }
    /**
     * 类实例
     *
     * @var \DAO\UserModel
     */
    private static $_instance = null;

    /**
     * 获取类实例
     *
     * @return \DAO\UserModel
     */

    /**
     * 单例模式获取类实例
     *
     */
    public static function getInstance($dbName=DbNameConst::salveDBConnectName)
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self($dbName);
        }

        return self::$_instance;
    }


    /**
     * 验证地址参数
     */
    public function getValidAddress($where){
        if(!$where['cityCode']){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyCityCode);
        }
        if(!($where['lng']&&$where['lat'])){
            \Error\ErrorModel::throwException(\Error\CodeConfigModel::emptyLatLng);
        }
    }

    public function getDefaultAddress(){
        return ArrayConst::defaultAddress;
    }

}
