<template>
    <div class="list-view">
        <div class="filters-container">
            <!-- <el-input placeholder="输入关键字" v-model="search" clearable class="filter-item"></el-input>
            <el-button @click="getData" type="primary" icon="el-icon-search" class="filter-item">搜索 </el-button> -->
            <el-button
                @click="openArrangement"
                type="primary"
                class="filter-item"
                :loading="loading"
                v-if="totalElements > 0"
                >自动编排
            </el-button>
            <el-button @click="distribute('已成功通知')" type="primary" class="filter-item">一键通知 </el-button>
            <!-- <el-button @click="autoAwards()" type="primary" class="filter-item">自动评奖 </el-button> -->
            <!-- <el-button @click="distribute('已生成证书')" type="primary" class="filter-item">生成证书 </el-button> -->
            <!-- <el-button
                @click="download"
                type="primary"
                icon="el-icon-download"
                :loading="downloading"
                class="filter-item"
                >导出EXCEL
            </el-button> -->
        </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="ID" width="100"> </el-table-column> -->
            <el-table-column prop="composition" label="作品名称"> </el-table-column>
            <el-table-column prop="artType" label="专业"> </el-table-column>
            <el-table-column prop="teacher" label="指导老师"> </el-table-column>
            <el-table-column prop="organizer" label="选送机构"> </el-table-column>
            <el-table-column prop="contact" label="联系人"> </el-table-column>
            <el-table-column prop="phone" label="联系电话"> </el-table-column>
            <el-table-column prop="status" label="状态" :formatter="statusFormatter"> </el-table-column>
            <el-table-column label="表演时间" min-width="140">
                <template slot-scope="{ row }">
                    <span v-if="row.showStartTime">{{ row.showStartTime }} 至 {{ row.showEndTime }}</span>
                    <span v-else>暂无</span>
                </template>
            </el-table-column>
            <el-table-column prop="awards" label="奖项">
                <template slot-scope="{ row }">
                    <span v-if="row.awards != null"> {{ row.awards }} </span>
                    <span v-else>暂无</span>
                </template>
            </el-table-column>
            <el-table-column prop="score" label="得分">
                <template slot-scope="{ row }">
                    <el-link v-if="row.score != null" @click="breakdown(row)"> {{ row.score }} </el-link>
                    <span v-else>暂无</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="right" fixed="right" min-width="200">
                <template slot-scope="{ row }">
                    <el-button
                        v-if="row.status === 'PENDING'"
                        :loading="row.loading"
                        @click="audit(row, true)"
                        type="success"
                        size="mini"
                        plain
                    >
                        通过
                    </el-button>
                    <el-button
                        v-if="row.status === 'PENDING'"
                        :loading="row.loading"
                        @click="audit(row, false)"
                        type="warning"
                        size="mini"
                        plain
                    >
                        拒绝
                    </el-button>
                    <el-button @click="editRow(row)" type="primary" size="mini" plain>查看</el-button>
                    <!-- <el-button @click="deleteRow(row)" type="danger" size="mini" plain>删除</el-button> -->
                    <!-- <el-button @click="showDialog(row)" type="primary" size="mini" plain>参演人员维护</el-button>
                    <el-button @click="editRow(row)" type="primary" size="mini" plain>二维码</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="参演人员" :visible.sync="dialogVisible" width="500px" center>
            <div>
                <div v-for="item in person" :key="item.id" style="padding: 10px 10px 10px 100px">
                    <span class="span-size">{{ item.name }}</span> <span class="span-size">{{ item.phone }}</span>
                </div>
                <div style="margin: 10px 170px 0">
                    <el-button class="dia-mar" type="primary" @click="add = true" v-if="!add" size="mini"
                        >添加人员</el-button
                    >
                </div>
                <div v-if="add">
                    <el-form :model="form" ref="form" size="small">
                        <el-input
                            class="dia-mar"
                            v-model="form.name"
                            placeholder="请输入姓名"
                            style="width: 130px"
                        ></el-input>
                        <el-input
                            class="dia-mar"
                            v-model="form.phone"
                            placeholder="请输入手机号"
                            style="width: 160px"
                        ></el-input>
                        <el-button class="dia-mar" size="mini" @click="onSave">确定</el-button>
                        <el-button class="dia-mar" size="mini" @click="add = false">取消</el-button>
                    </el-form>
                </div>
            </div>
        </el-dialog>
        <el-dialog title="自动编排" :visible.sync="dialogArrangement" width="1000px" center>
            <div style="margin-left: 20px;">
                <!-- <img style="width: 500px; heght: 400px;" src="@/assets/arrangement.png" /> -->
                <el-table :data="timeList">
                    <el-table-column prop="composition" label="作品名称" min-width="100"> </el-table-column>
                    <el-table-column prop="artType" label="专业" min-width="100"> </el-table-column>
                    <el-table-column prop="organizer" label="选送机构" min-width="150"> </el-table-column>
                    <el-table-column label="表演时间" show-overflow-tooltip min-width="180">
                        <template slot-scope="{ row }"> {{ row.showStartTime }} 至 {{ row.showEndTime }} </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="{ $index }">
                            <el-button
                                icon="el-icon-top"
                                :disabled="$index == 0"
                                circle
                                @click="move($index, -1)"
                            ></el-button>
                            <el-button
                                icon="el-icon-bottom"
                                :disabled="$index == timeList.length - 1"
                                @click="move($index, 1)"
                                circle
                            ></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="margin-top: 20px; margin-left: 445px;">
                    <el-button type="primary" @click="autoArrangement()">确定</el-button>
                </div>
            </div>
        </el-dialog>
        <el-dialog title="得分详细" :visible.sync="dialogScore" width="450px" center>
            <el-table :data="scoreList">
                <el-table-column prop="createdAt" label="评分时间" min-width="100" align="center"> </el-table-column>
                <el-table-column prop="score" label="分数" min-width="100" align="center"> </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>
