<template>
    <div class="list-view">
        <div class="filters-container">
            <el-form :model="form" :rules="rules" size="mini" ref="form" inline label-width="100px">
                <el-form-item label="活动名称" prop="performanceId">
                    <el-select
                        v-model="form.performanceId"
                        filterable
                        placeholder="活动名称"
                        style="width: 300px"
                        @change="getData"
                    >
                        <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 type="primary" @click="intoGroup">查看未分组情况情况</el-button>
                    <el-upload
                        :action="uploadUrl"
                        :before-upload="beforeUpload"
                        :headers="headers"
                        :show-file-list="false"
                        ref="upload"
                        :on-success="onSuccess"
                        class="uploader"
                        :on-error="onfail"
                        :loading="loading"
                        :disabled="loading"
                    >
                        <el-button
                            slot="trigger"
                            type="primary"
                            icon="el-icon-upload2"
                            :loading="loading"
                            :disabled="loading"
                            >导入分组</el-button
                        >
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>
        <el-table
            :data="tableData"
            row-key="id"
            ref="table"
            empty-text="暂无数据"
            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="address" label="活动地点" v-if="!online"> </el-table-column>
            <el-table-column prop="name" label="分组名称" min-width="130"> </el-table-column>
            <el-table-column label="时间安排" min-width="100" v-if="!online">
                <template slot-scope="{ row }"> {{ getTime(row.startTime) }}-{{ getTime(row.endTime) }} </template>
            </el-table-column>
            <el-table-column prop="quantity" label="节目数量"> </el-table-column>
            <el-table-column label="参赛专业">
                <template slot-scope="{ row }">
                    {{ row.specialtyName ? row.specialtyName.join(',') : '' }}
                </template>
            </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="online ? 160 : 320">
                <template slot-scope="{ row }">
                    <el-button
                        @click="editRow(row)"
                        type="primary"
                        size="mini"
                        plain
                        v-if="performance.status == 'ARRANGE' && !online"
                        >编辑</el-button
                    >
                    <el-button @click="assignAExpert(row)" type="primary" 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">
            <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"
                empty-text="暂无数据"
                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="500"
            >
                <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="gradingOrganization" label="考级机构" 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>
        </el-dialog>
        <arrange-log :dialogVisible="isShow" @close="isShow = false" ref="public"></arrange-log>
        <organ-log
            :tableData="tableData"
            :dialogVisible="isJudge"
            @close="isJudge = false"
            ref="publicOrgan"
        ></organ-log>
    </div>
</template>
<script>
import { mapState } from 'vuex';
import pageableTable from '@/mixins/pageableTable';
import ArrangeLog from '../../components/ArrangeLog';
import OrganLog from '../../components/OrganLog';
import { time } from 'echarts';
import delChild from '@/mixins/delChild';
import resolveUrl from 'resolve-url';

