<?php

namespace app\admin\model\setting;

use app\admin\model\box\Box;
use think\Model;
use traits\model\SoftDelete;


class Banner extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'banner';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [
        'value_short',
        'place_text',
        'type_text',
        'status_text',
        'update_time_text'
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    public function getValueShortAttr($value, $data)
    {
        if (!empty($data['value'])) {

            if (!empty($data['type']) && 'box' == $data['type']) {
                // 查询盲盒名称
                return Box::where('id', $data['value'])->value('box_name');
            }

            $text = mb_substr(strip_tags($data['value']), 0, 50);
            return mb_strlen($text) >= 50 ? $text . '...' : $text;
        }
        return '';
    }

    public function getPlaceList()
    {
//        return ['index' => __('Place index'), 'other' => __('Place other')];
        return ['index' => __('Place index')];
    }

    public function getTypeList()
    {
        return ['box' => __('Type box'), 'link' => __('Type link'), 'word' => __('Type word')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Status normal'), 'hidden' => __('Status hidden')];
    }


    public function getPlaceTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['place']) ? $data['place'] : '');
        $list = $this->getPlaceList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
