<?php

namespace app\model;

use app\model\system\SystemUploadFile;
use think\Model;

class CourseUserWork extends Model
{
    // 设置完整表名
    protected $table = 'fj_course_user_work';

    // 自动时间戳（将createtime转换为时间戳自动管理）
    protected $autoWriteTimestamp = true;
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    /** 作业列表
     * @param $userId
     * @param $page
     * @param $pageSize
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function workList($userId, $page = 1, $pageSize = 10)
    {

        $status = request()->post('status');
        $map = [];
        if($status){
            $map['status'] = $status;
        }
        return self::where(['user_id' => $userId, 'is_del' => 0])
            ->where($map)
            ->with(['course', 'courseWork'])
            ->field('id,user_id,work_id,status,course_id,createtime')
            ->paginate([
                'page' => $page,
                'list_rows' => $pageSize
            ])
            ->toArray();
    }

    /**作业详情
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function workDetail($id)
    {
        $detail = self::where(['id' => $id, 'is_del' => 0])
            ->with(['course', 'courseWork'])
            ->field('id,user_id,work_id,status,course_id,createtime,attachment_ids,note')
            ->findOrEmpty();

        if ($detail->isEmpty()) {
            return [];
        }

        $detail = $detail->toArray();
        // 处理 courseWork 文件 课程作业附件
        if (!empty($detail['courseWork']['file_id_str'])) {
            $fileIds = is_string($detail['courseWork']['file_id_str'])
                ? explode(',', $detail['courseWork']['file_id_str'])
                : (array)$detail['courseWork']['file_id_str'];

            $detail['courseWork']['file'] = SystemUploadFile::whereIn('fileid', $fileIds)
                ->field('fileurl,fileid,filename,filetype')
                ->select()
                ->toArray();
        } else {
            $detail['courseWork']['file'] = [];
        }

        // 处理 attachment 文件 学生上传附件
        $attachmentIds = !empty($detail['attachment_ids'])
            ? (is_string($detail['attachment_ids']) ? explode(',', $detail['attachment_ids']) : (array)$detail['attachment_ids'])
            : [];
        $detail['attachment_file'] = !empty($attachmentIds)
            ? SystemUploadFile::whereIn('fileid', $attachmentIds)
                ->field('fileurl,fileid,filename,filetype,storage')
                ->select()
                ->toArray()
            : [];

        return $detail;
    }

    /**用户作业上传
     * @param $workId
     * @param $attachment_ids
     * @return CourseUserWork
     */
    public static function uploadWork($workId, $attachment_ids)
    {
        return self::where(['id' => $workId, 'status' => 0, 'is_del' => 0])
            ->update(['attachment_ids' => $attachment_ids, 'status' => 1]);
    }


    //关联作业
    public function courseWork()
    {
        return $this->hasOne(CourseWork::class, 'id', 'work_id')
//            ->append(['filelist'])
            ->where('is_del', 0)
            ->field('id,title,file_id_str,content');
    }

    //关联课程
    public function course()
    {
        return $this->hasOne(Course::class, 'id', 'course_id')->where('is_del', 0)->field('id,title');
    }

    //关联用户学校
    public function userprofile()
    {
        return $this->belongsTo(\app\model\project\User::class, 'user_id')->where('is_del', 0)->field('id,username,mobile,realname');
    }

    public function getFilelistAttr($value,$data)
    {
        return get_upload_file($data['attachment_ids'],'list');
    }


    public function getStatusTextAttr($value, $data)
    {
        switch ($data['status']) {
            case 1:
                $text = '未考核';
                break;
            case 2:
                $text = '已通过考核';
                break;
            case 3:
                $text = '未通过考核';
                break;
            default;
                $text = '未提交';
        }

        return $text;
    }
}