<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="filterList"
            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 prop="name" label="名称"> </el-table-column>
            <el-table-column prop="desc" label="描述"> </el-table-column>
            <el-table-column prop="type" label="类型" :formatter="typeFormatter"></el-table-column>
            <el-table-column prop="value" label="值" show-overflow-tooltip> </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" width="150">
                <template slot-scope="{ row }">
                    <el-button @click="editRow(row, true)" type="primary" size="mini" plain>编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-wrapper"></div>

        <el-dialog :visible.sync="showDialog" width="500px" title="编辑设置" :close-on-click-modal="false">
            <el-form :model="formData" :rules="rules" ref="form" label-width="52px" label-position="right" size="small">
                <el-form-item prop="name" label="名称">
                    <el-input v-model="formData.name" :disabled="edit === true"></el-input>
                </el-form-item>
                <el-form-item prop="desc" label="描述">
                    <el-input v-model="formData.desc"></el-input>
                </el-form-item>
                <el-form-item prop="type" label="类型">
                    <el-select v-model="formData.type" placeholder="请选择" :disabled="edit === true">
                        <el-option
                            v-for="item in valueTypes"
                            :label="item.label"
                            :value="item.value"
                            :key="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="value" label="值">
                    <el-input v-model="formData.value" v-if="formData.type === 'STRING'"></el-input>
                    <el-date-picker
                        v-model="formData.value"
                        v-if="formData.type === 'DATETIME'"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择日期时间"
                    ></el-date-picker>
                    <el-date-picker
                        v-model="formData.value"
                        v-if="formData.type === 'DATE'"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择日期"
                    ></el-date-picker>
                    <el-time-picker
                        v-model="formData.value"
                        v-if="formData.type === 'TIME'"
                        value-format="HH:mm"
                        placeholder="请选择时间"
                        arrow-control
                    ></el-time-picker>
                    <el-switch
                        v-model="formData.value"
                        v-if="formData.type === 'BOOLEAN'"
                        active-text="是"
                        inactive-text="否"
                        active-value="1"
                        inactive-value="0"
                    ></el-switch>
                    <el-select v-if="formData.type === 'SELECT'" v-model="formData.value">
                        <el-option
                            v-for="item in formData.options.split(',')"
                            :key="item"
                            :label="item"
                            :value="item"
                        ></el-option>
                    </el-select>
                    <el-input-number v-model="formData.value" v-if="formData.type === 'NUMBER'"></el-input-number>
                    <file-upload v-model="formData.value" v-if="formData.type === 'FILE'" :limit="1"></file-upload>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button type="primary" size="mini" @click="save" :loading="saving">保存</el-button>
            </span>
        </el-dialog>

        <el-dialog title="支付选项" :visible.sync="showPayConfigDialog" width="800px">
            <div class="pay-config-item-list">
                <div class="pay-config-item head">
                    <div class="key">KEY</div>
                    <div class="name">名称</div>
                    <div class="icon">图标</div>
                    <div class="show">显示</div>
                    <div class="enabled">可用</div>
                    <div class="sort">排序</div>
                </div>
                <div class="pay-config-item" v-for="item in payConfig">
                    <div class="key">
                        <el-input v-model="item.key" size="mini"></el-input>
                    </div>
                    <div class="name">
                        <el-input v-model="item.name" size="mini"></el-input>
                    </div>
                    <div class="icon">
                        <el-image
                            @click="addIcon(item)"
                            :src="item.icon"
                            v-if="item.icon"
                            fit="contain"
                            style="width: 26px; height: 26px"
                        ></el-image>
                        <el-button v-else type="text" @click="addIcon(item)">上传</el-button>
                    </div>
                    <div class="show">
                        <el-checkbox v-model="item.show"></el-checkbox>
                    </div>
                    <div class="enabled">
                        <el-checkbox v-model="item.enabled"></el-checkbox>
                    </div>
                    <div class="sort">
                        <el-input-number v-model="item.sort" :controls="false"></el-input-number>
                    </div>
                </div>
            </div>
            <el-button @click="addPayConfig" size="mini">添加 </el-button>
            <div slot="footer">
                <el-button @click="showPayConfigDialog = false" size="mini">取消</el-button>
                <el-button @click="savePayConfig" size="mini" type="primary" :loading="saving">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { mapState } from 'vuex';
import pageableTable from '@/mixins/pageableTable';

