<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="editRow()" type="primary" icon="el-icon-plus"
                       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="context" label="内容"
            >
            </el-table-column>
            <el-table-column prop="type" label="类型"
                             :formatter="typeFormatter"
            >
            </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>

        <el-dialog :visible.sync="showDialog" width="320px">
            <el-form :model="formData" :rules="rules" ref="form" label-width="52px" label-position="right" size="small">
                <el-form-item prop="context" label="内容">
                    <el-input v-model="formData.context" style="width: 192px"></el-input>
                </el-form-item>
                <el-form-item prop="type" label="类型">
                    <el-select v-model="formData.type"
                               placeholder="请选择" value-key="name">
                        <el-option v-for="item in typeOptions" :label="item.label" :value="item.value"
                                   :key="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button type="primary" size="mini" @click="save" :loading="saving">保存</el-button>
            </span>
        </el-dialog>

    </div>
</template>
<script>
    import {mapState} from "vuex";
    import pageableTable from "@/mixins/pageableTable";

    export default {
        name: 'ChatWordsList',
        mixins: [pageableTable],
        created() {
            this.getData();
        },
        data() {
            return {
                multipleMode: false,
                search: "",
                url: "/chatWords/all",
                downloading: false,
                typeOptions: [{label: "商家话术", value: 0},
                    {label: "骑手话术", value: 1}],
                formData: {
                    type: '',
                    context: ''
                },
                rules: {
                    context: [
                        {required: true, message: '请输入内容(不超过9个字)', trigger: 'blur'},
                    ],
                    type: [
                        {required: true, message: '请选择类型', trigger: 'blur'},
                    ],
                },
                showDialog: false,
                saving: false
            }
        },
        computed: {
            selection() {
                return this.$refs.table.selection.map(i => i.id);
            }
        },
        methods: {
            typeFormatter(row, column, cellValue, index) {
                let selectedOption = this.typeOptions.find(i => i.value === cellValue);
                if (selectedOption) {
                    return selectedOption.label;
                }
                return '';
            },
            beforeGetData() {
                if (this.search) {
                    return {search: this.search};
                }
            },
            toggleMultipleMode(multipleMode) {
                this.multipleMode = multipleMode;
                if (!multipleMode) {
                    this.$refs.table.clearSelection();
                }
            },
            /*  addRow() {
                  this.$router.push({
                      path: "/chatWordsEdit",
                      query: {
                          ...this.$route.query
                      }
                  });
              },*/
            /*editRow(row) {
                this.$router.push({
                    path: "/chatWordsEdit",
                    query: {
                        id: row.id
                    }
                });
            },*/
            editRow(row) {
                if (!row) {
                    row = {
                        context: '',
                        type: '',
                    };
                }
                this.formData = row;
                this.showDialog = true;
            },
            download() {
                this.downloading = true;
                this.$axios
                    .get("/chatWords/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(`/chatWords/del/${row.id}`)
                }).then(() => {
                    this.$message.success('删除成功');
                    this.getData();
                }).catch(action => {
                    if (action === 'cancel') {
                        this.$message.info('删除取消');
                    } else {
                        this.$message.error('删除失败');
                    }
                })
            },
            save() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        let data = {...this.formData};
                        this.saving = true;
                        this.$http
                            .post('/chatWords/save', data, {body: 'json'})
                            .then(res => {
                                this.saving = false;
                                this.$message.success('成功');
                                this.showDialog = false;
                                this.getData();
                            })
                            .catch(e => {
                                console.log(e);
                                this.saving = false;
                                this.showDialog = false;
                                this.$message.error(e.error);
                            });
                    } else {
                        return false;
                    }
                });
            }
        }
    }
</script>
<style lang="less" scoped>
</style>
