<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2020/2/4
 * Time: 12:47
 */

namespace app\common\model;

use think\Model;

class Config extends Model
{
    protected $autoWriteTimestamp = false;

    const STATUS_OPEN = 1;//开启
    const STATUS_CLOSE = 0;//关闭

    const TYPE_INPUT = 0;//输入型配置
    const TYPE_SELECT = 1;//多选
    const TYPE_RADIO = 2;//单选

    const TYPES = [
        self::TYPE_INPUT => '输入型配置',
        self::TYPE_SELECT => '多选配置',
        self::TYPE_RADIO => '单选配置',
    ];

    //value_text
    public function getValueTextAttr($value, $data)
    {
        if ($this->getData('type') == self::TYPE_INPUT) {
            return $this->value;
        } elseif ($this->getData('type') == self::TYPE_SELECT) {
            $count = (new ConfigOption())->where('pid', $this->id)->where('status', ConfigOption::STATUS_OPEN)->count();
            return $count . "个" . $data['name'];
        } elseif ($this->getData('type') == self::TYPE_RADIO) {
            return (new ConfigOption())->where('pid', $this->id)->where('single_status', ConfigOption::STATUS_OPEN)->column('name');
        } else {
            return '';
        }
    }

    //type_text
    public function getTypeTextAttr($value, $data)
    {
        return self::TYPES[$this->getData('type')];
    }

    //tab_text
    public function getTabTextAttr($value, $data)
    {
        if (!$this->tab) {
            return "";
        } else {
            return $this->tab->getData('name')??'';
        }
    }

    //image_open
    public function getImageOpenAttr($value, $data)
    {
        return $value == 1 ? true : false;
    }

    //image_label
    public function getImageLabelAttr($value, $data)
    {
        return $value ?: '配图';
    }

    //name_label
    public function getNameLabelAttr($value, $data)
    {
        return $value ?: '名称';
    }

    //value_label
    public function getValueLabelAttr($value, $data)
    {
        return $value ?: '配置值';
    }

    //desc_label
    public function getDescLabelAttr($value, $data)
    {
        return $value ?: '备注';
    }

    //如果remark是json格式，用此方法获取对象
    public function getJsonConfig()
    {
        $config = json_decode($this->remark, true);
        return is_array($config) ? $config : [];
    }

    //关联标签
    public function tab()
    {
        return $this->belongsTo('ConfigTab', 'tab_id');
    }
}