export default {
    name: 'SysConfigList',
    mixins: [pageableTable],
    data() {
        return {
            multipleMode: false,
            search: '',
            url: '/sysConfig/all',
            downloading: false,
            formData: {
                name: '',
                desc: '',
                value: '',
                type: 'STRING'
            },
            rules: {
                name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
                desc: [{ required: true, message: '请输入描述', trigger: 'blur' }],
                type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
                value: [{ required: true, message: '请输入值', trigger: 'blur' }]
            },
            showDialog: false,
            saving: false,
            edit: false,
            sortStr: 'createdAt,desc',
            valueTypes: [
                {
                    label: '字符串',
                    value: 'STRING'
                },
                {
                    label: '日期时间',
                    value: 'DATETIME'
                },
                {
                    label: '日期',
                    value: 'DATE'
                },
                {
                    label: '时间',
                    value: 'TIME'
                },
                {
                    label: '开关',
                    value: 'BOOLEAN'
                },
                {
                    label: '数字',
                    value: 'NUMBER'
                },
                {
                    label: '文件',
                    value: 'FILE'
                },
                {
                    label: '选择',
                    value: 'SELECT'
                }
            ],
            htmlContents: [''],
            showPayConfigDialog: false,
            payConfig: []
        };
    },
    computed: {
        selection() {
            return this.$refs.table.selection.map(i => i.id);
        },
        filterList() {
            if (this.search) {
                return this.tableData.filter(i => i.name.indexOf(this.search) > -1 || i.desc.indexOf(this.search) > -1);
            } else {
                return this.tableData;
            }
        }
    },
    methods: {
        beforeGetData() {
            return { sort: 'createdAt,desc', size: 10000 };
        },
        toggleMultipleMode(multipleMode) {
            this.multipleMode = multipleMode;
            if (!multipleMode) {
                this.$refs.table.clearSelection();
            }
        },
        addRow() {
            this.$router.push({
                path: '/sysConfigEdit',
                query: {
                    ...this.$route.query
                }
            });
        },
        editRow(row, edit) {
            if (row && row.name === 'pay_config') {
                if (row.value) {
                    this.payConfig = JSON.parse(row.value).sort((a, b) => {
                        return a.sort - b.sort;
                    });
                }
                this.formData = { ...row };
                this.showPayConfigDialog = true;
                return;
            }
            this.edit = edit;
            if (!row) {
                row = {
                    name: '',
                    desc: '',
                    value: '',
                    type: null
                };
            }
            this.formData = { ...row };
            this.showDialog = true;
        },
        download() {
            this.downloading = true;
            this.$axios
                .get('/sysConfig/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);
                });
        },
        save() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    let data = { ...this.formData };
                    this.saving = true;
                    this.$http
                        .post('/sysConfig/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;
                }
            });
        },
        typeFormatter(row, cell, cellValue) {
            let item = this.valueTypes.find(i => i.value === cellValue);
            return item ? item.label : '';
        },
        addPayConfig() {
            this.payConfig.push({
                name: '',
                icon: '',
                show: false,
                enabled: false,
                description: '',
                sort: 0
            });
        },
        savePayConfig() {
            let data = { ...this.formData, value: JSON.stringify(this.payConfig) };
            this.saving = true;
            this.$http
                .post('/sysConfig/save', data, { body: 'json' })
                .then(res => {
                    this.saving = false;
                    this.$message.success('成功');
                    this.showPayConfigDialog = false;
                    this.getData();
                })
                .catch(e => {
                    console.log(e);
                    this.saving = false;
                    this.showPayConfigDialog = false;
                    this.$message.error(e.error);
                });
        },
        addIcon(item) {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/*';
            input.onchange = e => {
                console.log(input.files[0]);
                let form = new FormData();
                form.append('file', input.files[0]);
                this.$axios.post('/upload/file', form).then(res => {
                    this.$set(item, 'icon', res.data);
                });
            };
            input.click();
        }
    }
};
</script>
<style lang="less" scoped>
.pay-config-item-list {
    .pay-config-item {
        margin-bottom: 6px;
        .flex();
        font-size: 14px;
        .key {
            width: 150px;
        }
        .name {
            margin-left: 20px;
            width: 150px;
        }
        .icon {
            width: 50px;
            margin-left: 10px;
            font-size: 0;
            text-align: center;
        }
        .show {
            width: 50px;
            margin-left: 10px;
            text-align: center;
        }
        .enabled {
            width: 50px;
            margin-left: 10px;
            text-align: center;
        }
        .sort {
            width: 80px;
            margin-left: 10px;
            text-align: center;
            .el-input-number {
                width: 60px;
            }
        }
        &.head {
            .icon {
                font-size: 14px;
            }
        }
    }
}
</style>
