<template>
    <div class="list-view">
        <div class="filters-container">
            <el-form :model="form" size="mini" inline>
                <el-row>
                    <el-col :span="16">
                        <el-form-item label="参赛专业">
                            <el-cascader
                                ref="artCascader"
                                style="width: 100%"
                                v-model="form.specialtyId"
                                :props="optionProps"
                                :options="artTypes"
                                :show-all-levels="false"
                                placeholder="请选择专业"
                                clearable
                            >
                            </el-cascader>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="getData" type="primary" icon="el-icon-search" size="mini"
                                >查询
                            </el-button>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="24">
                        <el-form-item label="活动名称">
                            <el-select
                                v-model="performanceId"
                                clearable
                                filterable
                                placeholder="活动名称"
                                style="width: 300px"
                                @change="changeAddress"
                            >
                                <el-option
                                    v-for="item in performances"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="getData" type="primary" icon="el-icon-search">查询 </el-button>
                        </el-form-item>
                    </el-col> -->
                    <div v-if="!online">
                        <el-form-item label="活动日期">
                            <el-date-picker v-model="date" type="date" placeholder="选择日期" class="filter-item">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="时间">
                            <el-radio-group v-model="morning" @change="getData" class="filter-item">
                                <el-radio-button :label="true">上午</el-radio-button>
                                <el-radio-button :label="false">下午</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="活动地点">
                            <el-select v-model="form.address" class="filter-item">
                                <el-option
                                    v-for="(item, index) in addresses"
                                    :key="index"
                                    :value="item.value"
                                    :label="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                </el-row>
            </el-form>
        </div>
        <el-table
            :data="tableData"
            row-key="id"
            ref="table"
            header-row-class-name="table-header-row"
            header-cell-class-name="table-header-cell"
            row-class-name="table-row"
            cell-class-name="table-cell"
            :height="tableHeight"
        >
            <el-table-column v-if="multipleMode" align="center" type="selection" width="50"> </el-table-column>
            <el-table-column prop="id" label="节目编号" width="100"> </el-table-column>
            <!-- <el-table-column prop="arrangeName" label="分组" min-width="160"> </el-table-column> -->
            <el-table-column prop="name" label="节目名称" min-width="70"> </el-table-column>
            <el-table-column prop="specialty" label="参赛专业"> </el-table-column>
            <el-table-column
                prop="competitionGroup"
                label="参赛组别"
                :formatter="competitionGroupFormatter"
                min-width="70"
            >
            </el-table-column>
            <el-table-column prop="levelSetting" label="参赛级别" min-width="70"> </el-table-column>
            <el-table-column prop="participant" label="参赛人员" show-overflow-tooltip>
                <template slot-scope="{ row }">{{
                    row.participant ? row.participant.join(',') : row.participant
                }}</template>
            </el-table-column>
            <el-table-column prop="quantity" label="表演人数" min-width="70"> </el-table-column>
            <el-table-column prop="signedIn" label="状态" :formatter="signedInFormatter" v-if="!online">
            </el-table-column>
            <!-- <el-table-column prop="score" label="成绩"> </el-table-column> -->
            <el-table-column prop="myScore" label="评分" align="center" min-width="80">
                <template slot-scope="{ row }">
                    <span v-if="!row.myScore">暂无</span>
                    <span v-else>{{ row.myScore }}</span>
                    <!-- <el-input-number
                        v-else
                        v-model="row.myScore"
                        size="mini"
                        label=""
                        :min="0"
                        :max="100"
                        :step="1"
                        :controls="true"
                        controls-position="both"
                        @change="saveScore(row)"
                    >
                    </el-input-number> -->
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" align="center" min-width="80">
                <template slot-scope="{ row }">
                    <span v-if="!row.remark">暂无</span>
                    <span v-else>{{ row.remark }}</span>
                    <!-- <el-input
                        v-else
                        size="mini"
                        @change="saveScore(row)"
                        v-model="row.remark"
                        placeholder="请输入备注"
                        clearable
                    ></el-input> -->
                </template>
            </el-table-column>
            <el-table-column label="操作" align="left" fixed="right" min-width="100">
                <template slot-scope="{ row, $index }">
                    <el-button @click="playVideo(row, $index)" size="mini" plain type="primary">查看作品</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-wrapper">
            <!-- <div class="multiple-mode-wrapper">
                <el-button v-if="!multipleMode" @click="toggleMultipleMode(true)">批量编辑</el-button>
                <el-button-group v-else>
                    <el-button @click="operation1">批量操作1</el-button>
                    <el-button @click="operation2">批量操作2</el-button>
                    <el-button @click="toggleMultipleMode(false)">取消</el-button>
                </el-button-group>
            </div> -->
            <el-pagination
                background
                @size-change="onSizeChange"
                @current-change="onCurrentChange"
                :current-page="page"
                :page-sizes="[10, 20, 30, 40, 50]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalElements"
            >
            </el-pagination>
        </div>

        <el-dialog
            :title="programme.name"
            class="videoDialog"
            destroy-on-close
            center
            append-to-body
            :visible.sync="showViedo"
            width="45vw"
        >
            <div class="dialog-content">
                <video
                    :src="programme.video"
                    controls
                    style="max-height: 600px; max-width: 100%; margin: 0 auto"
                    v-if="programme.video"
                >
                    您的浏览器不支持 video 标签。
                </video>
                <img
                    style="max-height: 600px; max-width: 100%; display: block; margin: auto"
                    :src="programme.annex"
                    alt=""
                    v-if="programme.annex"
                />
                <el-card shadow="never" style="width: 100%; margin: 10px auto">
                    <el-form :form="programme">
                        <el-form-item label="分数">
                            <el-radio-group v-model="scoreType" @change="changeScore">
                                <el-radio-button :label="item.value" :key="item.value" v-for="item in scoreOptions">
                                    <span> {{ item.value }}</span>
                                    <span>({{ item.text1 }})</span>
                                </el-radio-button>
                            </el-radio-group>
                            <!-- <span class="scoreTips">{{ scoreInfo.text1 }}</span> -->
                            <!-- <span v-if="programme.second">{{ programme.myScore }}</span> -->
                            <div class="score-content">
                                <!-- <el-alert
                                    :title="scoreInfo.text1"
                                    type="warning"
                                    :closable="false"
                                    style="line-height:16px"
                                >
                                </el-alert> -->
                                <div class="score-list">
                                    <el-input-number
                                        class="number1"
                                        v-model="scoreValue[0]"
                                        size="mini"
                                        :min="scoreInfo.min"
                                        :max="scoreInfo.max"
                                        :step="1"
                                        :controls="true"
                                        controls-position="both"
                                    >
                                    </el-input-number>

                                    <span class="tag">
                                        .
                                    </span>

                                    <el-input-number
                                        class="number2"
                                        v-model="scoreValue[1]"
                                        size="mini"
                                        label=""
                                        :min="0"
                                        :max="9"
                                        :step="1"
                                        :controls="true"
                                        controls-position="both"
                                    >
                                    </el-input-number>

                                    <el-input-number
                                        class="number2"
                                        v-model="scoreValue[2]"
                                        size="mini"
                                        label=""
                                        :min="0"
                                        :max="9"
                                        :step="1"
                                        :controls="true"
                                        controls-position="both"
                                    >
                                    </el-input-number>
                                </div>
                                <div class="score-desc">
                                    <span class="number1">整数位</span>
                                    <div class="tag">.</div>
                                    <span class="number2">十分位</span>
                                    <span class="number2">百分位</span>
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item label="备注">
                            <!-- <span v-if="programme.second">{{ programme.remark }}</span> -->
                            <el-input
                                size="mini"
                                v-model="programme.remark"
                                placeholder="请输入备注"
                                style="width: 200px"
                                clearable
                            ></el-input>
                        </el-form-item>

                        <el-form-item>
                            <el-button size="mini" @click="saveScore(programme)" type="primary">保存</el-button>
                            <el-button size="mini" @click="move(-1)" :disabled="index == 0">上一个</el-button>
                            <el-button
                                size="mini"
                                @click="move(1)"
                                :disabled="(page - 1) * pageSize + index == totalElements - 1 || index >= pageSize - 1"
                                >下一个</el-button
                            >
                            <el-button @click="showViedo = false" size="mini">关闭</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import delChild from '@/mixins/delChild';
