<template>
    <div class="container" style="padding: 30px">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            label-width="68px"
            style="display: flex; margin-left: 5px"
        >
            <div style="margin-top: 5px; margin-bottom: 20px; margin-right: 5px">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="option({}, 'add')"
                    >新增课程</el-button
                >
            </div>
            <el-form-item label="课程" prop="courseId">
                <el-input v-model="queryParams.courseName"></el-input>
            </el-form-item>
            <el-form-item label="班级名称" prop="courseId">
                <el-input v-model="queryParams.className"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="courseList">
            <el-table-column label="序号" align="center" type="index" />
            <el-table-column label="所属班级" align="center" prop="className" />
            <el-table-column label="课程名称" align="center" prop="courseName" />
            <el-table-column label="任课老师" align="center" prop="instructor" />
            <el-table-column label="上课时间" align="center" prop="courseTime" />
            <el-table-column label="课程资料" align="center">
                <template slot-scope="scope">
                    <div
                        v-for="name in scope.row.attachments"
                        :key="name.fileId"
                        @click="downLoadSource(name)"
                        class="sourceItem"
                    >
                        {{ name.fileName }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="签到情况" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="option(scope.row, 'siginList')">{{
                        scope.row.signIn
                    }}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="option(scope.row, 'motify')">修改</el-button>
                    <el-button size="mini" type="text" @click="option(scope.row, 'delete')">删除</el-button>
                    <el-button size="mini" type="text" @click="option(scope.row, 'signIn')">签到</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <el-dialog
            class="diaform"
            :title="title"
            :visible.sync="visibleopen"
            :close-on-click-modal="false"
            append-to-body
            width="700px"
            @open="openDia"
            @close="closeDia"
        >
            <div v-if="optionType == 'signIn'">
                <vueQr :signInInfo="JSON.stringify(signInInfo)"></vueQr>
            </div>

            <el-form v-else :model="courseForm" :rules="rules" ref="form" label-width="150px" text-align:center>
                <el-form-item label="所属班级" prop="classId">
                    <el-select v-model="courseForm.classId" placeholder="请选择班级" clearable>
                        <el-option
                            v-for="item in classList"
                            :key="item.trainClassId"
                            :label="item.trainClassName"
                            :value="item.trainClassId"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="课程名称" prop="courseName">
                    <el-input class="courseName" v-model="courseForm.courseName"></el-input>
                </el-form-item>

                <el-form-item label="课堂老师" prop="instructor">
                    <el-select v-model="courseForm.instructor" placeholder="请选择老师" clearable>
                        <el-option
                            v-for="item in teacherList"
                            :key="item.talent_id"
                            :label="item.name"
                            :value="item.name"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上课时间" prop="courseTime">
                    <el-date-picker
                        v-model="courseForm.courseTime"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期时间"
                    >
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="课程资料" prop="attachments">
                    <div>
                        <fileUpload
                            ref="fileUpload"
                            v-model="courseForm.attachments"
                            listtype="picture-card"
                            :fileType="['rar']"
                            class="widthFix"
                            fileName="publicize"
                            :limit="3"
                        />
                    </div>
                </el-form-item>

                <el-form-item style="margin-top: 80px; text-align: center; margin-left: -150px">
                    <el-button
                        type="primary"
                        style="width: 135px; font-size: 16px; height: 39px; line-height: 11px"
                        @click="submitto('confirm')"
                        >确认</el-button
                    >
                    <el-button
                        style="width: 135px; font-size: 16px; height: 39px; line-height: 11px; margin-left: 30px"
                        @click="closeDia"
                        >取消</el-button
                    >
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import {
    getCourseList,
    addCourseItem,
    putCourseItem,
    delCourse,
    listTeacherAll,
    getClassList,
} from '@/api/trainService/index'
import fileUpload from '@/components/FileUpload/index.vue'
import { encodeChinese } from '@/utils/encodeChinese'
import vueQr from '@/components/vueQr/index.vue'
import { deepClone } from '@/utils'
const titleMap = {
    motify: '修改',
    delete: '删除',
    signIn: '签到码',
    add: '新增',
    siginList: '签到情况',
    attendance: '考勤',
}
const courseRule = {
    courseName: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
    classId: [{ required: true, message: '请选择班级', trigger: 'change' }],
    instructor: [{ required: true, message: '请选择任课老师', trigger: 'change' }],
    courseTime: [{ required: true, trigger: 'change', message: '请输入上课时间' }],
}
export default {
    components: { fileUpload, vueQr },
    data() {
        return {
            imgAction: process.env.VUE_APP_BASE_API + '/upload',
            loading: false,
            id: '',
            currentCourse: {},
            optionType: '',
            // 传递给二维码的信息
            signInInfo: {},
            courseList: [
                {
                    courseId: '',
                    className: '',
                    courseName: '',
                    courseTime: '',
                    instructor: '',
                    signIn: '',
                    attachments: [],
                },
            ],
            // 总条数
            total: 0,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                courseName: '',
                className: '',
            },
            courseForm: {
                classId: '',
                courseName: '',
                instructor: '',
                attachments: [],
                courseTime: '',
            },
            // 班级下拉框数据
            classList: [],
            // 教师下拉框数据
            teacherList: [],
            title: '',
            visibleopen: false,
            rules: courseRule,
        }
    },
    methods: {
        async getList() {
            const res = await getCourseList(this.queryParams)
            this.total = res.total
            this.courseList = res.rows
        },
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                courseName: '',
                className: '',
            }
            this.getList()
        },
        downLoadSource(params) {
            const url = params.filePath
            if (!url) {
                return
            }
            downloadHttp(url)
        },
        async option(row, type) {
            this.optionType = type
            this.currentCourse = row
            this.title = titleMap[type]
            switch (type) {
                case 'motify':
                    this.courseForm = deepClone(row)
                    this.initDialog()
                    break
                case 'delete':
                    this.deleteRow(row)
                    return
                case 'add':
                    this.initDialog()
                    break
                case 'signIn':
                    this.generateSignIn(row)
                    break
                case 'siginList':
                    // this.id = row.courseId
                    this.$router.push({
                        path: '/signInInfoList',
                        query: {
                            name: row.className,
                            id: row.courseId,
                        },
                    })
                    return
                default:
                    break
            }
            this.visibleopen = true
        },
        // 提交
        submitto() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    this.submit()
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        async submit() {
            const data = deepClone(this.courseForm)
            if (this.courseForm.courseId) {
                const res = await putCourseItem(data)
                res.code == 200 && this.$message.success('修改成功')
            } else {
                const res = await addCourseItem(data)
                res.code == 200 && this.$message.success('新增成功')
            }
            this.closeDia()
            this.getList()
        },
        // dialog init
        async initDialog() {
            const classRes = await getClassList()
            const teacherRes = await listTeacherAll()
            this.teacherList = teacherRes
            this.classList = classRes.data
        },
        openDia() {
            if (this.optionType === 'motify') {
                this.$refs.fileUpload?.fileInit(this.courseForm.attachments)
            }
        },
        // 关闭
        closeDia() {
            this.$refs['form']?.resetFields()
            Object.keys(this.courseForm).forEach((item) => {
                if (Array.isArray(this.courseForm[item])) {
                    this.courseForm[item] = []
                } else {
                    this.courseForm[item] = ''
                }
            })
            this.$refs.fileUpload?.reset()
            this.visibleopen = false
        },
        // 生成二维码信息
        generateSignIn(row) {
            this.signInInfo['courseId'] = row.courseId
            this.signInInfo['className'] = encodeChinese(row.className)
            this.signInInfo['courseName'] = encodeChinese(row.courseName)
            this.title = '签到码'
            this.visibleopen = true
        },
        /**
         * 删除签到信息
         */
        deleteRow(row) {
            this.$confirm('是否确认删除课程', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(function () {
                    return delCourse(row.courseId)
                })
                .then(() => {
                    this.getList()
                    this.$message.success('删除成功')
                })
        },
    },

    created() {
        this.getList()
    },
}
</script>

<style lang="scss">
.courseName {
    width: 220px;
}
.sourceItem {
    color: #1890ff;
    cursor: pointer;
    text-decoration: underline;
}
.sourceItem:hover {
    color: #0e4272;
    cursor: pointer;
    text-decoration: underline;
}
</style>
