<template>
    <div>
        <el-form :model="formData" :rules="rules" ref="form" label-width="80px" label-position="right" size="small">
            <el-form-item prop="databasetype" label="库类型">
                <el-select placeholder="库类型" size="small" v-model="formData.databasetype" @change="changeDataBaseType" class="filter-item">
                    <el-option label="Mysql" value="Mysql">
                    </el-option>
                    <el-option label="SqlServer" value="SqlServer">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item prop="dataSourceCode" label="数据库">

                <el-select placeholder="数据库" size="small" v-model="formData.dataSourceCode" @change="changeDataSourceCode" class="filter-item">
                    <el-option v-for="item in datasourceInfoList" :label="item.databaseName" :value="item.code" :key="item.code"></el-option>
                </el-select>

            </el-form-item>

            <el-form-item prop="tableName" label="表名">

                <el-select placeholder="表名" size="small" clearable filterable v-model="formData.tableName" @change="changeTableName" class="filter-item">
                    <el-option v-for="item in tableList" :label="item" :value="item" :key="item"></el-option>
                </el-select>

            </el-form-item>

            <el-form-item prop="code" label="code" style="width:300px;">
                <el-input v-model="formData.code"></el-input>
            </el-form-item>

            <el-form-item prop="typeFlag" label="分类" style="width:300px;">
                <el-input v-model="formData.typeFlag"></el-input>
            </el-form-item>

            <el-form-item prop="modules" label="功能">
                <el-select placeholder="modules" size="small" multiple v-model="formData.modules" class="filter-item">
                    <el-option label="搜索" value="search">
                    </el-option>
                    <el-option label="高级搜索" value="query">
                    </el-option>
                    <el-option label="添加" value="add">
                    </el-option>
                    <el-option label="编辑" value="edit">
                    </el-option>
                    <el-option label="删除" value="del">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item prop="tablecolumns" label="字段">
                <el-tabs value="1" type="border-card">
                    <el-tab-pane label="字段" name="1">

                        <el-table :data="tablecolumnsFields">

                            <el-table-column prop="value" label="字段" width="150" align="center">
                                <template slot-scope="{row}">
                                    <el-input v-model="row.name"></el-input>
                                </template>
                            </el-table-column>

                            <el-table-column prop="remark" label="显示" width="150" align="center">
                                <template slot-scope="{row}">
                                    <el-input v-model="row.remark"></el-input>
                                </template>
                            </el-table-column>

                            <el-table-column prop="formType" label="类型" width="150" align="center">
                                <template slot-scope="{row}">
                                    <el-select v-model="row.formType">
                                        <el-option v-for="item in columnTypes" :label="item.label" :value="item.value" :key="item.value"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column prop="apiFlag" label="接口" width="50" align="center">
                                <template slot-scope="{row}">
                                    <el-checkbox v-model="row.apiFlag" :disabled="row.formType!='select'&&row.formType!='multiSelect'"></el-checkbox>
                                </template>
                            </el-table-column>
                            <el-table-column prop="optionsValue" label="选项" min-width="150" align="center">
                                <template slot-scope="{row}">
                                    <el-input type="textarea" v-model="row.optionsValue" :disabled="row.formType!='select'&&row.formType!='multiSelect'"></el-input>
                                </template>
                            </el-table-column>

                            <el-table-column width="60" align="center">
                                <template slot-scope="{ row, column, $index }">
                                    <el-button @click="removeField($index)" size="small" type="text">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-button @click="addField" type="text" icon="el-icon-plus">添加</el-button>
                    </el-tab-pane>
                    <el-tab-pane label="表单校验" name="2">
                        <el-table :data="tablecolumnsFields">

                            <el-table-column prop="name" label="字段" width="150" align="center">
                            </el-table-column>

                            <el-table-column prop="remark" label="显示" width="150" align="center">
                            </el-table-column>

                            <el-table-column prop="required" label="必填" width="50" align="center">
                                <template slot-scope="{row}">
                                    <el-checkbox v-model="row.required"></el-checkbox>
                                </template>
                            </el-table-column>
                            <el-table-column prop="validate" label="校验" width="50" align="center">
                                <template slot-scope="{row}">
                                    <el-checkbox v-model="row.validate"></el-checkbox>
                                </template>
                            </el-table-column>
                            <el-table-column prop="minLength" label="最短" width="80" align="center">
                                <template slot-scope="{row}">
                                    <el-input v-model.number="row.minLength"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="maxLength" label="最长" width="80" align="center">
                                <template slot-scope="{row}">
                                    <el-input v-model.number="row.maxLength"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="min" label="最小值" width="80" align="center">
                                <template slot-scope="{row}">
                                    <el-input v-model="row.min"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="max" label="最大值" width="80" align="center">
                                <template slot-scope="{row}">
                                    <el-input v-model="row.max"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="validatorType" label="校验类型" width="150" align="center">
                                <template slot-scope="{row}">
                                    <el-select v-model="row.validatorType" clearable>
                                        <el-option v-for="item in validatorTypes" :label="item.label" :value="item.value" :key="item.value"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="子表" name="3">
                        <el-table :data="subtables">

                            <el-table-column prop="name" label="控件名" width="150" align="center">
                                <template slot-scope="{row}">
                                    <el-input v-model="row.name"></el-input>
                                </template>
                            </el-table-column>

                            <el-table-column prop="column" label="主表字段" width="150" align="center">
                                <template slot-scope="{row}">
                                    <el-input v-model="row.column"></el-input>
                                </template>
                            </el-table-column>

                            <el-table-column prop="subColumn" label="子表字段" width="150" align="center">
                                <template slot-scope="{row}">
                                    <el-input v-model="row.subColumn"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="subCode" label="子表Code" width="150" align="center">
                                <template slot-scope="{row}">
                                    <el-select v-model="row.subCode" clearable>
                                        <el-option v-for="item in subCodes" :label="item.code" :value="item.code" :key="item.code"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column width="60" align="center">
                                <template slot-scope="{ row, column, $index }">
                                    <el-button @click="removeSubtable($index)" size="small" type="text">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-button @click="addSubtable" type="text" icon="el-icon-plus">添加</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form-item>

            <el-form-item>
                <el-button @click="onSave" :loading="$store.state.fetchingData" type="primary">保存</el-button>
                <el-button @click="$router.go(-1)">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import formValidator from '../formValidator'
