<template>
    <div class="list-view">
        <div class="filters-container">
            <el-form :model="form" size="mini" ref="form" inline label-width="120px">
                <el-form-item label="活动名称" prop="performanceId">
                    <el-select
                        v-model="form.performanceId"
                        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-card shadow="hover" :body-style="{ padding: '20px' }" style="margin-bottom: 20px">
                    <el-row :gutter="15">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="活动日期" prop="dateRange">
                                <el-date-picker
                                    v-model="dateRange"
                                    value-format="yyyy-MM-dd"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    style="width: 316px"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="address" class="flex" label="活动地点" style="width: 100%">
                                <el-select v-model="form.address">
                                    <el-option
                                        v-for="(item, index) in addresses"
                                        :key="index"
                                        :value="item.value"
                                        :label="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item label="时间安排" prop="morning">
                                <el-checkbox v-model="form.morning">上午</el-checkbox>
                                <el-checkbox v-model="form.afternoon">下午</el-checkbox>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item style="margin-left: 40px">
                        <el-button type="primary" @click="getData">查询</el-button>
                    </el-form-item>
                </el-card>
            </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"
            :span-method="objectSpanMethod"
        >
            <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="date" label="活动日期"> </el-table-column>
            <el-table-column prop="morning" label="活动时间">
                <template slot-scope="{ row }">
                    {{ row.morning ? '上午' : '下午' }}
                </template>
            </el-table-column>
            <el-table-column prop="address" label="活动地点"> </el-table-column>
            <el-table-column label="参赛专业">
                <template slot-scope="{ row }">
                    {{ row.specialtyName ? row.specialtyName.join(',') : '' }}
                </template>
            </el-table-column>
            <el-table-column prop="name" label="分组名称" min-width="130"> </el-table-column>
            <el-table-column label="评审专家" min-width="130" prop="experts"> </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" min-width="320">
                <template slot-scope="{ row }">
                    <el-button @click="assignExpert(row)" type="primary" size="mini" plain>分配评委</el-button>
                    <el-button @click="cancelAssign(row)" type="warning" size="mini" plain>取消分配</el-button>
                    <el-button @click="programme(row)" 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 :visible.sync="showProgramme" width="80%" title="未分组节目" center>
            <el-table
                :data="unGrouped"
                row-key="id"
                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="300"
            >
                <el-table-column prop="name" label="节目名称"> </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="level" label="参赛级别" min-width="70"> </el-table-column>
                <el-table-column prop="durationOfWork" label="作品时长" min-width="70"> </el-table-column>
                <el-table-column prop="quantity" label="参赛人数" min-width="70"> </el-table-column>
                <el-table-column prop="contact" label="联系人" min-width="68"> </el-table-column>
                <el-table-column prop="phone" label="联系电话" min-width="95"> </el-table-column>
                <el-table-column prop="gradingOrganization" label="考级机构" show-overflow-tooltip min-width="160">
                </el-table-column>
                <el-table-column prop="organization" label="承办单位" min-width="160"> </el-table-column>
                <el-table-column prop="examPoint" label="考级点"> </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="{ row }">
                        <el-button @click="choose(row)" size="mini" type="primary">增加</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>
<script>
import { mapState } from 'vuex';
import pageableTable from '@/mixins/pageableTable';
import delChild from '@/mixins/delChild';

