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

namespace app\model;

use app\api\middleware\Auth;
use app\api\service\UtilService;
use app\model\project\User;
use app\model\system\SystemUploadFile;
use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;

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

    use SoftDelete;
    protected $deleteTime = 'deletetime';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    public function getShStatusTimeAttr($value)
    {
        if (!$value) return null;
        return date('Y-m-d H:i:s', $value);
    }

    public function getPutTimeAttr($value)
    {
        if (!$value) return null;
        return date('Y-m-d H:i:s', $value);
    }

    public function getCompleteTimeAttr($value)
    {
        if (!$value) return null;
        return date('Y-m-d H:i:s', $value);
    }

    public function getPutEndTimeAttr($value)
    {
        if (!$value) return null;
        return date('Y-m-d H:i:s', $value);
    }

    public function getCreatetimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }


    public function projectcatedata()
    {

        return $this->hasOne(ProjectCategory::class, 'id', 'cate_id')
            ->field('id,title');

    }

    //用户信息
    public function getuserdata()
    {
        return $this->belongsTo(User::class, 'user_id')
            ->field('username,mobile,id,headico');
    }

    public function getShStatusTextAttr($value, $data)
    {
        switch ($data['sh_status']) {
            case 1:
                $statustxt = '审核失败';
                break;
            case 2:
                $statustxt = '审核成功';
                break;
            default:
                $statustxt = '待审核';
        }

        return $statustxt;
    }

    public function getStatusTextAttr($value, $data)
    {
        switch ($data['status']) {
            case 1:
                $statustxt = '招募中';
                break;
            case 2:
                $statustxt = '进行中';
                break;
            case 3:
                $statustxt = '待验收';
                break;
            case 4:
                $statustxt = '已完成';
                break;
            case 5:
                $statustxt = '已取消';
                break;
            default:
                $statustxt = '等待审核';
        }

        return $statustxt;
    }

    public function getProjectList($category_id,$page,$pageSize,$type,$searchKeyWords = null)
    {

        $where = ['sh_status' => 2, 'status' => 1];
        $query = self::where($where);
        $query->where('put_end_time','>',time());


        if ($category_id) {
            $son_ids = ProjectCategory::where('pid', $category_id)->column('id');
            $query->whereIn('cate_id', array_merge([$category_id], $son_ids));
        }


        if ($searchKeyWords)
        {
            $query->where('title', 'like', '%' . $searchKeyWords . '%');
        }

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

        //热门项目
        if ($type == 3)
        {
            $query->where('is_hot',1);
        }
        $list = $query->field('id,sn,title,createtime,cate_id,yusuan,zhouqi,tag_ids,put_end_time,thumb')
            ->with(['thumb'])
            ->paginate([
                'page' => $page,
                'list_rows' => $pageSize
            ]);
        if ($list->isEmpty()) {
            return $list;
        }

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

       return $list;

    }

    // 6.20 两级分类查询
    public function getProjectListSecond($first_category_id, $second_category_id, $page, $pageSize, $type, $searchKeyWords = null)
    {
        // 基础查询条件
        $where = ['sh_status' => 2, 'status' => 1];
        $query = self::where($where);
        $query->where('put_end_time', '>', time());

        // 处理分类查询逻辑
        if ($second_category_id > 0) {
            // 情况1：只要二级分类有值，无论一级分类是什么，都精确查询该二级分类
            $query->where('cate_id', $second_category_id);
        } elseif ($first_category_id > 0) {
            // 情况2：只有一级分类有值，查询该一级分类及其所有子分类
            $son_ids = ProjectCategory::where('pid', $first_category_id)->column('id');

            $query->whereIn('cate_id', array_merge([$first_category_id], $son_ids));
        }
        // 如果一级分类为0，则不限制分类（查询全部）

        // 关键词搜索
        if ($searchKeyWords) {
            $query->where('title', 'like', '%' . $searchKeyWords . '%');
        }

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

        // 热门项目
        if ($type == 3) {
            $query->where('is_hot', 1);
        }

        $list = $query->field('id,sn,title,createtime,cate_id,yusuan,zhouqi,tag_ids,put_end_time,thumb,user_id')
            ->with(['thumb','getuserdata'=>['headico']])
            ->paginate([
                'page' => $page,
                'list_rows' => $pageSize
            ]);

        if ($list->isEmpty()) {
            return $list;
        }

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

        return $list;
    }

    //项目详情
    public function projectDetail($id, $userId)
    {
        $project = self::with(['getuserdata','projectcatedata','thumb'])
            ->field([
                '*',
                // 当 status=3 时，计算截止日期（put_time + zhouqi * 86400）
                'IF(
                    status IN (2, 3, 4) AND put_time IS NOT NULL AND zhouqi IS NOT NULL, 
                    FROM_UNIXTIME(put_time + zhouqi * 86400), 
                    NULL
                ) as deadline_date',
            ])
            ->find($id);
        if (!$project) {
            return [];
        }

        return array_merge($project->toArray(), [
            'is_put' => ProjectPut::where([
                'project_id' => $id,
                'user_id' => $userId
            ])->count(),
            'fileData' => $this->getValidFiles($project->file_id_str)
        ]);
    }

    protected function getValidFiles($fileIds)
    {
        if (empty($fileIds)) {
            return [];
        }

        return SystemUploadFile::whereIn('fileid', explode(',', $fileIds))
            ->where('isdel', 0)
            ->field('fileid,filename,filesize,fileurl,filetype,storage')
            ->select()
            ->toArray();
    }




    public function getFileListAttr($value, $data)
    {

        return get_upload_file($data['file_id_str'], 'list');
    }

    public function thumb()
    {
        return $this->hasOne(SystemUploadFile::class, 'fileid', 'thumb')
            ->where('isdel',0)
            ->field('fileid,filename,filesize,fileurl,filetype,storage');
    }

    public function put()
    {
        return $this->hasMany(ProjectPut::class, 'project_id', 'id');
    }


}