import axios from 'axios'

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

                    res.data.modules = res.data.modules ? res.data.modules.split(',').map(i => String(i)) : [];

                    this.formData = res.data;

                    this.tablecolumnsFields = [];
                    // 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]
                    //     }

                    //     this.tablecolumnsFields.push(temp);
                    // });

                    this.tablecolumnsFields = JSON.parse(res.data.configJson);

                    this.subtables = [];
                    if (res.data.subJson) {

                        this.subtables = JSON.parse(res.data.subJson);
                    }

                }
            })
        }

        this.$http.get({
            url: '/dataSourceInfo/all'
        }).then(res => {
            if (res.success) {
                this.MysqlDataSourceInfos.push(this.baseDataSource);

                if (res.data.length > 0) {
                    res.data.forEach(item => {
                        if ('Mysql' == item.databaseType) {
                            this.MysqlDataSourceInfos.push(item);
                        } else if ('SqlServer' == item.databaseType) {
                            this.SqlServerDataSourceInfos.push(item);
                        }
                    })
                }
                this.datasourceInfoList = this.MysqlDataSourceInfos;
            }
        });

        this.$http.get({
            url: '/queryConfig/all'
        }).then(res => {
            if (res.success) {
                this.subCodes = res.data;
            }
        });


        this.getDatabaseTables();

    },
    data() {
        return {
            saving: false,
            formData: {
                databasetype: 'Mysql',
                dataSourceCode: 'dataSource',
                tableName: '',
                modules: []
            },
            rules: {
                databasetype: [
                    { required: true, message: '请选择数据库类型', trigger: 'blur' },
                ],
                code: [
                    { required: true, message: '请填写CODE', trigger: 'blur' },
                ],
                modules: [
                    { required: true, message: '请选择功能', trigger: 'blur' },
                ],
                tableName: [
                    { required: true, message: '请填写表名', trigger: 'blur' },
                ],
                dataSourceCode: [
                    { required: true, message: '请填选择数据库', trigger: 'blur' },
                ],
                typeFlag: [
                    { required: true, message: '请填写分类', trigger: 'blur' },
                ],
            },

            tablecolumnsFields: [
            ],
            tablecolumnsStr: '',
            columnTypes: [
                { label: '单行文本', value: 'singleLineText' },
                { label: '多行文本', value: 'textarea' },
                { label: '富文本', value: 'richText' },
                { label: '数字', value: 'number' },
                { label: '日期选择', value: 'date' },
                { label: '日期时间选择', value: 'datetime' },
                { label: '单选下拉框', value: 'select' },
                { label: '多选下拉框', value: 'multiSelect' },
                { label: '单图上传', value: 'singleImage' },
            ],
            validatorTypes: [
                { label: '英文', value: 'english' },
                { label: '数字', value: 'number' },
                { label: '手机', value: 'phone' },
                { label: '网址', value: 'url' },
                { label: '电子邮件', value: 'email' },
                { label: '身份证', value: 'id' }
            ],
            MysqlDataSourceInfos: [],
            SqlServerDataSourceInfos: [],
            baseDataSource: {
                databaseType: 'Mysql',
                code: 'dataSource',
                databaseName: '基础数据库'

            },
            datasourceInfoList: [],
            tableList: [],
            subtables: [],
            subCodes: [],

        }
    },
    methods: {
        onSave() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.submit();
                } else {
                    return false;
                }
            });
        },
        submit() {

            this.tablecolumnsStr = '';

            if (this.tablecolumnsFields.length > 0) {

                this.formData.subtables = this.subtables;
                this.formData.fields = this.tablecolumnsFields;
                this.formData.configJson = '';
                var data = JSON.parse(JSON.stringify(this.formData));;
                data.modules = this.formData.modules.join();

                this.$alert('确认要生成么？', '警告', { type: 'error' }).then(() => {
                    this.loading = true;
                    return axios.post(this.formData.id ? '/queryConfig/update' : '/queryConfig/save', data)
                }).then(() => {
                    this.loading = false;
                    this.$message.success('代码生成成功');
                    this.$router.go(-1);
                }).catch(res => {
                    this.loading = false;
                    if ('cancel' === res) {
                        this.$msgbox({ title: '提示', type: 'error', message: '生成取消' });
                    } else {
                        this.$msgbox({ title: '提示', type: 'error', message: '生成失败' });
                    }
                })
            } else {
                this.$message.warning('请添加字段')
            }
        },
        addField() {
            this.tablecolumnsFields.push({
                label: '',
                value: '',
                type: 'singleLineText',
            });
        },
        removeField(i) {
            if (this.tablecolumnsFields.length > 0) {
                this.tablecolumnsFields.splice(i, 1);
            }
        },
        changeDataBaseType() {
            if ('Mysql' == this.formData.databasetype) {
                this.datasourceInfoList = this.MysqlDataSourceInfos;
                this.formData.dataSourceCode = 'dataSource';
                this.getDatabaseTables();
            } else if ('SqlServer' == this.formData.databasetype) {
                this.datasourceInfoList = this.SqlServerDataSourceInfos;
                this.formData.dataSourceCode = '';
            }
        },
        getDatabaseTables(code) {
            this.tableList = [];
            this.$http.get({
                url: '/genCode/tables',
                data: {
                    code: code
                }
            }).then(res => {
                if (res.success) {

                    this.tableList = res.data;
                }
            })
        },
        changeDataSourceCode() {

            this.formData.tableName = '';
            this.getDatabaseTables(this.formData.dataSourceCode);
        },
        changeTableName() {

            this.tablecolumnsFields = [];

            this.getTableFields(this.formData.tableName);
        },
        getTableFields(tableName) {
            this.$http.get({
                url: '/genCode/tableFields',
                data: {
                    code: this.formData.dataSourceCode,
                    tableName: tableName,
                    databaseType: this.formData.databasetype,
                }
            }).then(res => {
                if (res.success) {



                    this.tablecolumnsFields = res.data;

                    // res.data.forEach(item => {

                    //     this.tablecolumnsFields.push({
                    //         label: item.remark,
                    //         value: item.name,
                    //         type: 'singleLineText',
                    //     })
                    // })

                }
            })
        },
        addSubtable() {
            this.subtables.push({
                name: '',
                column: '',
                subColumn: '',
                subCode: '',
            });
        },
        removeSubtable(i) {
            if (this.subtables.length > 0) {
                this.subtables.splice(i, 1);
            }
        },
    }
}
</script>
<style lang="less" scoped>
</style>