export default {
    name: 'ArrangeJudgeList',
    mixins: [pageableTable, delChild],
    data() {
        return {
            multipleMode: false,
            search: '',
            url: '/arrange/all2',
            downloading: false,
            form: {},
            performances: [],
            addresses: [],
            dateRange: '',
            rules: {
                performanceId: [{ required: true, message: '请选择活动名称', trigger: 'blur' }],
                address: [{ required: true, message: '请选择活动地点', trigger: 'blur' }],
                quantity: [{ required: true, message: '请输入分组节目数量', trigger: 'blur' }],
                duration: [{ required: true, message: '请输入单个节目时长', trigger: 'blur' }]
            },
            showProgramme: false,
            unGrouped: [],
            competitionGroupOptions: [
                { label: '个人', value: 'SINGLE' },
                { label: '集体', value: 'COLLECTIVE' }
            ],
            columnKeys: ['date', 'morning', 'address'],
            addressList: []
        };
    },
    created() {
        this.$http
            .post(
                '/performance/all',
                {
                    size: 100,
                    sort: 'year,desc',
                    query: {
                        publish: true
                    }
                },
                { body: 'json' }
            )
            .then(res => {
                if (res.content.length > 0) {
                    res.content.forEach(item => {
                        this.performances.push({
                            label: item.name,
                            value: item.id
                        });
                    });
                    // this.form.performanceId = res.content[0].id;
                    this.$http
                        .post(
                            '/performanceSchedule/all',
                            { size: 100, query: { performanceId: this.form.performanceId } },
                            { body: 'json' }
                        )
                        .then(res => {
                            if (res.content.length > 0) {
                                res.content.forEach(item => {
                                    this.addressList.push({
                                        value: item.address,
                                        pid: item.performanceId
                                    });
                                });
                            }
                        })
                        .catch(e => {
                            console.log(e);
                            this.$message.error(e.error);
                        });
                }
            })
            .catch(e => {
                console.log(e);
                this.$message.error(e.error);
            });
    },
    computed: {
        selection() {
            return this.$refs.table.selection.map(i => i.id);
        },
        showTable() {
            return this.backMap(this.tableData);
        }
    },
    methods: {
        backMap(list, key = 'date', preActive = 0, keys = ['date', 'morning', 'address']) {
            let _map = new Map();
            list.forEach((item, index) => {
                let info = {
                    active: index + preActive,
                    childNum: 1,
                    list: []
                };
                let 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 = keys.indexOf(key);
            if (keyIndex !== keys.length - 1) {
                [..._map.keys()].forEach(item => {
                    let info = _map.get(item);
                    let childMap = this.backMap(info.list, keys[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;
        },
        competitionGroupFormatter(row, column, cellValue, index) {
            let selectedOption = this.competitionGroupOptions.find(i => i.value === cellValue);
            if (selectedOption) {
                return selectedOption.label;
            }
            return '';
        },
        beforeGetData() {
            let data = {
                search: this.search,
                sort: 'date,asc;startTime,asc',
                query: { performanceId: this.form.performanceId }
            };
            if (this.form.address) {
                data.query.address = this.form.address;
            }
            if (this.dateRange) {
                data.query.date = this.dateRange[0] + ',' + this.dateRange[1];
            }
            if (this.form.morning && !this.form.afternoon) {
                data.query.morning = true;
            } else if (this.form.afternoon && !this.form.morning) {
                data.query.morning = false;
            }
            return data;
        },
        toggleMultipleMode(multipleMode) {
            this.multipleMode = multipleMode;
            if (!multipleMode) {
                this.$refs.table.clearSelection();
            }
        },
        addRow() {
            this.$router.push({
                path: '/arrangeEdit',
                query: {
                    ...this.$route.query
                }
            });
        },
        editRow(row) {
            this.$router.push({
                path: '/arrangeEdit',
                query: {
                    id: row.id
                }
            });
        },
        assignExpert(row) {
            let keys = [...this.columnKeys].slice(0, 3).map(item => {
                return row[item];
            });
            let info = this.getInfo(this.showTable, keys);
            let aid = info.list.map(item => {
                return item.id;
            });
            this.$router.push({
                path: '/arrangeAssignExpert',
                query: {
                    aid: aid.join(',')
                }
            });
        },
        programme(row) {
            this.$router.push({
                path: '/programmeGroupList',
                query: {
                    aid: row.id
                }
            });
        },
        download() {
            this.downloading = true;
            this.$axios
                .get('/arrange/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(`/arrange/del/${row.id}`);
                })
                .then(() => {
                    this.$message.success('删除成功');
                    this.getData();
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        this.$message.error(e.error);
                    }
                });
        },
        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
                    };
                }
            }
        },
        cancelAssign(row) {
            console.log(row);
            // this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
            //     .then(() => {
            //         return this.$http.post(`/arrange/del/${row.id}`);
            //     })
            //     .then(() => {
            //         this.$message.success('删除成功');
            //         this.getData();
            //     })
            //     .catch(e => {
            //         if (e !== 'cancel') {
            //             this.$message.error(e.error);
            //         }
            //     });
        }
    }
};
</script>
<style lang="less" scoped></style>
