<template>
    <div class="list-view">
        <div class="filters-container">
            <el-form :model="form" :rules="rules" 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-form-item>
                    <el-button type="primary" @click="getData">查看活动分组情况</el-button>
                    <el-button type="primary" @click="intoGroup">查看未分组情况情况</el-button>
                </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">
                            <el-form-item label="时间安排" prop="morning">
                                <el-checkbox v-model="form.morning" disabled>上午</el-checkbox>
                                <el-time-select
                                    placeholder="起始时间"
                                    format="HH:mm"
                                    value-format="HH:mm:ss"
                                    v-model="timeRange[0]"
                                    :picker-options="{
                                        start: '08:30',
                                        step: '00:15',
                                        end: '12:00'
                                    }"
                                    class="time"
                                >
                                </el-time-select>
                                <el-time-select
                                    placeholder="结束时间"
                                    v-model="timeRange[1]"
                                    :picker-options="{
                                        start: '08:30',
                                        step: '00:15',
                                        end: '12:00',
                                        minTime: timeRange[0]
                                    }"
                                    class="time"
                                >
                                </el-time-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6" :offset="0">
                            <el-form-item class="flex" label="分组节目数量" prop="quantity">
                                <!-- <el-input-number type="number" v-model="form.quantity"></el-input-number> -->
                                <el-select v-model="form.quantity" clearable>
                                    <el-option v-for="item in nums" :key="item" :label="item" :value="item"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" :offset="0">
                            <el-form-item class="flex" label="单个节目时长" prop="duration">
                                <!-- <el-input-number type="number" v-model="form.duration"></el-input-number> -->
                                <el-select v-model="form.duration" clearable>
                                    <el-option
                                        v-for="item in times"
                                        :key="item"
                                        :label="item"
                                        :value="item"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item label=" " prop="afternoon">
                                <el-checkbox v-model="form.afternoon" disabled>下午</el-checkbox>

                                <el-time-select
                                    placeholder="起始时间"
                                    format="HH:mm"
                                    value-format="HH:mm:ss"
                                    v-model="afterTimeRange[0]"
                                    :picker-options="{
                                        start: '13:00',
                                        step: '00:15',
                                        end: '18:00'
                                    }"
                                    class="time"
                                >
                                </el-time-select>
                                <el-time-select
                                    placeholder="结束时间"
                                    v-model="afterTimeRange[1]"
                                    :picker-options="{
                                        start: '13:00',
                                        step: '00:15',
                                        end: '18:00',
                                        minTime: afterTimeRange[0]
                                    }"
                                    class="time"
                                >
                                </el-time-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" :offset="0">
                            <el-form-item label="参赛专业" class="flex" prop="specialtyId">
                                <el-select v-model="form.specialtyId" multiple>
                                    <el-option
                                        v-for="item in artTypes"
                                        :key="item.value"
                                        :value="item.value"
                                        :label="item.label"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item style="margin-left: 40px">
                        <el-button type="primary" @click="clear">清空</el-button>
                        <el-button type="primary" @click="group">节目分组</el-button>
                        <el-button type="primary">发布分组安排</el-button>
                        <el-button type="primary">导出分组安排</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"
        >
            <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="address" label="活动地点"> </el-table-column>
            <el-table-column prop="name" label="分组名称" min-width="130"> </el-table-column>
            <el-table-column label="时间安排" min-width="100">
                <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 prop="duration" 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="writerDirector" label="编导姓名"> </el-table-column>
            <el-table-column prop="phone" label="联系电话"> </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" min-width="320">
                <template slot-scope="{ row, $index }">
                    <el-button @click="editRow(row)" type="primary" size="mini" plain>编辑</el-button>
                    <el-button @click="programme(row)" size="mini" plain>查看节目</el-button>
                    <!-- <el-button @click="editRow(row)" type="warning" size="mini" plain>上移</el-button>
                    <el-button @click="editRow(row)" type="warning" size="mini" plain>下移</el-button> -->

                    <el-button @click="move($index, -1)" :disabled="$index == 0" type="success" size="mini" plain
                        >上移</el-button
                    >
                    <el-button
                        @click="move($index, 1)"
                        :disabled="(page - 1) * pageSize + $index == totalElements - 1"
                        type="warning"
                        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="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="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>
        </el-dialog>
    </div>
</template>
<script>
import { mapState } from 'vuex';
import pageableTable from '@/mixins/pageableTable';
import { time } from 'echarts';
import delChild from '@/mixins/delChild';

export default {
    name: 'ArrangeList',
    mixins: [pageableTable, delChild],
    data() {
        return {
            multipleMode: false,
            search: '',
            url: '/arrange/all',
            downloading: false,
            form: {},
            performances: [],
            addresses: [],
            addressList: [],
            timeRange: [null, null],
            dateRange: '',
            afterTimeRange: [null, null],
            artTypes: [],
            showProgramme: false,
            unGrouped: [],
            competitionGroupOptions: [
                { label: '个人', value: 'SINGLE' },
                { label: '集体', value: 'COLLECTIVE' }
            ],
            nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            times: [3, 5, 10, 15, 20]
        };
    },
    watch: {
        timeRange(value) {
            let checked = value.includes(null);
            console.log(checked);
            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.$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.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'
                    }
                ]
            };
        }
    },
    methods: {
        competitionGroupFormatter(row, column, cellValue, index) {
            let selectedOption = this.competitionGroupOptions.find(i => i.value === cellValue);
            if (selectedOption) {
                return selectedOption.label;
            }
            return '';
        },
        beforeGetData() {
            return {
                search: this.search,
                sort: 'date,asc;startTime,asc',
                query: {
                    performanceId: this.form.performanceId
                }
            };
        },
        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
                }
            });
        },
        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);
                    }
                });
        },
        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];
            data.morningStartTime = this.timeRange[0];
            data.morningEndTime = this.timeRange[1];
            data.afternoonStartTime = this.afterTimeRange[0];
            data.afternoonEndTime = this.afterTimeRange[1];

            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 => {
                    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();
            });
        }
    }
};
</script>
<style lang="less" scoped>
.flex {
    display: flex;
    width: 100%;
    /deep/ .el-form-item__content {
        flex-grow: 1;

        .el-select {
            width: 100%;
        }
    }
}
.time {
    width: 120px;
    margin-left: 15px;
    & + .time {
        margin-left: 10px;
    }
}
</style>
