<?php

namespace app\admin\model\cases;

use app\admin\model\CategoryLangs;
use app\common\model\Category;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\Model;
use traits\model\SoftDelete;

class Cases extends Model
{

    use SoftDelete;


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

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

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text'
    ];


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


    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }


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


    public static function validWhere($alias = '')
    {
        $str = '';
        if ($alias) {
            $str = $alias . '.';
        }
        return self::where($str . 'status', '1')->where($str . 'showswitch', 1);
    }

    /**
     * @param $where
     * @return array
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getValidArticleList($where)
    {
        $model = self::validWhere();
        if (isset($where['title']) && $where['title'] != '') {
            $ids = CasesLangs::where('title|synopsis', 'like', "%{$where['title']}%")->column('cases_id');
            $ids2 = self::where('title|synopsis', 'like', "%{$where['title']}%")->column('id');
            $all_ids = array_merge($ids, $ids2);
            $model->where('id', 'in', $all_ids);
        }
        if (isset($where['category_id']) && $where['category_id'] != '') {
            $model->where('find_in_set(' . $where['category_id'] . ',category_ids)');
        }
        $count = $model->count();
        $model = self::validWhere();
        if (isset($where['title']) && $where['title'] != '') {
            $ids = CasesLangs::where('title|synopsis', 'like', "%{$where['title']}%")->column('cases_id');
            $ids2 = self::where('title|synopsis', 'like', "%{$where['title']}%")->column('id');
            $all_ids = array_merge($ids, $ids2);
            $model->where('id', 'in', $all_ids);
        }
        if (isset($where['category_id']) && $where['category_id'] != '') {
            $model->where('find_in_set(' . $where['category_id'] . ',category_ids)');
        }
        $model = $model->order('weigh', 'desc')
            ->field('id,title,coverimage,category_ids,visit,synopsis,author,createtime,updatetime');
        $list = $model->page((int)($where['page'] ?? 1), (int)($where['limit'] ?? 10))
            ->select();
        //var_dump(self::getLastSql());
        foreach ($list as &$item) {
            $cate = function ($item) use ($where) {
                $cates = Category::where('id', 'in', $item['category_ids'])->column('id');
                $cate_item = [];
                foreach ($cates as $v) {
                    $cate = Category::where('id', $v)->value('name');
                    if (isset($where['lang']) && $where['lang']) {
                        $info = CategoryLangs::where('category_id', $v)->where('langlist', $where['lang'])->find();
                        if ($info) {
                            $cate = $info['name'];
                        }
                    }
                    $cate_item[] = $cate;
                }
                $item['cate'] = $cate_item;
                if (isset($where['lang']) && $where['lang']) {
                    $info = CasesLangs::where('cases_id', $item['id'])->where('langlist', $where['lang'])->find();
                    if ($info) {
                        $item['title'] = $info['title'];
                        $item['synopsis'] = $info['synopsis'];
                        $item['content'] = $info['content'];
                    }
                }
            };
            $cate($item);
        }
        return compact('list', 'count');
    }

    /**
     * @param $id
     * @param string $lang
     * @param bool $add_visit
     * @return array|false|\PDOStatement|string|Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getValidArticle($id, $lang = '', $add_visit = false)
    {
        $model = self::validWhere();
        $info = $model->where('id', $id)->find();
        if ($info && $add_visit) {
            $info->hidden(['showswitch', 'weigh', 'status', 'admin_id', 'deletetime']);
            $info['visit'] = $info['visit'] + 1;
            $info->save();
            $cates = Category::where('id', 'in', $info['category_ids'])->column('id');
            $info_cate = [];
            foreach ($cates as $v) {
                $cate = Category::where('id', $v)->value('name');
                if ($lang) {
                    $lang_info = CategoryLangs::where('category_id', $v)->where('langlist', $lang)->find();
                    if ($lang_info) {
                        $cate = $lang_info['name'];
                    }
                }
                $info_cate[] = $cate;
            }
            $info['cate'] = $info_cate;
            if ($lang) {
                $lang_info = CasesLangs::where('cases_id', $info['id'])->where('langlist', $lang)->find();
                if ($lang_info) {
                    $info['title'] = $lang_info['title'];
                    $info['synopsis'] = $lang_info['synopsis'];
                    $info['content'] = $lang_info['content'];
                }
            }
        }
        return $info;
    }

}
