<template>
    <div class="list-view">
        <div class="filters-container">
            <el-form :model="form" size="mini" inline>
                <el-col :span="24">
                    <el-form-item label="活动名称">
                        <el-select
                            v-model="form.performanceId"
                            clearable
                            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-col>

                <el-form-item>
                    <el-button @click="canEdit = true" type="primary" v-if="!canEdit">编辑</el-button>
                    <el-button @click="saveAward" type="success" v-if="canEdit" :loading="saving">保存</el-button>
                    <el-button @click="canEdit = false" type="warning" v-if="canEdit" :loading="saving">取消</el-button>
                    <el-button @click="saveProgramme" type="primary">批量生成各种奖项</el-button>
                    <el-button @click="resultRow" type="primary">查看节目获奖情况</el-button>
                </el-form-item>
            </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="specialty" label="专业" min-width="80"> </el-table-column>
            <el-table-column prop="programmeNum" label="节目数量" min-width="80"> </el-table-column>
            <el-table-column prop="award" label="奖项" min-width="80"> </el-table-column>
            <el-table-column prop="percentage" label="占比" min-width="100">
                <template slot-scope="{ row }">
                    <span v-if="!canEdit">{{ row.percentage }}</span>
                    <el-input-number
                        v-else
                        v-model="row.percentage"
                        :precision="2"
                        size="mini"
                        label=""
                        :min="0"
                        :max="getMaxPercentage(row)"
                        :step="1"
                        :controls="true"
                        controls-position="both"
                        @change="changePercentage(row)"
                    >
                    </el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="num" label="数量" min-width="100">
                <template slot-scope="{ row }">
                    <span v-if="!canEdit">{{ row.num }}</span>
                    <el-input-number
                        v-else
                        v-model="row.num"
                        size="mini"
                        label=""
                        :min="0"
                        :max="getMax(row)"
                        :step="1"
                        :controls="true"
                        controls-position="both"
                        @change="changeNum(row)"
                    >
                    </el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="120">
                <template slot-scope="{ row }">
                    <span v-if="!canEdit">{{ row.remark }}</span>
                    <el-input v-else size="mini" v-model="row.remark" placeholder="请输入备注" clearable></el-input>
                </template>
            </el-table-column>
            <!-- <el-table-column label="操作" align="center" fixed="right" min-width="150">
                <template slot-scope="{ row }">
                    <el-button @click="editRow(row)" type="primary" size="mini" plain>编辑</el-button>
                    <el-button @click="deleteRow(row)" type="danger" 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>
    </div>
</template>
<script>
import { mapState } from 'vuex';
// import pageableTable from '@/mixins/pageableTable';

export default {
    name: 'ProgrammeAwardList',
    // mixins: [pageableTable],
    data() {
        return {
            multipleMode: false,
            search: '',
            // url: '/programmeAward/getAll',
            downloading: false,
            form: {},
            performances: [],
            tableData: [],
            tableHeight: 200,
            columnKeys: ['specialty', 'programmeNum'],
            canEdit: false,
            saving: false
        };
    },
    created() {
        this.$http
            .post(
                '/performance/all',
                {
                    size: 1000,
                    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();
            })
            .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);
        }
    },
    mounted() {
        this.tableHeight = document.querySelector('.el-table').getBoundingClientRect().height;
    },
    methods: {
        beforeGetData() {
            // return { search: this.search };
        },
        getData() {
            this.$http
                .post('/programmeAward/getAll', {
                    performanceId: this.form.performanceId
                })
                .then(res => {
                    this.tableData = res;
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        },
        toggleMultipleMode(multipleMode) {
            this.multipleMode = multipleMode;
            if (!multipleMode) {
                this.$refs.table.clearSelection();
            }
        },
        resultRow() {
            this.$router.push({
                path: '/programmeResultList',
                query: {
                    ...this.$route.query
                }
            });
        },
        editRow(row) {
            this.$router.push({
                path: '/programmeAwardEdit',
                query: {
                    id: row.id
                }
            });
        },
        download() {
            this.downloading = true;
            this.$axios
                .get('/programmeAward/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(`/programmeAward/del/${row.id}`);
                })
                .then(() => {
                    this.$message.success('删除成功');
                    this.getData();
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        this.$message.error(e.error);
                    }
                });
        },
        backMap(list, key = 'specialty', 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 = ['specialty']) {
            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
                    };
                }
            }
        },
        changePercentage(row) {
            let num = (row.programmeNum * row.percentage) / 100;
            row.num = Math.round(num);
            row.percentage = (row.num / row.programmeNum) * 100;
        },
        changeNum(row) {
            row.percentage = (row.num / row.programmeNum) * 100;
        },
        getMax(row) {
            let list = this.tableData.filter(item => {
                return item.specialty == row.specialty;
            });
            let total = 0;
            list.forEach(item => {
                total += item.num;
            });
            let max = row.programmeNum - total + row.num;
            return max;
        },
        getMaxPercentage(row) {
            let list = this.tableData.filter(item => {
                return item.specialty == row.specialty;
            });
            let total = 0;
            list.forEach(item => {
                total += item.percentage;
            });
            let max = 100 - total + row.percentage;
            return max;
        },
        saveAward() {
            let data = this.tableData;
            this.$http
                .post('/programmeAward/batchSave', 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);
                });
        },
        saveProgramme() {}
    }
};
</script>
<style lang="less" scoped></style>
