<?php namespace Phpcmf\Model\Block;

// 模型类

class Block extends \Phpcmf\Model
{

    // 格式化结果
    public function getValueAll($v) {

        foreach ($v as $i => $value) {
            $v[$i] = $this->getValue($value);
        }

        return $v;
    }

    public function getValue($value) {

        if (!$value['content']) {
            $value['i'] = 0;
            $value['value_0'] = '';
        } else {
            if (preg_match('/\{i-([0-9]+)\}:/U', $value['content'], $preg)) {
                $value['i'] = intval($preg[1]);
                $value['value_'.$value['i']] = str_replace((string)$preg[0], '', $value['content']);
                if ($value['i'] == 4) {
                    $value['value_'.$value['i']] = dr_string2array($value['value_'.$value['i']]);
                }
            } else {
                $value['i'] = 1;
                $value['value_1'] = $value['content'];
            }
        }

        return $value;
    }

    /**
     * 确保当前站点的资料块表存在（替代 Install_site.sql）
     * 表名：{dbprefix}{siteid}_block
     */
    protected function _ensure_site_table($siteid) {

        $siteid = intval($siteid);
        $table = $siteid.'_block';
        $full = $this->dbprefix($table);
        if ($this->is_table_exists($full)) {
            return $table;
        }

        $rt = \Phpcmf\Service::M('table')->create_table(
            $full,
            [
                'id' => 'smallint(5) unsigned NOT NULL AUTO_INCREMENT',
                'name' => 'varchar(100) NOT NULL COMMENT \'名称\'',
                'code' => 'varchar(100) NOT NULL COMMENT \'别名\'',
                'hide' => 'tinyint(1) unsigned NOT NULL COMMENT \'隐藏\'',
                'content' => 'text NOT NULL COMMENT \'内容\'',
            ],
            [
                'PRIMARY KEY (`id`)',
                'KEY `code` (`code`)',
            ],
            '资料块表'
        );
        if (!$rt['code']) {
            log_message('error', 'Block 站点表创建失败['.$full.']：'.($rt['msg'] ?? ''));
        }

        return $table;
    }

    // 缓存（按站点执行；缺表时自动建表）
    public function cache($siteid = SITE_ID) {

        $this->_ensure_site_table($siteid);
        $table = \Phpcmf\Service::M()->dbprefix($siteid.'_block');
        if (!\Phpcmf\Service::M()->is_field_exists($table, 'hide')) {
            \Phpcmf\Service::M('table')->add_field($table, 'hide', 'int(5)', 'DEFAULT 0', '');
        }
        $data = $this->table($siteid.'_block')->getAll();
        $cache = [];
        if ($data) {
            foreach ($data as $t) {
                if ($t['hide']) {
                    continue;
                }
                $t = $this->getValue($t);
                if (!$t['code']) {
                    // 填充默认code
                    $t['code'] = $t['id'];
                    $this->table($siteid.'_block')->update($t['id'], [
                        'code' => $t['id'],
                    ]);
                }
                switch (intval($t['i'])) {
                    case 0:
                        // 文本内容
                        $value = $t['value_0'];
                        break;
                    case 1:
                        // 文本内容
                        $value = $t['value_1'];
                        break;
                    case 2:
                        // 丰富文本
                        $value = htmlspecialchars_decode($t['value_2']);
                        break;
                    case 3:
                        // 单文件
                        $value = $t['value_3'];
                        break;
                    case 4:
                        // 多文件
                        $value = dr_string2array($t['value_4']);
                        break;
                }
                $cache[$t['code']] = [
                    1 => $t['name'],
                    0 => $value
                ];
            }
        }
        \Phpcmf\Service::L('cache')->set_file('block-'.$siteid, $cache);
        return;
    }

}