<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>
                <!-- <el-button type="primary" icon="el-icon-plus" size="mini" @click="importCourse">导入课程</el-button> -->
                <!-- <buttonUpload v-if="courseForm.classId !== ''" style="margin-left: 10px;"><el-button type="primary" icon="el-icon-plus" size="mini" @click="uploadExcel">导入课程</el-button></buttonUpload> -->
                <!-- <buttonUpload  style="margin-left: 10px;"><el-button type="primary" icon="el-icon-plus" size="mini" @click="uploadExcel">导入课程</el-button></buttonUpload> -->
            </div>
            <el-form-item label="课程" prop="courseId">
                <el-input v-model="queryParams.courseName" clearable></el-input>
            </el-form-item>
            <el-form-item label="班级名称" prop="courseId">
                <el-input v-model="queryParams.className" clearable></el-input>
                <!-- <el-select v-model="queryParams.className" placeholder="选择班级" clearable>
                    <el-option v-for="item in classList" :key="item.trainClassId" :label="item.trainClassName" :value="item.trainClassName">
                    </el-option>
                </el-select> -->
            </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-tabs v-model="queryParams.classType" @tab-click="handleClick">
            <el-tab-pane v-for="(myClass, classIndex) in classMap" :key="classIndex" :label="myClass.type"
                :name="myClass.value">
            </el-tab-pane>
        </el-tabs>
        <el-table v-loading="loading" :data="courseList" ref="table">
            <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 v-if="queryParams.classType == 4" label="下课时间" align="center" prop="dateTime">
                <template slot-scope="scope">
                    <div>{{ scope.row.classType == 4 ? scope.row.dateTime : '' }}</div>
                </template>
            </el-table-column>
            <el-table-column v-if="queryParams.classType != 4" 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 v-if="queryParams.classType != 4" label="签到情况" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="option(scope.row, 'siginList')">{{
                        scope.row.classType == 4 ? '' : scope.row.signIn
                        }}</el-button>
                </template>
            </el-table-column>
            <el-table-column v-if="queryParams.classType != 3" label="布置作业" align="center">
                <template slot-scope="scope">
                    <el-button v-if="!scope.row.homework" size="mini" type="text"
                        @click="toAssignHomework(scope.row)">新增</el-button>
                    <el-button v-else size="mini" type="text" @click="toAssignHomework(scope.row)">修改</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <!-- <el-button size="mini" type="text" v-show="scope.row.classType != 3"
                        @click="toAssignHomework(scope.row)">布置作业</el-button> -->
                    <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" v-show="scope.row.classType != 4"
                        @click="option(scope.row, 'signIn')">签到</el-button>
                    <el-button v-show="scope.row.classType == 4" size="mini" type="text"
                        @click="option(scope.row, 'inCome')">收入管理</el-button>
                    <el-button v-show="scope.row.classType == 4" size="mini" type="text"
                        @click="option(scope.row, 'studentRows')">学习人数</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>

            <div v-else-if="optionType == 'inCome'">
                <el-table v-loading="loading" :data="inComeForm">
                    <el-table-column label="序号" align="center" type="index" />
                    <el-table-column label="付费时间" align="center" width="250px" prop="recordTime" />
                    <el-table-column label="付费金额" align="center" width="110px" prop="recordAmount" />
                    <el-table-column label="流水号" align="center" width="250px" prop="reqsn" />
                </el-table>
                <pagination v-show="total > 0" :total="inComeTotal" :page.sync="inComeParams.pageNum"
                    :limit.sync="inComeParams.pageSize" @pagination="inComeManage('')" />
            </div>
            <el-form v-else :model="courseForm" :rules="rules" ref="courseForm" label-width="150px" text-align:center>
                <el-form-item label="所属班级" prop="classId">
                    <div style="display: flex;">
                        <el-select v-model="courseForm.classId" filterable placeholder="请选择" @change="classChange">
                            <el-option v-for="item in classList" :key="item.trainClassId" :label="item.trainClassName"
                                :value="item.trainClassId">
                            </el-option>
                        </el-select>
                    </div>
                </el-form-item>

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

                <el-form-item label="课堂老师" prop="instructor" v-if="classType != 4">
                    <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="title" v-if="classType == 4">
                    <el-input class="courseName" v-model="courseForm.title" placeholder="请输入职称"></el-input>
                </el-form-item>

                <el-form-item label="授课老师" prop="instructor" v-if="classType == 4">
                    <el-autocomplete class="inline-input" v-model="courseForm.instructor"
                        :fetch-suggestions="querySearch" placeholder="请输入授课老师" @select="handleSelect">
                        <template slot-scope="{ item }">
                            <span class="addr">{{ item.name }}</span>
                        </template></el-autocomplete>
                </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"
                        @change="timeChange('courseTime')" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="下课时间" prop="dateTime" v-if="classType == 4">
                    <el-date-picker v-model="courseForm.dateTime" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                        @change="timeChange('dateTime')" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="授课内容" prop="courseContent" v-if="classType == 4">
                    <el-input v-model="courseForm.courseContent" placeholder="请输入授课内容" type="textarea"
                        :rows="2"></el-input>
                </el-form-item>

                <el-form-item label="授课链接" prop="url" v-if="classType == 4">
                    <el-input class="courseName" v-model="courseForm.url" placeholder="请输入授课链接"></el-input>
                </el-form-item>

                <el-form-item label="是否付费" prop="isPay" v-if="classType == 4">
                    <!-- <el-cascader v-model="courseForm.isPay" :options="payOptions"
                        @change="payHandleChange"></el-cascader> -->
                    <el-select v-model="courseForm.isPay" placeholder="请选择是否付费">
                        <el-option label="付费" value="1"></el-option>
                        <el-option label="免费" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="费用" prop="amount" v-if="classType == 4 && courseForm.isPay == 1">
                    <el-input v-model="courseForm.amount" type="number" placeholder="请输入费用"></el-input>
                </el-form-item>
                <el-form-item label="口令" prop="password" v-if="classType == 4 && courseForm.isPay == 1">
                    <el-input v-model="courseForm.password" type="number" placeholder="请输入口令"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark" v-if="classType == 4">
                    <el-input v-model="courseForm.remark" placeholder="请输入备注"></el-input>
                </el-form-item>


                <el-form-item label="课程资料" prop="attachments" v-if="classType != 4">
                    <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>
        <assignWork ref="assignWork" @subWork="subWork"></assignWork>
    </div>
