<template>
    <div>
        <el-form :model="formData" :rules="rules" ref="form" label-width="80px" label-position="right" size="small" style="max-width: 500px;">

            <template v-for="item in tableColumns">

                <el-form-item :prop="item.value" :label="item.label">
                    <el-input v-if="item.type=='text'" v-model="formData[item.value]"></el-input>

                    <template v-if="item.type=='date'">
                        <div class="block">
                            <el-date-picker v-model="formData[item.value]" type="datetime" placeholder="选择日期">
                            </el-date-picker>
                        </div>
                    </template>

                    <single-upload v-if="item.type=='image'" v-model="formData[item.value]"></single-upload>

                </el-form-item>

            </template>
            <el-form-item>
                <el-button @click="onSave" :loading="$store.state.fetchingData" type="primary">保存</el-button>
                <el-button @click="onDelete" v-if="$route.query.id&&isModulesShow('del')" type="danger">删除</el-button>
                <el-button @click="$router.go(-1)">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import formValidator from '../formValidator'
import { format } from 'date-fns'
import zh from 'date-fns/locale/zh_cn'

export default {
    created() {
        this.getTableBase();


    },
    data() {
        return {
            saving: false,
            formData: {

            },
            rules: {
            },
            tableColumns: [],
            databasetype: 'Mysql',
            tableName: '',
            modules: [],
        }
    },
    methods: {
        onSave() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.submit();
                } else {
                    return false;
                }
            });
        },
        submit() {

            var formDataTemp = JSON.parse(JSON.stringify(this.formData));

            for (var key in formDataTemp) {
                var flag = 0;
                var type = 'text';

                this.tableColumns.forEach(element => {
                    if (element.value == key) {
                        flag = 1;
                        type = element.type;
                    }

                });

                if (!flag) {

                    delete formDataTemp[key];
                } else {
                    if (type == 'date') {
                        formDataTemp[key] = format(formDataTemp[key], 'YYYY/MM/DD HH:mm', { locale: zh });
                    }

                }



            }

            var data = {
                formData: JSON.stringify(formDataTemp),
                tableName: this.tableName,
                primaryKey: this.formData.id || this.formData.ID,
                databasetype: this.databasetype,
            };
            this.$http.post({
                url: this.formData.id || this.formData.ID ? '/commonQuery/update' : '/commonQuery/save',
                data: data
            }).then(res => {
                if (res.success) {
                    this.$message.success('成功');
                    this.$router.go(-1);
                } else {
                    this.$message.warning('失败')
                }
            });
        },
        getData() {
            if (this.$route.query.id) {
                this.$http.get({
                    url: '/commonQuery/one',
                    data: {
                        tableName: this.tableName,
                        primaryKey: this.$route.query.id,
                        databasetype: this.databasetype
                    }
                }).then(res => {
                    if (res.success) {

                        this.tableColumns.forEach(element => {
                            if (element.type == 'date') {
                                res.data[element.value] = new Date(res.data[element.value]);
                            }

                        });

                        this.formData = res.data;
                    }
                })
            }
        },
        getTableBase() {

            this.$http.get({
                url: '/queryConfig/getOne',
                data: {
                    code: this.$route.query.code,
                }
            }).then(res => {
                if (res.success) {


                    if (res.data) {

                        this.modules = res.data.modules.split(',');

                        this.tableName = res.data.tableName;
                        this.databasetype = res.data.databasetype;

                        this.tableColumns = [];
                        var tableColumnsStr = res.data.tablecolumns;

                        var columns = tableColumnsStr.split('_;');


                        columns.forEach(element => {
                            var items = element.split('_,');
                            var temp = {
                                label: items[0],
                                value: items[1],
                                type: items[2] ? items[2] : 'text',
                                show: true
                            }

                            this.tableColumns.push(temp);
                        });


                        this.getData();
                    }

                }
            })
        },

        onDelete() {
            if (this.$route.query.id) {
                this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' }).then(() => {
                    return this.$http.post({
                        url: '/commonQuery/del',
                        data: {
                            tableName: this.tableName,
                            primaryKey: this.$route.query.id,
                            databasetype: this.databasetype
                        }
                    })
                }).then(() => {
                    this.$message.success('删除成功');
                    this.$router.go(-1);
                }).catch(action => {
                    if (action === 'cancel') {
                        this.$message.info('删除取消');
                    } else {
                        this.$message.error('删除失败');
                    }
                })
            }
        },
        isModulesShow(column) {
            var row = this.modules.find(i => i === column);
            return row ? true : false;
        },
    }
}
</script>
<style lang="less" scoped>
</style>
