<?php
namespace app\apicom\model;

use think\Model;
use think\facade\Db;
use app\model\Field;

/**
 * 文档模型
 */
class Document extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'cms_document';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    
    /**
     * 获取文档列表
     * @param array $map 筛选条件
     * @param array $order 排序
     * @return mixed
     */
    public static function getList($map=[],$order='',$offset=20)
    {
        $data_list = self::view('cms_document d', true)
            ->view("cms_column c", ['name' => 'column_name'], 'c.id=d.cid', 'left')
            ->view("admin_user a", 'username', 'a.id=d.uid', 'left')
            ->where($map)
            ->order($order)
            ->paginate($offset, false, ['query' => request()->param()])
            ->each( function($item, $key){
                //$item->status_n = self::getStatusName($item->status);
            });
        return $data_list;
    }

    /**
     * 获取单篇文档
     * @param string $id 文档id
     * @param string $model 独立模型id
     * @param array $map 查询条件
     * @return mixed
     */
    public static function getOne($id)
    {
        $info = Db::view('cms_document d')
            ->view('cms_document_content c', 'content', 'd.id = c.aid')
            ->where(['d.id'=> $id,'d.status' => 1,'d.trash'  => 0])
            ->find();
        //print_r($info);exit;
        $host = sysConfig('app_url').'/uploads/images/';
        $info['content'] = isset($info['content']) ? str_replace('/uploads/images/',$host,$info['content']) : '';
        if (isset($info['tags'])) {
            $info['tags'] = explode(',', $info['tags']);
        }
        return $info['content'] ? $info : false;
    }

    /**
     * 新增或更新文档
     * @return bool
     */
    public function saveData()
    {
        $data = request()->post();
        $data['uid'] = UID;

        // 文档模型
        $model = Db::name('cms_model')->where('id', $data['model'])->find();

        if ($model['type'] != 2 && empty($data['summary']) && config('cms_config.summary') > 0) {
            $data['summary'] = mb_substr(strip_tags($data['content']), 0, config('cms_config.summary'), 'utf-8');
        }

        // 处理自定义属性
        if (isset($data['flag'])) {
            $data['flag'] = implode(',', $data['flag']);
        } else {
            $data['flag'] = '';
        }

        // 验证基础内容
        if ($data['title'] == '') {
            $this->error = '标题不能为空';
            return false;
        }

        // 处理特殊字段类型
        $fields = Field::where('model', $data['model'])->where('status', 1)->column('name,type');

        foreach ($fields as $name => $type) {
            if (!isset($data[$name])) {
                switch ($type) {
                    // 开关
                    case 'switch':
                        $data[$name] = 0;
                        break;
                    case 'checkbox':
                        $data[$name] = '';
                        break;
                }
            } else {
                // 如果值是数组则转换成字符串，适用于复选框等类型
                if (is_array($data[$name])) {
                    $data[$name] = implode(',', $data[$name]);
                }
                switch ($type) {
                    // 开关
                    case 'switch':
                        $data[$name] = 1;
                        break;
                    // 日期时间
                    case 'date':
                    case 'time':
                    case 'datetime':
                        $data[$name] = strtotime($data[$name]);
                        break;
                }
            }
        }

        if (empty($data['id'])) {
            if ($model['type'] == 2) {
                // 新增独立模型文档
                $data['create_time'] = request()->time();
                $data['update_time'] = request()->time();
                $insert_id = Db::table($model['table'])->insertGetId($data);
                if (false === $insert_id) {
                    $this->error = '新增失败';
                    return false;
                } else {
                    // 记录行为
                    action_log('document_add', $model['table'], $insert_id, UID, $data['title']);
                    return true;
                }
            } else {
                // 新增文档基础内容
                if ($document = self::create($data)) {
                    // 新增文档扩展内容
                    if ($model['table'] != '') {
                        $data['aid'] = $document['id'];
                        if (false === Db::table($model['table'])->insert($data)) {
                            // 删除已添加的基础内容
                            self::destroy($document['id']);
                            $this->error = '新增扩展内容出错';
                            return false;
                        }
                    }
                    // 记录行为
                    action_log('document_add', 'cms_document', $document['id'], UID, $document['title']);
                    return true;
                } else {
                    $this->error = '新增基础内容出错';
                    return false;
                }
            }
        } else {
            // 更新独立模型文档
            if ($model['type'] == 2) {
                // 新增独立模型文档
                $data['update_time'] = request()->time();
                if (false === Db::table($model['table'])->update($data)) {
                    $this->error = '编辑失败';
                    return false;
                } else {
                    // 记录行为
                    action_log('document_edit', $model['table'], $data['id'], UID, $data['title']);
                    return true;
                }
            } else {
                // 更新文档基础内容
                if (self::update($data)) {
                    // 更新文档扩展内容
                    $data['aid'] = $data['id'];
                    if (false !== Db::table($model['table'])->update($data)) {
                        // 记录行为
                        action_log('document_edit', 'cms_document', $data['id'], UID, $data['title']);
                        return true;
                    } else {
                        $this->error = '更新扩展内容出错';
                        return false;
                    }
                } else {
                    $this->error = '更新基础内容出错';
                    return false;
                }
            }
        }
    }
}