<?php

namespace DAO;


class GoodsAttributeModel extends \DAO\AbstractModel {



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

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

    }
    public function getList($field,$where){
        $this->setDb();
        $data = $this->db->select($field)->from($this->_tableName)->where($where)->fetchAll();
        return $data;
    }
    public function option($field,$where){
        $data = $this->getList($field,$where);
        $productData = [];
        if(is_array($data) && !empty($data)){
            foreach ($data as $v){
                $productData[] = array('attrName'=>$v['attribute'],'attrValue'=>unserialize($v['attribute_value']));
            }
        }
        return $productData;
    }
    public function getAttrs($field,$where){
        $this->setDb();
        $where = $this->db->getSqlWhereByArray($where);
        $data = $this->db->select($field)->from($this->_tableName)->join('han_goods_attribute_value','han_goods_attribute_value.goods_attribute_id = han_goods_attribute.id','inner')->where($where)->fetchAll();
        return $this->attrOption($data);
    }
    public function getAttrsWithGoods($field,$where){
        $this->setDb();
        $where = $this->db->getSqlWhereByArray($where);
        $data = $this->db->select($field)->from($this->_tableName)->join('han_goods_common','han_goods_common.goods_commonid = han_goods_attribute.goods_commonid')->join('han_goods_attribute_value','han_goods_attribute_value.goods_attribute_id = han_goods_attribute.id','inner')->where($where)->fetchAll();
        return $this->attrOption($data);
    }
    public function attrOption($productData){
        $attrs = [];
        if($productData){
            foreach ($productData as $v){
                if(key_exists($v['attribute'],$attrs)){
                    array_push($attrs[$v['attribute']]['attrValue'],$v['attribute_value']);
                }else{
                    $attrs[$v['attribute']] = array('attrName'=>$v['attribute'],'attrValue'=>array($v['attribute_value']));
                }

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

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

        return self::$_instance;
    }

}
