<template>
    <div class="container" style="padding: 30px">
        <el-form :model="queryParamss" ref="queryForm" inline label-width="68px">
            <el-form-item label="姓名" prop="studentName">
                <el-input v-model="queryParamss.studentName" placeholder="请输入姓名" clearable size="small" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="queryParamss.mobile" placeholder="请输入手机号" clearable size="small" />
            </el-form-item>
            <!-- <el-form-item label="所属学院" prop="homeCollege" v-if="$route.query.type == 0">
                    <el-input v-model="queryParamss.homeCollege" placeholder="请输入所属学院" clearable size="small" />
                </el-form-item> -->
            <el-form-item label="辅导员" prop="counsellor" v-if="$route.query.type == 0">
                <el-input v-model="queryParamss.counsellor" placeholder="请输入辅导员姓名" clearable size="small" />
            </el-form-item>
            <el-form-item label="专业" prop="majorName" v-if="$route.query.type == 0">
                <el-input v-model="queryParamss.majorName" placeholder="请输入专业" clearable size="small" />
            </el-form-item>
            <el-form-item label="结课报告" prop="reportName" v-if="$route.query.type == 0">
                <el-select v-model="queryParamss.reportName" placeholder="是否上传" style="width: 100px;">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-button icon="el-icon-download" type="warning" size="small" style="margin-bottom: 20px"
            @click="exporExcel">导出为excel</el-button>
        <el-button icon="el-icon-download" type="success" size="small" style="margin-bottom: 20px"
            @click="exportEvaReport('multify')">导出评价</el-button>
        <el-button icon="el-icon-download" type="primary" size="small" style="margin-bottom: 20px"
            @click="downloadReport('multify')">下载结课报告</el-button>
        <el-button icon="el-icon-download" size="small" style="margin-bottom: 20px"
            @click="downloadAttachment('multify')">下载附件简历</el-button>
        <!-- 详细学生信息弹层 -->
        <el-table v-if="$route.query.type != 3" :data="studentList" v-loading="loading"
            :default-sort="{ prop: 'asseGradeVag', order: 'descending' }" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" align="center" type="index" />
            <el-table-column label="学号" align="center" prop="studentCode" v-if="$route.query.type == 0" />
            <el-table-column label="姓名" align="center" prop="studentName" />
            <el-table-column label="性别" align="center" prop="sex">
                <template slot-scope="scope">
                    <div v-show="scope.row.sex === '0'">男</div>
                    <div v-show="scope.row.sex === '1'">女</div>
                </template>
            </el-table-column>
            <!-- <el-table-column label="所属学院" align="center" prop="homeCollege" v-if="$route.query.type == 0" /> -->
            <el-table-column label="专业名称" align="center" prop="majorName" v-if="$route.query.type == 0" />
            <el-table-column label="手机号" align="center" prop="mobile" />
            <el-table-column label="辅导员" align="center" prop="counsellor" v-if="$route.query.type == 0" />
            <el-table-column label="辅导员联系方式" align="center" prop="counsellorTel" v-if="$route.query.type == 0" />
            <el-table-column label="报名时间" align="center" prop="registrationTime" />

            <el-table-column label="结课报告" align="center" prop="registrationTime">
                <template slot-scope="scope">
                    <div style="color: #1890ff;cursor: pointer;" @click="downloadReport(scope.row.reportAttachment)">{{
                        scope.row.reportName ? scope.row.reportName : '' }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="评分(次数)" sortable align="center" prop="asseGradeVag">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="evaluateContend(scope.row)">{{ scope.row.asseGradeVag ? (
                        scope.row.asseGradeVag + '(' + scope.row.asseCount + ')') : '' }}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="附件简历" align="center" prop="registrationTime">
                <template slot-scope="scope">
                    <div style="color: #1890ff;cursor: pointer;" @click="downloadReport(scope.row.attResume)">{{
                        scope.row.attResume ? '下载' : '' }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" v-if="scope.row.remark"
                        @click="editRemark(scope.row)">修改备注</el-button>
                    <el-button size="mini" type="text" v-else @click="addRemark(scope.row)">添加备注</el-button>
                    <el-button size="mini" type="text" @click="delRow(scope.row)">删除</el-button>
                    <el-button size="mini" type="text" @click="evaluate(scope.row)">去评价</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-table v-else :data="teacherList" v-loading="loading"
            :default-sort="{ prop: 'asseGradeVag', order: 'descending' }">
            <el-table-column label="序号" align="center" type="index" />
            <el-table-column v-for="it in headerList" :key="it" :label="headerData[it]" align="center" :prop="it" />
            <el-table-column label="评分(次数)" sortable align="center" prop="asseGradeVag">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="evaluateContend(scope.row)">{{ scope.row.asseGradeVag ? (
                        scope.row.asseGradeVag + '(' + scope.row.asseCount + ')') : '' }}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" v-if="scope.row.remark"
                        @click="editRemark(scope.row)">修改备注</el-button>
                    <el-button size="mini" type="text" v-else @click="addRemark(scope.row)">添加备注</el-button>
                    <el-button size="mini" type="text" @click="delRow(scope.row)">删除</el-button>
                    <el-button size="mini" type="text" @click="evaluate(scope.row)">去评价</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="totals > 0" :total="totals" :page.sync="queryParamss.pageNum"
            :limit.sync="queryParamss.pageSize" @pagination="getStudentList" />
        <!-- 弹层 -->
        <el-dialog class="diaform" :title="title" :visible.sync="visibleopen" :close-on-click-modal="false"
            width="650px" append-to-body @close="colsedia">
            <el-form v-show="currentType === 'remark'" :model="form" :rules="rules" ref="Form" label-width="80px">
                <!-- 类型 -->
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" clearable type="textarea" />
                </el-form-item>
            </el-form>
            <el-form v-show="currentType === 'evaluate'" :model="evaForm" :rules="evaFormrules" ref="evaForm"
                label-width="150px">
                <!-- 类型 -->
                <el-form-item label="日期" prop="assessmentDate">
                    <el-date-picker v-model="evaForm.assessmentDate" :default-value="new Date()" style="width: 340px"
                        value-format="yyyy-MM-dd" placeholder="请选择评价日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="评分" prop="grade">
                    <el-input v-model="evaForm.grade" type="number" style="width: 340px" placeholder="请输入评分" />
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <el-input v-model="evaForm.content" style="width: 340px" placeholder="请输入评价内容" clearable
                        type="textarea" />
                </el-form-item>
            </el-form>
            <div v-show="currentType === 'evaContent'">
                <h3 style="text-align: center;font-weight: bold;margin: 0;">平均分：<span class="scoreNum">{{ asseGradeVag
                        }}分</span></h3>
                <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 3px;">
                    <div style="text-align: center;margin-left: -10px;">总数:{{ asseCount }}</div>
                    <div class="loadMore" v-if="evaTotal > evaQuery.pageSize" @click="loadMoreEva">加载更多...</div>
                    <!-- <div class="" v-else>已显示</div> -->
                </div>
                <div class="evaWrap">
                    <div v-for="(item, index) in evaList" :key="index" class="evaItem">
                        <div class="evaItemWrap">
                            <div class="evaTitle">
                                <div class="evaHead">
                                    <div class="timeStemp">{{ item.assessmentDate.substr(0, 10) }}</div>
                                    <div><span class="scoreNum">{{ item.grade }}分</span></div>
                                </div>
                                <div style="padding-right: 10px;">评价老师：{{ item.assessmentBy }}</div>
                            </div>
                            <div class="evaContend">
                                <div class="evaHead">
                                    <div class="timeLine"></div>
                                    <el-tooltip v-if="item.content.length > 15" placement="top" effect="light"
                                        class="evaText">
                                        <div slot="content">{{ item.content }}</div>
                                        <div class="">{{ item.content }}</div>
                                    </el-tooltip>
                                    <div v-else class="">{{ item.content }}</div>
                                </div>
                                <el-button size="mini" @click="delEva(item)" type="text"
                                    v-show="nickName(item.assessmentBy)"
                                    style="color: red;padding-right: 5px;">删除</el-button>
                            </div>
                        </div>
                    </div>
                    <div v-show="evaTotal <= evaQuery.pageSize" class="startSteamp">开始</div>
                </div>
            </div>


            <span slot="footer" class="dialog-footer">
                <el-button @click="colsedia">取 消</el-button>
                <el-button type="primary" @click="submitRemark">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
// const currentTypeMap = {}
import {
    searchNum, addRemarkI, delSign, exportExcelF, addStuentEva
    , delStudentEva, getStudentEva, exportEva
} from '@/api/trainService/index.js'
import { saveAs } from 'file-saver'
import store from '@/store'
import { downPdf } from '../../utils';
// 1 报名未开始、2 报名中、 3 报名结束未开课、4 开课中、5 已结束   status字段
export default {
    name: 'peixunbaoming',
    data() {
        return {
            loading: false,
            // 总条数
            multipleSelection: [],
            queryParamss: {
                pageNum: 1,
                pageSize: 10,
                studentName: null,
                mobile: null,
                reportName: '',
                majorName: null,
                counsellor: null,
                counsellorTel: null,
            },
            totals: 0,
            evaList: [],
            options: [
                { value: '1', label: '已上传' },
                { value: '0', label: '未上传' }
            ],
            studentList: [],
            // 弹层
            title: '添加备注',
            visibleopen: false,
            form: {},
            rules: {
                // remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
            },
            rowId: null,
            teacherList: [], //原始数据
            // 表头数据
            headerList: [],
            // 评价的总数
            evaTotal: 0,
            asseGradeVag: 0,
            asseCount: 0,
            evaQuery: {
                pageSize: 5,
                pageNum: 1,
            },
            base: process.env.VUE_APP_BASE_API,
            headerData: {},

            // 选中的学生
            courrentStudnent: {},
            currentType: '',
            evaForm: {
                assessmentDate: '',
                grade: NaN,
                content: ''
            },
            evaFormrules: {
                assessmentDate: [
                    { required: true, message: '请选择评价日期', trigger: 'change' }
                ],
                grade: [
                    { required: true, message: '请填写评分', trigger: 'blur' },
                    { pattern: /^(([1-9]?\d)|100)$/, message: '请输入0-100的整数', trigger: 'blur' }
                ],
                content: [
                    { required: true, message: '请添加评价', trigger: 'blur' },
                    { min: 1, max: 500, message: '只能输入1-500个字符', trigger: 'blur' }
                ],
            }
        }
    },

    mounted() {
        this.getStudentList()
    },
    computed: {
        nickName() {
            return function (myNickName) {
                if (store.getters.name == 'admin' || store.getters.name == 'manager') {
                    return true
                } else if (myNickName == store.getters.nickName) {
                    return true
                } else {
                    return false
                }
            }
        },
        average() {
            let re = 0
            this.evaList.forEach(item => { re += item.grade })
            return re / (this.evaList.length)
        },
    },
    methods: {

        async getStudentList() {
            this.loading = true
            if (localStorage.getItem('jsondata')) {
                const firstData = JSON.parse(localStorage.getItem('jsondata'))
                this.headerList = []
                this.headerData = {}
                // 取第一项处理表头
                firstData.forEach((it) => {
                    // 循环标识
                    this.headerList.push(it.key)
                    // 表头文字
                    this.headerData[it.key] = it[it.key]
                })
                // 处理备注列
                this.headerList.push('remark')
                this.headerData.remark = '备注'
            }
            const res = await searchNum({
                classType: this.$route.query.type,
                trainClassId: this.$route.query.id,
                ...this.queryParamss,
            })
            if (this.$route.query.type == 3 && res.total > 0) {
                // 处理json
                if (res.rows[0].data) {
                    // this.headerList = []
                    // this.headerData = {}
                    // // 取第一项处理表头
                    // const firstData = JSON.parse(res.rows[0].data)
                    // firstData.forEach((it) => {
                    //     // 循环标识
                    //     this.headerList.push(it.key)
                    //     // 表头文字
                    //     this.headerData[it.key] = it[it.key]
                    // })
                    // // 处理备注列
                    // this.headerList.push('remark')
                    // this.headerData.remark = '备注'
                    // 表格新数据
                    const newData = []
                    // 构造表格数据--解析每一条json串
                    res.rows.forEach((item) => {
                        if (item.data) {
                            const obj = {}
                            JSON.parse(item.data).forEach((ite) => {
                                obj[ite.key] = ite.value
                                obj.trainingStudentId = item.trainingStudentId
                                obj.remark = item.remark
                                obj.asseGradeVag = item.asseGradeVag
                                obj.asseCount = item.asseCount
                            })
                            newData.push(obj)
                        }
                    })
                    this.teacherList = newData
                }
            } else {
                this.studentList = res.rows
            }
            this.totals = res.total
            this.loading = false
        },
        handleQuery() {
            this.getStudentList()
        },
        loadMoreEva() {
            this.evaQuery.pageSize = this.evaQuery.pageSize + 5
            this.initEvalist()
        },
        resetQuery() {
            this.resetForm('queryForm')
            this.getStudentList()
        },
        // 删除行
        delRow(row) {

            this.$confirm('是否确认删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    delSign(row.trainingStudentId).then((res) => {
                        this.getStudentList()
                        this.$message.success('删除成功')
                    })
                })
                .catch(() => { })
        },
        // 添加评价
        evaluate(row) {
            this.courrentStudnent = row
            this.title = '添加评价'
            this.currentType = 'evaluate'
            this.visibleopen = true
        },
        async evaluateContend(row) {
            this.courrentStudnent = row
            this.title = '查看评分'
            this.currentType = 'evaContent'
            await this.initEvalist()
            this.asseGradeVag = row.asseGradeVag
            this.asseCount = row.asseCount
            this.visibleopen = true
        },
        initEvalist() {
            getStudentEva(this.courrentStudnent.trainingStudentId, this.evaQuery).then(res => {
                this.evaList = res.rows
                this.evaTotal = res.total
                if (this.evaList.length == 0) {
                    this.visibleopen = false
                    this.getStudentList()
                }
            })
        },

        // 添加备注
        addRemark(row) {
            this.currentType = 'remark'
            this.title = '添加备注'
            this.visibleopen = true
            // trainClassId  trainingStudentId  userId
            this.rowId = row.trainingStudentId
        },
        // 修改备注
        editRemark(row) {
            this.currentType = 'remark'
            this.rowId = row.trainingStudentId
            this.visibleopen = true
            this.title = '修改备注'
            this.form = { remark: row.remark }
        },
        // 提交备注
        submitRemark() {
            if (this.currentType == 'remark') {
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        addRemarkI({ trainingStudentId: this.rowId, remark: this.form.remark }).then(() => {
                            this.$message.success('备注成功！')
                            this.getStudentList()
                            this.colsedia()
                        })
                    }
                })
            } else if (this.currentType == 'evaluate') {
                this.$refs['evaForm'].validate((valid) => {
                    if (valid) {
                        const data = JSON.parse(JSON.stringify(this.evaForm))
                        // data.grade = data.grade*1
                        data['studentId'] = this.courrentStudnent.trainingStudentId
                        data.assessmentDate = data.assessmentDate
                        addStuentEva(data).then(() => {
                            this.$message.success('评价成功')
                            this.getStudentList()
                            this.colsedia()
                        })
                    }
                })
            }

        },
        // 删除某条评价
        delEva(row) {
            this.$confirm('此操作将永久删除该评价, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delStudentEva(row.assessmentId).then(res => {
                    // getStudentEva(this.courrentStudnent.trainingStudentId)
                    this.initEvalist()

                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                })
            })
        },
        // 取消备注
        colsedia() {
            this.$refs['evaForm']?.resetFields()
            this.evaList = []
            this.evaQuery = {
                pageSize: 5,
                pageNum: 1
            }
            this.evaTotal = 0
            this.form = {}
            this.visibleopen = false
        },
        // 导出为excel
        exporExcel() {
            exportExcelF(this.$route.query.id, this.queryParamss).then((res) => {
                const blob = new Blob([res])
                saveAs(blob, this.$route.query.name + '报名表.xlsx')
            })
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 导出评价
        async exportEvaReport() {
            if (this.multipleSelection.length == 0) {
                return
            }
            const ids = this.multipleSelection.map(item => {
                return item.trainingStudentId
            })
            const res = await exportEva({ 'ids': ids })
            const blob = new Blob([res])
            saveAs(blob, this.$route.query.name + '评价表.xlsx')
        },
        downloadAttachment() {
            this.multipleSelection.forEach(item => {
                if (item.attResume) {
                    downPdf(this.base + item.attResume)
                    //     const iframe = document.createElement("iframe");
                    //     iframe.style.display = "none"; // 不可见
                    //     iframe.style.height = "0"; // 高度为0
                    //     iframe.src = this.base + item.reportAttachment; // 下载地址
                    //     document.body.appendChild(iframe); // 必须有，iframe挂在到dom树触发请求
                    //     // this.$nextTick(()=>{
                    //     //     document.body.removeChild(iframe)
                    //     // })
                    //     setTimeout(() => {
                    //         document.body.removeChild(iframe);
                    //     }, 1000)
                    // }
                }
            })
        },
        downloadReport(val) {
           
            // return
            if (val === 'multify') {
                const self = this
                this.multipleSelection.forEach(item => {
                    if (item.reportAttachment) {
                        downPdf(this.base + item.reportAttachment)
                        //     const iframe = document.createElement("iframe");
                        //     iframe.style.display = "none"; // 不可见
                        //     iframe.style.height = "0"; // 高度为0
                        //     iframe.src = this.base + item.reportAttachment; // 下载地址
                        //     document.body.appendChild(iframe); // 必须有，iframe挂在到dom树触发请求
                        //     // this.$nextTick(()=>{
                        //     //     document.body.removeChild(iframe)
                        //     // })
                        //     setTimeout(() => {
                        //         document.body.removeChild(iframe);
                        //     }, 1000)
                        // }
                    }
                })
            } else if (val) {
                downPdf(this.base + val)
            }
        }
    },
    created() {
        console.log();

    },
}
</script>

