<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Overtrue\Pinyin\Pinyin;

class DrugModel extends Model
{
    use HasDateTimeFormatter;
    use SoftDeletes;

    protected $table = 'drug';

    // 是否处方药[0=不是,1=是]
    const RX_TRUE = 0;

    const RX_FALSE = 1;

    // 是否处方药-文字映射
    const RX_MAP = [
        self::RX_TRUE => '是',
        self::RX_FALSE => '否',
    ];

    public function setCodeAttribute($value)
    {
        $pinyin = new Pinyin();
        $abbr = $pinyin->abbr($this->name)->join(''); // 获取拼音首字母
        $this->attributes['code'] = strtoupper($abbr);
    }

    // 药品标签关联问诊问题，多对多
    public function tag()
    {
        $relatedModel = DrugTagModel::class; // 药品要关联的标签模型类名

        $pivotTable = 'drug_related_tag'; // 药品和标签关联中间表

        return $this->belongsToMany($relatedModel, $pivotTable, 'drug_id', 'tag_id')->withTimestamps();
    }
}