</template>
<script>
import {
    getCourseList,
    addCourseItem,
    putCourseItem,
    delCourse,
    listTeacherAll,
    getClassList,
    getInComeInfo,
    assignHomeWork,
    updateHomeWork
} from '@/api/trainService/index'
import fileUpload from '@/components/FileUpload/index.vue'
import { encodeChinese } from '@/utils/encodeChinese'
import buttonUpload from '@/components/buttonUpload/index.vue'
import vueQr from '@/components/vueQr/index.vue'
import { deepClone } from '@/utils'
import assignWork from './assignWork.vue'
import store from '../../store'
const titleMap = {
    motify: '修改',
    delete: '删除',
    signIn: '签到码',
    add: '新增',
    siginList: '签到情况',
    attendance: '考勤',
    inCome: '收入管理'
}
const classMap = [
    { type: '校企合作班', value: '0' },
    { type: '线下培训进阶班', value: '1' },
    { type: '可靠性人才培训班', value: '2' },
    { type: '师资培训班', value: '3' },
    { type: '线上培训班', value: '4' }
]
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: '请输入上课时间' }],
    dateTime: [{ required: true, trigger: 'change', message: '请输入下课时间' }],
    courseContent: [{ required: true, message: '请输入课程内容', trigger: 'blur' }],
    password: [{ required: true, message: '请输入口令', trigger: 'blur' },
    { min: 4, max: 4, message: '请输入四位数字', trigger: 'blur' }
    ],
    amount: [{ required: true, message: '请输入付款金额', trigger: 'blur' },
    { pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/, message: "请输入正确的金额", trigger: 'blur' }],
    isPay: [{ required: true, message: '请输入选择授课方法', trigger: 'change' }],
    url: [{ required: true, message: '请输入课程链接', trigger: 'blur' }],
    title: [{ required: false, message: '请输入职称', trigger: 'blur' }],
    payMethods: [{ required: true, message: '请输入支付方式', trigger: 'change' }]
}
export default {
    components: { fileUpload, vueQr, buttonUpload, assignWork },
    data() {
        return {
            classMap: classMap,
            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: 20,
                courseName: '',
                className: '',
                classType: '0'
            },
            courseForm: {
                classId: '',
                courseName: '',
                instructor: '',
                attachments: [],
                courseTime: '',
            },
            // 班级下拉框数据
            classList: [],
            // 教师下拉框数据
            teacherList: [],
            title: '',
            visibleopen: false,
            rules: courseRule,
            classType: 0,
            inComeForm: [],

            // payOptions: [
            //     {
            //         value: '1',
            //         label: '付费',
            //         children: [{
            //             key: '0',
            //             value: '1-1',
            //             label: '金额'
            //         }, {
            //             key: '0',
            //             value: '1-2',
            //             label: '口令'
            //         }]
            //     },
            //     {
            //         value: '0',
            //         label: '免费',

            //     }],
            payMethods: '0',
            inComeParams: {
                pageNum: 1,
                pageSize: 10,
            },
            inComeTotal: 1,

        }
    },
    methods: {
        // arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        //     if (columnIndex === 1) {
        //         if (rowIndex % 2 === 0) {
        //             return {
        //                 rowspan: 2,
        //                 colspan: 1
        //             };
        //         } else {
        //             return {
        //                 rowspan: 0,
        //                 colspan: 0
        //             };
        //         }
        //     }
        // },
        querySearch(queryString, cb) {
            var restaurants = this.teacherList;
            console.log(restaurants);
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        handleSelect(item) {
            this.courseForm.instructor = item.name
            console.log(item);
        },
        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()
        },
        // payHandleChange(e) {
        //     this.courseForm.isPay = e[0]
        //     if (e[1]) {
        //         this.payMethods = e[1]
        //     }
        //     console.log(e);
        // },
        classChange(e) {
            const result = this.classList.find(item => {
                console.log(item);
                return item.trainClassId == e
            })
            if (result) {
                this.classType = result.classType * 1
            }
            console.log(this.courseForm);
        },
        downLoadSource(params) {
            const url = params.filePath
            if (!url) {
                return
            }
            downloadHttp(url)
        },
        // 导入excel
        uploadExcel() {

        },
        handleClick() {
            this.getList()
            this.$nextTick(() => {
                this.$refs.table.doLayout()
            })
        },
        // importCourse(){
        //     this.$router.push('/course/courseImport')
        // },
        toAssignHomework(row) {
            console.log(row);
            
            this.currentCourse = row
            this.$refs.assignWork.dialogVisible = true
            if (row.homework) {
                this.$refs.assignWork.editContent = row.homework
            } else {

            }
        },
        async subWork(content) {
            const data = {
                courseId: this.currentCourse.courseId,
                // teacherId: store.getters.userId,
                homework: content
            }
            const res = await assignHomeWork(data)
            if (res.code == 200) {
                this.$refs.assignWork.dialogVisible = false
                this.getList()
                this.$message.success('操作成功')
            }
            console.log(res);

            return
            /* 未布置过作业 */
            if (!this.currentCourse.content) {
                const res = await assignHomeWork(data)
                if (res.code == 200) {
                    this.$refs.assignWork.dialogVisible = false
                    this.getList()
                    this.$message.success('作业布置成功')

                }
            }
            /* 修改作业 */
            else {
                const res = await updateHomeWork(data)
                if (res.code == 200) {
                    this.$refs.assignWork.dialogVisible = false
                    this.getList()
                    this.$message.success('作业修改成功')

                }
            }
        },
        async option(row, type) {
            this.optionType = type
            this.currentCourse = row
            this.title = titleMap[type]
            switch (type) {
                case 'motify':
                    this.courseForm = deepClone(row)
                    this.initDialog(this.courseForm.classId)
                    // 为提供线上培训班的类型
                    // console.log(this.classList);
                    // const result = this.classList.find(item => {
                    //     console.log(item);
                    //     return item.trainClassId == this.courseForm.classId
                    // })
                    // console.log(result);
                    // this.classType = result.classType
                    break
                case 'delete':
                    this.deleteRow(row)
                    return
                case 'add':
                    this.initDialog()
                    break
                case 'signIn':
                    this.generateSignIn(row)
                    break
                case 'inCome':
                    this.inComeManage(row)
                    return
                case 'studentRows':
                    // this.studentRows(row)
                    this.$router.push({
                        path: '/course/learnNum',
                        query: {
                            courseId: row.courseId,
                            rourseName: row.courseName
                        },
                    })
                    return
                case 'siginList':
                    // this.id = row.courseId
                    this.$router.push({
                        path: '/signInInfoList',
                        query: {
                            name: row.courseName,
                            id: row.courseId,
                            classType: row.classType,
                        },
                    })
                    return
                default:
                    break
            }
            this.visibleopen = true
        },
        // 提交
        submitto() {
            this.$refs['courseForm'].validate((valid) => {
                if (valid) {
                    this.submit()
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        async submit() {
            const data = deepClone(this.courseForm)
            if (data.amount) {
                data.amount = data.amount * 1
            }
            if (this.classType == 4) {
                data.classType = '4'
            }
            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()
        },
        timeChange(val) {
            if (this.queryParams.classType != 4) {
                return
            }
            if (this.courseForm.courseTime && this.courseForm.dateTime) {
                const sta = new Date(this.courseForm.courseTime).getTime()
                const end = new Date(this.courseForm.dateTime).getTime()
                if (end - sta <= 0) {
                    this.$message.error('上课时间不能晚于下课时间');
                    ('dateTime' == val) && (this.courseForm.dateTime = '');
                    ('courseTime' == val) && (this.courseForm.courseTime = '')
                }
            }
        },
        // dialog init
        async initDialog(val) {
            console.log(val);
            const obj = {
                classType: this.queryParams.classType
            }
            const classRes = await getClassList(obj)
            this.classList = classRes.data
            if (val) {
                this.classChange(val)
            }
            const teacherRes = await listTeacherAll()
            this.teacherList = teacherRes

        },
        // 收入管理
        inComeManage(row) {
            row.courseId ? '' : (row = this.currentCourse)
            getInComeInfo({ recordName: row.courseName, ...this.inComeParams }).then(res => {
                this.inComeTotal = res.total
                this.inComeForm = res.rows
                this.visibleopen = true
            })
        },
        openDia() {
            if (this.optionType === 'motify') {
                this.$refs.fileUpload?.fileInit(this.courseForm.attachments)
            }
        },
        // 关闭
        closeDia() {
            this.$refs['courseForm']?.resetFields()
            Object.keys(this.courseForm).forEach((item) => {
                if (Array.isArray(this.courseForm[item])) {
                    if (item == 'remark') {
                        this.courseForm[item] = ''
                    } else {
                        this.courseForm[item] = []
                    }
                } else {
                    this.courseForm[item] = ''
                }
            })
            this.classType = 0
            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>
