<?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 => '否',
    ];

    // 是否医保药品[0=否,1=是]
    const SI_TRUE = 0;

    const SI_FALSE = 1;

    // 是否医保药品-文字映射
    const SI_MAP = [
        self::RX_TRUE => '是',
        self::RX_FALSE => '否',
    ];

    // 是否进口药[0=否,1=是]
    const FOREIGN_TRUE = 0;

    const FOREIGN_FALSE = 1;

    // 是否进口药-文字映射
    const FOREIGN_MAP = [
        self::FOREIGN_TRUE => '是',
        self::FOREIGN_FALSE => '否',
    ];

    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value;
        $pinyin = new Pinyin();
        $abbr = $pinyin->abbr($value)->join(''); // 获取拼音首字母
        // echo $abbr;exit;
        $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();
    }
}