export default {
    name: 'JudgeList',
    mixins: [pageableTable, delChild],
    components: { ArrangeLog, OrganLog },
    data() {
        return {
            showMore: false,
            multipleMode: false,
            search: '',
            isShow: false,
            url: '/arrange/all2',
            downloading: false,
            form: {},
            performances: [],
            performance: {},
            addresses: [],
            addressList: [],
            timeRange: [null, null],
            dateRange: '',
            afterTimeRange: [null, null],
            artTypes: [],
            showProgramme: false,
            unGrouped: [],
            competitionGroupOptions: [
                { label: '个人', value: 'SINGLE' },
                { label: '集体', value: 'COLLECTIVE' }
            ],
            times: [3, 5, 10, 15, 20],
            activeNames: [],
            online: false,
            loading: false,
            uploadUrl: '',
            isJudge: false
        };
    },
    watch: {
        timeRange(value) {
            let checked = value.includes(null);
            // console.log(value[0] + ':00');
            this.form.morning = !checked;
            this.$refs.form.validateField('afternoon');
        },
        afterTimeRange(value) {
            let checked = value.includes(null);
            console.log(checked);
            this.form.afternoon = !checked;
        }
    },
    created() {
        this.uploadUrl = resolveUrl(this.$baseUrl, 'arrange/upload');
        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.performance = res.content[0];
                    this.online = this.performance.online;
                    if (this.review) {
                        this.online = this.performance.reviewOnline;
                    }
                    this.getData();
                    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);
            });

        this.$http
            .post('/artType/parent')
            .then(res => {
                if (res.length > 0) {
                    res.forEach(item => {
                        this.artTypes.push({
                            label: item.name,
                            value: item.id
                        });
                    });
                }
            })
            .catch(e => {
                console.log(e);
                this.$message.error(e.error);
            });
    },
    computed: {
        selection() {
            return this.$refs.table.selection.map(i => i.id);
        },
        rules() {
            return {
                performanceId: [{ required: true, message: '请选择活动名称', trigger: 'blur' }],
                address: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
                quantity: [{ required: true, message: '请输入分组节目数量', trigger: 'blur' }],
                duration: [{ required: true, message: '请输入单个节目时长', trigger: 'blur' }],
                morning: [
                    {
                        validator: (rule, value, callback) => {
                            callback();
                        },
                        trigger: 'change'
                    }
                ],
                afternoon: [
                    {
                        validator: (rule, value, callback) => {
                            if (this.form.afternoon || this.form.morning) {
                                callback();
                            } else {
                                callback(new Error('请选择时间安排!'));
                            }
                        },
                        trigger: 'change'
                    }
                ]
            };
        },
        headers() {
            return {
                Authorization: 'Bearer ' + sessionStorage.getItem('token')
            };
        }
    },
    methods: {
        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,
                query: {
                    performanceId: this.form.performanceId
                }
            };
            if (this.review) {
                data.query.auditTimes = this.performance.auditTimes;
            } else {
                data.query.auditTimes = 1;
            }
            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.isShow = true;
            this.$refs.public.init(row.id);
        },
        programme(row) {
            if (this.online) {
                if (this.review) {
                    this.$router.push({
                        path: '/progGroupOnlineList',
                        query: {
                            arid: row.id
                        }
                    });
                } else {
                    this.$router.push({
                        path: '/progGroupOnlineList',
                        query: {
                            aid: row.id
                        }
                    });
                }
            } else {
                if (this.review) {
                    this.$router.push({
                        path: '/programmeGroupList',
                        query: {
                            arid: row.id
                        }
                    });
                } else {
                    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);
                    }
                });
        },
        group() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.submit();
                } else {
                    return false;
                }
            });
        },
        submit() {
            let data = { ...this.form };
            data.startDate = this.dateRange[0];
            data.endDate = this.dateRange[1];
            if (this.timeRange[0] != null || this.timeRange[1] != null) {
                data.morningStartTime = this.timeRange[0] + ':00';
                data.morningEndTime = this.timeRange[1] + ':00';
            }
            if (this.afterTimeRange[0] != null || this.afterTimeRange[1] != null) {
                data.afternoonStartTime = this.afterTimeRange[0] + ':00';
                data.afternoonEndTime = this.afterTimeRange[1] + ':00';
            }
            this.saving = true;
            this.$http
                .post('/arrange/group', data, { body: 'json' })
                .then(res => {
                    this.saving = false;
                    this.$message.success('成功');
                    this.getData();
                })
                .catch(e => {
                    console.log(e);
                    this.saving = false;
                    this.$message.error(e.error);
                });
        },
        submitOffline() {
            let data = { ...this.form };
            this.saving = true;
            this.$http
                .post('/arrange/group', data, { body: 'json' })
                .then(res => {
                    this.saving = false;
                    this.$message.success('成功');
                    this.getData();
                })
                .catch(e => {
                    console.log(e);
                    this.saving = false;
                    this.$message.error(e.error);
                });
        },
        move(index, direction) {
            const start = index;
            const end = direction + index;
            const startInfo = { ...this.tableData[start] };
            const endInfo = { ...this.tableData[end] };
            Promise.all([
                this.$http.post(
                    '/arrange/save',
                    {
                        ...startInfo,
                        startTime: endInfo.startTime,
                        endTime: endInfo.endTime,
                        name: endInfo.name
                    },
                    { body: 'json' }
                ),
                this.$http.post(
                    '/arrange/save',
                    {
                        ...endInfo,
                        startTime: startInfo.startTime,
                        endTime: startInfo.endTime,
                        name: startInfo.name
                    },
                    { body: 'json' }
                )
            ])
                .then(_ => {
                    this.loading = false;
                    this.getData();
                    this.$message.success('成功');
                })
                .catch(e => {
                    console.log(e);
                    this.loading = false;
                    this.$message.error(e.error);
                });
        },
        intoGroup() {
            this.showProgramme = true;
            this.$http
                .post('/programme/unGrouped', { performanceId: this.form.performanceId })
                .then(res => {
                    if (res.length > 0) this.unGrouped = res;
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        },
        clear() {
            this.form = {
                address: '',
                morning: '',
                afternoon: '',
                quantity: '',
                duration: '',
                specialtyId: ''
            };
            this.dateRange = '';
            this.timeRange = [null, null];
            this.afterTimeRange = [null, null];
            this.$nextTick(() => {
                this.$refs.form.resetFields();
            });
        },
        handleChange(val) {},
        publishGroup() {
            this.$alert('发布后分组信息及节目分组情况不能修改，确认要发布么？', '警告', { type: 'error' })
                .then(() => {
                    return this.$http.post(`/arrange/publish`, { performanceId: this.form.performanceId });
                })
                .then(() => {
                    this.$message.success('发布成功');
                    this.getData();
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        this.$message.error(e.error);
                    }
                });
        },
        canEdit() {
            let can = this.performance.status == 'UNDER_REVIEW' || this.performance.status == 'ARRANGE';
            return can;
        },
        upload() {},
        onfail(e) {
            console.log(e);
            this.$message.error('失败:' + e);
            this.loading = false;
            this.getData();
        },
        onSuccess() {
            this.$message.success('上传成功');
            this.loading = false;
            this.getData();
        },
        beforeUpload() {
            return this.$confirm('确认要上传文件吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loading = true;
            });
        },
        assignAExpert(row) {
            this.isJudge = true;
            this.$refs.publicOrgan.init(row.id);
        }
    }
};
</script>
<style lang="less" scoped>
.flex {
    display: flex;
    width: 100%;
    /deep/ .el-form-item__content {
        flex-grow: 1;

        .el-select {
            width: 100%;
        }
    }
}
/deep/ .el-form-item__label {
    width: 150px !important;
}
/deep/ .el-card__body {
    padding: 20px 0 !important;
}
.time {
    width: 120px;
    margin-left: 15px;
    & + .time {
        margin-left: 10px;
    }
}
.uploader {
    display: inline-block;
    margin: 0 10px;
}
</style>
