<?php
/**
 * ===========================================================================
 * Veitool 快捷开发框架系统
 * Author: Niaho 26843818@qq.com
 * Copyright (c)2019-2025 www.veitool.com All rights reserved.
 * Licensed: 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
 * ---------------------------------------------------------------------------
 */

namespace app\model;

use app\api\service\UtilService;
use \app\model\CertCategory;
use app\model\system\SystemUploadFile;
use think\facade\Db;
use think\Model;

/**
 * 课程模型
 */
class Cert extends Model
{


    public function getCreatetimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }
    public function getStarttimetxtAttr($value,$data)
    {
        return date('Y-m-d', $data['start_time']);
    }
    public function getEndtimetxtAttr($value,$data)
    {
        return date('Y-m-d', $data['end_time']);
    }

    public function getThumbpathAttr($value, $data)
    {
        return get_upload_file($data['thumb_id']);
    }

    public function setStartTimeAttr($value)
    {

        return strtotime($value);
    }

    public function setEndTimeAttr($value)
    {
        return strtotime($value);
    }

    public function certcatedata()
    {
        return $this->hasOne(CertCategory::class, 'id', 'cate_id')
            ->field('id,title');
    }

    /**分类下的项目列表
     * @param $category_id
     * @param $page
     * @param $pageSize
     * @param $type 1 普通列表 2即将开始
     * @return array|\think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCertList($category_id,$page,$pageSize,$type)
    {
        $where = ['is_sell' => 1, 'is_del' => 0];
        if ($category_id) {
            $where['cate_id'] = $category_id;
        }

        $query = self::where($where);

        if ($type == 2) {
            $currentTime = time();
            $query->where('start_time', '<=', $currentTime)
                ->where('end_time', '>=', $currentTime);

            $query->order('end_time','asc');

        }else{
            $query->order('createtime','desc');
        }

        $list = $query->field('id,thumb_id,title,createtime,description,shrq,fzjg,price,tag_ids,start_time,end_time')
            ->paginate([
                'page' => $page,
                'list_rows' => $pageSize
            ]);

        if ($list->isEmpty() || $type==2) {
            return $list;
        }

        $list = UtilService::listWithTags($list,CertTag::class,'tag_ids');

        return $list;

    }








}