<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.name" :label="item.remark">
                    <template v-if="item.name!=subColumn">

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

                        <template v-else-if="item.formType=='datetime'">
                            <div class="block">
                                <el-date-picker v-model="formData[item.name]" type="datetime" value-format="timestamp" placeholder="选择时间">
                                </el-date-picker>
                            </div>
                        </template>

                        <template v-else-if="item.formType=='select'">

                            <el-select v-model="formData[item.name]" clearable placeholder="请选择">
                                <el-option v-for="optionItem in selectOptions[item.name]" :key="optionItem" :label="optionItem" :value="optionItem">
                                </el-option>
                            </el-select>

                        </template>

                        <template v-else-if="item.formType=='multiSelect'">
                            <el-select v-model="formData[item.name]" multiple clearable placeholder="请选择">
                                <el-option v-for="optionItem in selectOptions[item.name]" :key="optionItem" :label="optionItem" :value="optionItem">
                                </el-option>
                            </el-select>
                        </template>

                        <single-upload v-else-if="item.formType=='singleImage'" v-model="formData[item.name]"></single-upload>

                        <el-input v-else v-model="formData[item.name]"></el-input>

                    </template>
                    <el-input v-else v-model="formData[item.name]" disabled></el-input>

                </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() {

        if (this.$route.query.column) {
            this.subColumn = this.$route.query.column.split(',')[1];
            this.subValue = this.$route.query.column.split(',')[0];
        }
        this.getTableBase();


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

            },
            rules: {
            },
            tableColumns: [],
            databasetype: 'Mysql',
            tableName: '',
            modules: [],
            dataSourceCode: '',
            subColumn: '',
            subValue: '',
        }
    },
    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 formType = 'singleLineText';

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

                });

                if (!flag) {

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


                }



            }

            var data = {
                formData: JSON.stringify(formDataTemp),
                tableName: this.tableName,
                primaryKey: this.formData.id || this.formData.ID,
                databasetype: this.databasetype,
                dataSourceCode: this.dataSourceCode,
            };
            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,
                        dataSourceCode: this.dataSourceCode,
                    }
                }).then(res => {
                    if (res.success) {

                        this.tableColumns.forEach(element => {
                            if (element.formType == 'multiSelect') {
                                res.data[element.name] = res.data[element.name] ? res.data[element.name].split(',').map(i => String(i)) : [];
                            }

                        });

                        this.formData = res.data;
                        if (this.$route.query.column) {
                            this.formData[this.subColumn] = this.subValue;
                        }
                    }
                })
            } else {
                if (this.$route.query.column) {
                    this.formData[this.subColumn] = this.subValue;
                }
            }



        },
        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.dataSourceCode = res.data.dataSourceCode;
                        this.tableColumns = [];
                        this.rules = {};
                        var columns = JSON.parse(res.data.configJson)
                        columns.forEach(element => {
                            //下拉框选项
                            if (element.optionsValue) {
                                if (element.apiFlag) {

                                    this.$http.get({
                                        url: element.optionsValue.split(',')[0],
                                        data: {}
                                    }).then(res => {
                                        if (res.success) {

                                            var tempOptions = [];
                                            res.data.forEach(item => {
                                                tempOptions.push(item[element.optionsValue.split(',')[1]])
                                            });

                                            this.selectOptions = {
                                                ...this.selectOptions,
                                                [element.name]: tempOptions
                                            };
                                        }
                                    })

                                } else {
                                    this.selectOptions = {
                                        ...this.selectOptions,
                                        [element.name]: element.optionsValue.split(',')
                                    };
                                }
                            }


                            element.show = true;
                            this.tableColumns.push(element);

                            //如果需要验证或必填
                            if (element.required || element.validate) {
                                var tempRule = [];
                                if (element.required) {
                                    tempRule.push({ required: true, message: '请输入 ' + element.remark, trigger: 'blur' })
                                }
                                if (element.validate) {
                                    if (element.maxLength && element.minLength) {
                                        tempRule.push({ min: element.minLength, max: element.maxLength, message: '长度在 ' + element.minLength + '到 ' + element.maxLength + ' 个字符', trigger: 'blur' }, )
                                    }
                                    if (element.min && element.max) {
                                        tempRule.push({
                                            validator: (rule, value, callback) => {
                                                if (value) {
                                                    if (value <= element.max && value >= element.min) {
                                                        callback();
                                                    } else {
                                                        callback(new Error('值在 ' + element.min + ' 到 ' + element.max + ' 之间'));
                                                    }
                                                }
                                            }, trigger: 'blur'
                                        })
                                    }
                                    if (element.validatorType == "phone") {
                                        tempRule.push(formValidator.phone)
                                    }
                                    if (element.validatorType == "number") {
                                        tempRule.push(formValidator.number)
                                    }
                                    if (element.validatorType == "url") {
                                        tempRule.push(formValidator.url)
                                    }
                                    if (element.validatorType == "email") {
                                        tempRule.push(formValidator.email)
                                    }
                                    if (element.validatorType == "idCard") {
                                        tempRule.push(formValidator.idCard)
                                    }
                                    if (element.validatorType == "english") {
                                        tempRule.push(formValidator.english)
                                    }
                                }

                                this.rules[element.name] = tempRule;

                            }

                        });


                        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,
                            dataSourceCode: this.dataSourceCode
                        }
                    })
                }).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>