import { mapState } from 'vuex';
import pageableTable from '@/mixins/pageableTable';
import { format, isSameDay, startOfDay } from 'date-fns';
import endOfDay from 'date-fns/endOfDay';
import addHours from 'date-fns/addHours';

export default {
    name: 'ProgrammeScoreList',
    mixins: [pageableTable, delChild],
    props: ['review'],
    data() {
        return {
            multipleMode: false,
            search: '',
            url: '/programme/byScore',
            downloading: false,
            form: {},
            dialogSign: false,
            performanceId: '',
            performances: [],
            performance: {},
            signedInOptions: [
                { label: '已签到', value: 'SIGNED_IN' },
                { label: '未签到', value: 'UNSIGNED' },
                { label: '已调整', value: 'ADJUSTED' }
            ],
            artTypes: [],
            optionProps: {
                value: 'id',
                label: 'name',
                children: 'children',
                multiple: false,
                emitPath: false,
                checkStrictly: true,
                expandTrigger: 'hover'
            },
            signForm: {},
            addresses: [],
            morning: true,
            date: new Date(),
            columnKeys: ['arrangeName'],
            addressList: [],
            showViedo: false,
            programme: {},
            index: 0,
            online: true,
            competitionGroupOptions: [
                { label: '个人', value: 'SINGLE' },
                { label: '集体', value: 'COLLECTIVE' }
            ],
            scoreType: 'D',
            scoreOptions: [
                {
                    value: 'D',
                    text1: '60-70分',
                    text2: '歌唱姿势正确，能够完整地演唱整首歌曲，音准、节奏尚可，歌唱方法无明显毛病。',
                    min: 60,
                    max: 69
                },
                {
                    value: 'C',
                    text1: '70-80分',
                    text2:
                        '歌唱姿势正确，音域达到f2以上，音准、节奏、共鸣较好，气息流畅，吐字较清晰，喉头较稳定，有一定的艺术表现力，曲目具有一定的难度。',
                    min: 70,
                    max: 79
                },
                {
                    value: 'B',
                    text1: '80-90分',
                    text2:
                        '自然嗓音条件良好，音域达到g2以上，音准、节奏、共鸣以及气息的运用技巧娴熟，基本功扎实，喉头稳定，音乐感觉好，艺术表现力强，曲目难度较大。',
                    min: 80,
                    max: 89
                },
                {
                    value: 'A',
                    text1: '90分以上',
                    text2: '嗓音条件很好，音域宽广，歌唱技术全面完美，音乐感很好，演唱艺术感染力强，曲目难度大。',
                    min: 90,
                    max: 98.99
                }
            ],
            scoreValue: [65, 0, 0]
        };
    },
    created() {
        this.morning = isSameDay(addHours(new Date(), 12), new Date());
        this.$http
            .post('/artType/allList')
            .then(res => {
                this.artTypes = this.delChild(res);
            })
            .catch(e => {
                console.log(e);
            });
    },
    computed: {
        selection() {
            return this.$refs.table.selection.map(i => i.id);
        },
        showTable() {
            return this.backMap(this.tableData);
        },
        scoreInfo() {
            let info = [...this.scoreOptions].find(item => {
                return item.value === this.scoreType;
            });
            return info || {};
        }
    },
    methods: {
        changeScore() {
            setTimeout(() => {
                console.log(this.scoreInfo.max + this.scoreInfo.min);
                let val = parseInt((this.scoreInfo.max + this.scoreInfo.min) / 2);
                console.log(val);
                this.$set(this.scoreValue, 0, val + 1);
            }, 100);
        },
        competitionGroupFormatter(row, column, cellValue, index) {
            let selectedOption = this.competitionGroupOptions.find(i => i.value === cellValue);
            if (selectedOption) {
                return selectedOption.label;
            }
            return '';
        },
        signedInFormatter(row, column, cellValue, index) {
            let selectedOption = this.signedInOptions.find(i => i.value === cellValue);
            if (selectedOption) {
                return selectedOption.label;
            }
            return '';
        },
        beforeGetData() {
            let data = {
                query: {
                    auditTimes: 1
                }
            };
            if (this.performanceId) {
                data.query.performanceId = this.performanceId;
            }
            if (this.review) {
                data.query.auditTimes = this.performance.auditTimes || 1;
            }
            if (this.$route.query.eid) {
                data.query.userId = this.$route.query.eid;
            }
            if (this.form.specialtyId) {
                data.query.code = this.getCode(this.form.specialtyId);
            }
            // if (this.date) {
            //     if (this.morning) {
            //         data.query.showBegin = [
            //             format(startOfDay(this.date), 'yyyy-MM-dd HH:mm:ss'),
            //             format(this.date, 'yyyy-MM-dd') + ' 12:00:00'
            //         ].join(',');
            //     } else {
            //         data.query.showBegin = [
            //             format(this.date, 'yyyy-MM-dd') + ' 12:00:00',
            //             format(endOfDay(this.date), 'yyyy-MM-dd HH:mm:ss')
            //         ].join(',');
            //     }
            // }

            return data;
        },
        toggleMultipleMode(multipleMode) {
            this.multipleMode = multipleMode;
            if (!multipleMode) {
                this.$refs.table.clearSelection();
            }
        },
        showSign(row) {
            this.dialogSign = true;
            this.signForm.id = row.id;
        },
        operation1() {
            this.$notify({
                title: '提示',
                message: this.selection
            });
        },
        operation2() {
            this.$message('操作2');
        },
        signIn() {
            this.$alert('确认签到？', '提示', { type: 'primary' })
                .then(() => {
                    return this.$http.post('/programme/signIn', {
                        id: this.signForm.id,
                        signedIn: this.signForm.signedIn,
                        description: this.signForm.description
                    });
                })
                .then(() => {
                    this.$message.success('签到成功');
                    this.dialogSign = false;
                    this.getData();
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        this.$message.error(e.error);
                    }
                });
        },
        saveScore(row) {
            // if (!row.myScore) {
            //     this.$message.warning('请输入评分');
            //     return;
            // }
            let record = {
                programmeId: row.id,
                score: this.scoreValue[0] + '.' + this.scoreValue[1] + this.scoreValue[2],
                remark: row.remark,
                performanceId: row.performanceId,
                expertId: this.$route.query.eid
            };
            this.$http
                .post('/programmeScore/mark', record, { body: 'json' })
                .then(res => {
                    this.$message.success('评分成功');
                    this.getData();
                    this.programme = JSON.parse(res);
                })
                .catch(e => {
                    this.$message.error(e.error);
                });
        },
        backMap(list, key = 'arrangeName', preActive = 0) {
            let _map = new Map();
            list.forEach((item, index) => {
                let info = {
                    active: index + preActive,
                    childNum: 1,
                    list: []
                };
                if (_map.has(item[key])) {
                    info = _map.get(item[key]);
                    info.list.push(item);
                    info.childNum = info.list.length;
                } else {
                    info.list.push(item);
                }

                _map.set(item[key], info);
            });

            let keyIndex = this.columnKeys.indexOf(key);
            if (keyIndex !== this.columnKeys.length - 1) {
                [..._map.keys()].forEach(item => {
                    let info = _map.get(item);
                    let childMap = this.backMap(info.list, this.columnKeys[keyIndex + 1], info.active);
                    _map.set(item, {
                        ...info,
                        childMap: childMap
                    });
                });
            }

            return _map;
        },
        getInfo(mapInfo = new Map(), keys = ['date']) {
            let info = {};
            keys.forEach(item => {
                if (mapInfo.has(item)) {
                    info = mapInfo.get(item);
                    mapInfo = mapInfo.get(item).childMap;
                }
            });
            return info;
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            let keyIndex = columnIndex;
            // if (column.label === '操作') {
            //     keyIndex = 2;
            // }

            if (keyIndex < this.columnKeys.length) {
                let keys = [...this.columnKeys].slice(0, keyIndex + 1).map(item => {
                    return row[item];
                });
                let info = this.getInfo(this.showTable, keys);
                if (rowIndex === info.active) {
                    return {
                        rowspan: info.childNum,
                        colspan: 1
                    };
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }
            }
        },
        playVideo(row, index) {
            this.index = index;
            this.showViedo = true;
            this.programme = row;
            let info = [...this.scoreOptions].find(item => {
                return row.myScore >= item.min && row.myScore <= item.max;
            });

            this.scoreType = info ? info.value : 'D';
            let score = (row.myScore * 100).toString();

            this.scoreValue = [Number(score.substr(0, 2)), Number(score.substr(2, 1)), Number(score.substr(3, 1))];
        },
        move(direction) {
            const end = direction + this.index;
            this.programme = { ...this.tableData[end] };
            this.index = end;

            let info = [...this.scoreOptions].find(item => {
                return this.programme.myScore >= item.min && this.programme.myScore <= item.max;
            });
            this.scoreType = info ? info.value : 'D';
            let score = (this.programme.myScore * 100).toString();

            this.scoreValue = [Number(score.substr(0, 2)), Number(score.substr(2, 1)), Number(score.substr(3, 1))];
        },
        setPerformance(row) {
            this.form.performanceId = row.id;
            this.performance = row;
            this.online = row.online;
            if (this.review) {
                this.online = this.reviewOnline;
            }
        },
        getCode(value) {
            return this.forTree(this.artTypes, value).code;
        },
        forTree(list, value) {
            var result = null;
            if (!list) {
                return;
            }
            for (var i in list) {
                if (result !== null) {
                    break;
                }
                var item = list[i];
                if (item.id == value) {
                    result = item;
                    break;
                } else if (item.children && item.children.length > 0) {
                    result = this.forTree(item.children, value);
                }
            }
            return result;
        }
    }
};
</script>
<style lang="less" scoped>
.right {
    float: right;
}
/deep/.el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
    margin-bottom: 10px;
}
.videoDialog {
    display: flex;
    align-items: center;
    justify-content: center;
    .el-dialog {
        max-width: 900px;
        margin-top: 0px;

        .close {
            position: absolute;
            right: 0px;
            top: -42px;
            width: 71px;
            height: 32px;
            background: #00000015;

            font-size: 12px;
            color: #fdffff;
            line-height: 32px;
            text-align: center;
            cursor: pointer;

            &:hover {
                background: #00000055;
            }
        }
    }
    .el-dialog__header {
        display: none;
    }

    .el-dialog__body {
        padding: 0;

        video {
            display: block;
            height: auto;
            width: 100%;
            outline: none;
        }
    }
}
.scoreTips {
    font-size: 12px;
    color: #606266;
    margin-left: 20px;
}
.score-content {
    padding: 10px 40px;
    .score-list {
        // padding: 5px 10px;
        .number1 {
            width: 130px;
            display: inline-block;
        }
        .number2 {
            width: 90px;
            display: inline-block;
        }
        .tag {
            width: 30px;
            display: inline-block;
            text-align: center;
        }
        .number2 + .number2 {
            margin-left: 5px;
        }
    }
    .score-desc {
        font-size: 12px;
        color: #606266;
        // padding: 0 10px;
        .number1 {
            width: 130px;
            display: inline-block;
            text-align: center;
        }
        .number2 {
            width: 90px;
            display: inline-block;
            text-align: center;
        }
        .number2 + .number2 {
            margin-left: 5px;
        }
        .tag {
            width: 30px;
            display: inline-block;
            text-align: center;
        }
    }
}
</style>