<style lang="scss">
.scoreNum {
    color: #fbaa10;
}

.el-tooltip__popper.is-light {
    width: 300px !important;
    overflow: hidden;
}

.loadMore {
    text-align: center;
    color: rgb(24, 144, 255);
    cursor: pointer;
}

.evaWrap {
    padding: 0 10px;
    max-height: 500px;
    overflow: auto;

    .evaHead {
        display: flex;
        align-items: center;

        .evaText {
            width: 500px;
            line-height: 40px;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            cursor: pointer;
        }
    }

    .startSteamp {
        width: 100px;
        font-weight: bold;
        padding-left: 20px;
        color: #676768;
        position: relative;

        &::before {
            content: ' ';
            position: absolute;
            margin-top: 5px;
            left: -2px;
            width: 10px;
            border-radius: 50%;
            height: 10px;
            background-color: #aeb0b6;
        }
    }

    .evaItemWrap {
        border-radius: 4px;
        border: 1px solid #ebeef5;
        margin-left: 10px;
        padding: 5px;
        border-radius: 5px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1)
    }

    .evaItem {
        margin-top: 5px;

        .evaTitle {
            display: flex;
            align-items: center;
            justify-content: space-between;
            // background-color: #6767682a;
            border-radius: 5px;

            .timeStemp {
                font-weight: bold;
                color: #676768;
                width: 100px;
                padding-left: 10px;
            }
        }

        .evaContend {
            padding-right: 5px;
            display: flex;
            align-items: center;
            height: 40px;
            justify-content: space-between;
            // background-color: #6767685b;
            margin-left: 10px;

            .timeLine {
                width: 0px;
                height: 50px;
                position: relative;

                &::before {
                    content: ' ';
                    position: absolute;
                    margin-top: -5px;
                    left: -24px;
                    width: 2px;
                    height: 75px;
                    background-color: #aeb0b6;
                    border-radius: 2px;
                }

                &::after {
                    content: ' ';
                    position: absolute;
                    margin-top: -10px;
                    left: -28px;
                    width: 10px;
                    border-radius: 50%;
                    height: 10px;
                    background-color: #aeb0b6;
                }
            }
        }
    }
}
</style>
