<?php

/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace home\models;

use Yii;
use home\models\Tag;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "qc_tag_link".
 * 
 * <简述>
 *
 * @property integer $link_id  (关联表ID )
 * @property integer $tag_id  (关联tag集，关联表qc_tag)
 * @property string $link_type  (关联类型 表名)
 *
 * @author <Author> http://blog.u-bo.com
 * @since 0.1
 */
class TagLink extends ActiveRecord {

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%tag_link}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['link_id', 'tag_id', 'link_type'], 'required'],
            [['link_id', 'tag_id'], 'integer'],
            [['link_type'], 'string', 'max' => 20]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'link_id' => '关联id',
            'tag_id' => '标签id',
            'link_type' => '关联类型',
        ];
    }

    /**
     * 插入标签关联表
     * 
     * @param type $tags
     * @param type $linkId
     * @param type $linkType
     * @return boolean
     */
    public static function insertTagLink($tags, $linkId, $linkType) {
        $tagIds = explode(",", $tags);
        foreach ($tagIds as $tagId) {
            $list = static::find()->where(['link_id' => $linkId, 'tag_id' => $tagId, 'link_type' => $linkType])->one();
            if (empty($list)) {
                $data = new TagLink();
                $data->link_id = $linkId;
                if (empty($tagId)) {
                    return FALSE;
                } else {
                    $data->tag_id = $tagId;
                    $data->link_type = $linkType;
                    $data->save();
                }
            }
        }
    }

    public static function selectNames($linkId, $linkType) {
        $tag_ids = static::find()
                ->select('tag_id')
                ->where(['link_id' => $linkId, 'link_type' => $linkType])
                ->asArray()
                ->column();
        $tag_names = Tag::find()
                ->select('name')
                ->where(['in','tag_id', $tag_ids])
                ->asArray()
                ->column();
        $tags=  implode(',', $tag_names);
        return $tags;
    }

    /**
     * 删除标签关联表
     */
    public static function deleteTagLink($linkId, $linkType) {
         $taglink = static::findAll(['link_id' => $linkId,'link_type'=>$linkType]);
         foreach ($taglink as $tag) {
             $tag->delete();
         }
         
    }

}