<script>
import { mapState } from 'vuex';
import pageableTable from '@/mixins/pageableTable';

export default {
    name: 'PerformanceApplyList',
    mixins: [pageableTable],
    data() {
        return {
            multipleMode: false,
            search: '',
            url: '/performanceApply/all',
            downloading: false,
            statusOptions: [
                { label: '审核中', value: 'PENDING' },
                { label: '通过', value: 'PASS' },
                { label: '拒绝', value: 'DENY' }
            ],
            dialogVisible: false,
            person: [],
            form: {
                performanceApplyId: '',
                name: '',
                value: ''
            },
            add: false,
            loading: false,
            dialogArrangement: false,
            timeList: [],
            dialogScore: false,
            scoreList: []
        };
    },
    computed: {
        selection() {
            return this.$refs.table.selection.map(i => i.id);
        },
        saveOtherJson() {
            const timeList = [...this.timeList].filter(item => {
                return !!item.composition || !!item.showStartTime || !!item.showEndTime || !!item.organizationId;
            });

            return JSON.stringify(timeList);
        }
    },
    methods: {
        statusFormatter(row, column, cellValue, index) {
            let selectedOption = this.statusOptions.find(i => i.value === cellValue);
            if (selectedOption) {
                return selectedOption.label;
            }
            return '';
        },
        beforeGetData() {
            return {
                search: this.search,
                query: {
                    performanceId: Number(this.$route.query.perforId)
                }
            };
        },
        toggleMultipleMode(multipleMode) {
            this.multipleMode = multipleMode;
            if (!multipleMode) {
                this.$refs.table.clearSelection();
            }
        },
        addRow() {
            this.$router.push({
                path: '/performanceApplyEdit',
                query: {
                    ...this.$route.query
                }
            });
        },
        editRow(row) {
            this.$router.push({
                path: '/performanceApplyEdit',
                query: {
                    id: row.id
                }
            });
        },
        download() {
            this.downloading = true;
            this.$axios
                .get('/performanceApply/excel', {
                    responseType: 'blob',
                    params: { size: 10000 }
                })
                .then(res => {
                    console.log(res);
                    this.downloading = false;
                    const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
                    const link = document.createElement('a');
                    link.href = downloadUrl;
                    link.setAttribute('download', res.headers['content-disposition'].split('filename=')[1]);
                    document.body.appendChild(link);
                    link.click();
                    link.remove();
                })
                .catch(e => {
                    console.log(e);
                    this.downloading = false;
                    this.$message.error(e.error);
                });
        },
        operation1() {
            this.$notify({
                title: '提示',
                message: this.selection
            });
        },
        operation2() {
            this.$message('操作2');
        },
        deleteRow(row) {
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
                .then(() => {
                    return this.$http.post(`/performanceApply/del/${row.id}`);
                })
                .then(() => {
                    this.$message.success('删除成功');
                    this.getData();
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        this.$message.error(e.error);
                    }
                });
        },
        showDialog(row) {
            this.dialogVisible = true;
            this.form.performanceApplyId = row.id;
            this.getPerson(row.id);
        },
        getPerson(id) {
            this.$http
                .post('/person/all', { size: 100, query: { del: false, performanceApplyId: id } }, { body: 'json' })
                .then(res => {
                    this.person = res.content;
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        },
        audit(row, pass) {
            this.$set(row, 'loading', true);
            this.$http
                .post('/performanceApply/audit', {
                    id: row.id,
                    pass: pass
                })
                .then(res => {
                    this.$set(row, 'loading', false);
                    this.$message.success('OK');
                    this.getData();
                })
                .catch(e => {
                    console.log(e);
                    this.$set(row, 'loading', false);
                    this.$message.error(e.error);
                });
        },
        distribute(content) {
            this.$alert(content, '通知', {
                confirmButtonText: '确定'
            });
        },
        autoArrangement() {
            this.loading = true;
            this.$http
                .post('/performanceApply/saveArrangement', {
                    applies: this.saveOtherJson
                })
                .then(res => {
                    this.loading = false;
                    this.$message.success('自动编排成功');
                    this.getData();
                    this.dialogArrangement = false;
                })
                .catch(e => {
                    console.log(e);
                    this.loading = false;
                    this.$message.error(e.error);
                });
        },
        autoAwards() {
            this.$confirm('是否进行自动评奖', '评奖', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            })
                .then(() => {
                    this.$http
                        .post('/performanceApply/autoAwards', {
                            performanceId: Number(this.$route.query.perforId)
                        })
                        .then(res => {
                            this.loading = false;
                            this.$message.success('OK');
                            this.getData();
                        })
                        .catch(e => {
                            console.log(e);
                            this.loading = false;
                            this.$message.error(e.error);
                        });
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
        },
        getArrangement() {
            this.loading = true;
            this.$http
                .post('/performanceApply/autoArrangement', {
                    performanceId: Number(this.$route.query.perforId)
                })
                .then(res => {
                    this.loading = false;
                    this.timeList = res;
                })
                .catch(e => {
                    console.log(e);
                    this.loading = false;
                    this.$message.error(e.error);
                });
        },
        openArrangement() {
            this.dialogArrangement = true;
            this.getArrangement();
        },
        move(index, direction) {
            let timeList = [...this.timeList];
            const start = index;
            const end = direction + index;

            const startInfo = {
                showStartTime: timeList[end].showStartTime,
                showEndTime: timeList[end].showEndTime
            };
            const endInfo = {
                showStartTime: timeList[start].showStartTime,
                showEndTime: timeList[start].showEndTime
            };

            timeList[start] = {
                ...timeList[start],
                ...startInfo
            };

            timeList[end] = {
                ...timeList[end],
                ...endInfo
            };

            this.timeList = this.sortByKey(timeList);
        },
        sortByKey(array) {
            return array.sort(function(a, b) {
                var x = a['showStartTime'];
                var y = b['showStartTime'];
                return x < y ? -1 : x > y ? 1 : 0;
            });
        },
        // 打分明细
        breakdown(row) {
            this.dialogScore = true;
            this.$http
                .post('/performanceScore/breakdown', {
                    performanceApplyId: row.id
                })
                .then(res => {
                    this.scoreList = res;
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        }
    }
};
</script>
<style lang="less" scoped>
.dia-mar {
    margin: 8px 6px;
}
.span-size {
    margin: 20px;
    font-size: 15px;
}
.right {
    margin-right: 60px;
}
</style>
