<template>
    <div class="app-container">
        <el-card style="margin-bottom: 15px;">
            <el-form ref="form" :model="form" label-width="100px" :rules="rules">
                <el-form-item label="数据库名称" prop="dataBaseName">
                    <el-input v-model="form.dataBaseName" style="width: 600px;"></el-input>
                </el-form-item>
                <el-form-item label="数据表名称" prop="tableName">
                    <el-input v-model="form.tableName" style="width: 600px;"></el-input>
                </el-form-item>
                <el-form-item label="表描述">
                    <el-input v-model="form.tableComment" style="width: 600px;"></el-input>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card>
            <div class="titleitem">
                <span>数据表字段</span>
            </div>
            <el-form ref="tableform" :rules="tableform" :model="experienceDataForm">
                <el-table :data="experienceData" stripe style="width: 100%">
                    <el-table-column prop="fieldName" label="字段名称" width="200">
                        <template slot-scope="scope">
                            <el-form-item :prop="'fieldName' + scope.$index" :name="'fieldName' + scope.$index"
                                style="margin: 0px;padding: 0px;">
                                <el-input v-model="scope.row.fieldName"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>

                    <el-table-column prop="fieldType" label="字段类型" width="200">
                        <template slot-scope="scope">
                            <el-form-item :prop="'fieldType' + scope.$index" :name="'fieldType' + scope.$index"
                                style="margin: 0px;padding: 0px;">
                                <el-select v-model="scope.row.fieldType" filterable  @blur="selectBlur(scope.row)">
                                    <!-- <el-option v-for="item in list" :key="item" :label="item" :value="item">
                                    </el-option> -->
                                    <!-- 
                                    <el-option v-for="item in dict.type.mysql_data_type"  :label="item.dictLabel" :value="item.dictValue">
                                    </el-option> -->

                                    <el-option v-for="item in dict.type.mysql_data_type" :key="item.value"
                                        :label="item.label" :value="item.value" />


                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>

                    <el-table-column prop="fieldLength" label="长度" width="200">
                        <template slot-scope="scope">
                            <el-form-item :prop="'fieldLength' + scope.$index" :name="'fieldLength' + scope.$index"
                                style="margin: 0px;padding: 0px;">
                                <el-input v-model="scope.row.fieldLength"
                                    :disabled="testasd(dict.type.mysql_data_type.find(item => item.label === scope.row.fieldType),scope)"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>

                    <el-table-column prop="isNull" label="不是null" width="100">
                        <template slot-scope="scope">
                            <el-checkbox v-model="scope.row.isNull"></el-checkbox>
                        </template>
                    </el-table-column>


                    <el-table-column prop="isPrimary" label="键" width="100">
                        <template slot-scope="scope">
                            <el-checkbox v-model="scope.row.isPrimary" @change="hanleCheckbox(scope.$index)"></el-checkbox>
                        </template>
                    </el-table-column>

                    <el-table-column prop="isAuto" label="自增" width="100">
                        <template slot-scope="scope">
                            <el-checkbox v-model="scope.row.isAuto"></el-checkbox>
                        </template>
                    </el-table-column>

                    <el-table-column prop="fieldDescription" label="字段描述" width="200">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.fieldDescription"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="operate" label="操作">
                        <template slot-scope="scope">
                            <!-- <el-button size="mini" type="success" icon="el-icon-save"
                                @click="handlesaveExperience(scope.$index, scope.row)">保存
                            </el-button> -->
                            <el-button size="mini" type="danger" icon="el-icon-delete"
                                @click="handleDeleteExperience(scope.$index, scope.row)">删除
                            </el-button>

                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <div>
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddExperienceline">新增字段
                </el-button>
            </div>
        </el-card>

        <div style="margin-top: 15px;">
            <el-button @click="add" type="primary">添加</el-button>
        </div>
    </div>
</template>

<script>
import { createDatabase } from "@/api/datasheet/index"
export default {
    name: "Datasheet",
    dicts: ['mysql_data_type'],
    data() {
        return {
            testzidian: null,
            form: {
                dataBaseName: '',
                tableName: '',
                tableComment: '',
            },
            experienceDataForm: {},
            experienceData: [
                // {
                //     fieldName: '',
                //     fieldType: '',
                //     fieldLength: undefined,
                //     isNull: false,
                //     isPrimary: false,
                //     fieldDescription: '',
                //     isAuto: false
                // },
            ],
            rules: {
                dataBaseName: { required: true, message: '请输入数据库名称', trigger: 'blur' },
                tableName: { required: true, message: '请输入数据库名称', trigger: 'blur' }
            },
            tableform:
            {
                // fieldName0: { required: true, message: '请输入字段名称', trigger: 'blur' },
                // fieldType0: { required: true, message: '请选择', trigger: 'change' },
                // fieldLength0: { required: true, message: '请输入', trigger: 'blur' },
            },
            list: [
                'int', 'varchar'
            ]
        }
    },
    watch: {
        experienceData: {
            handler(n, o) {
                // do something
                this.experienceDataForm = {}
                let rulesAdd = {}
                this.experienceData.forEach((item, index) => {
                    rulesAdd['fieldName' + index] = item.fieldName
                    rulesAdd['fieldType' + index] = item.fieldType
                    rulesAdd['fieldLength' + index] = item.fieldLength
                    this.experienceDataForm = { ...rulesAdd }

                })
                // console.log(this.experienceDataForm);
            },
            deep: true// 深度监听父组件传过来对象变化
        }
    },
    methods: {
        testasd(tem,scope) {  
            if (tem == undefined) return;
            console.log(tem.raw.listClass)
            if (tem.raw.listClass === 'success'){
                this.$delete(this.tableform,scope.column.property+''+scope.$index);
                return true;
            } 
            return false;
        },
        // handleSelectChange(selectedValue) {
        //     console.log(JSON.stringify(selectedValue)+"------------");
        //     if (selectedValue.fieldType === 'varchar') {
        //         selectedValue.fieldLength = '';
        //         selectedValue.isRequired = true;
        //     } else {
        //         selectedValue.fieldLength = '';
        //         selectedValue.isRequired = false;
        //     }
        // }
        // ,
        selectBlur(aa) {
            if (aa.fieldType == "") {
                aa.fieldType = undefined
            }
        },
        // 处理非空校验问题
        handleRules() {
            let rulesAdd = {};
            this.experienceData.forEach((item, index) => {
                rulesAdd['fieldName' + index] = { required: true, message: '请输入字段名称', trigger: 'blur' }
                rulesAdd['fieldType' + index] = { required: true, message: '请选择', trigger: 'change' }
                rulesAdd['fieldLength' + index] = { required: true, message: '请输入', trigger: 'blur' }

                this.tableform = {
                    ...rulesAdd
                }
            })
            console.log(this.tableform)
        },
        // 处理主键选框问题
        hanleCheckbox(ind) {
            this.experienceData.forEach((item, index) => {
                if (index != ind) {
                    item.isPrimary = false;
                }
                if (index == ind && item.isPrimary == true) {
                    item.isNull = true
                }
                console.log(item);

            })
        },
        //增加经验行
        handleAddExperienceline() {
            if (this.experienceData == undefined) {
                this.experienceData = new Array();
            }
            let obj = {
                fieldName: '',
                fieldType: '',
                fieldLength: undefined,
                isNull: false,
                isPrimary: false,
                fieldDescription: '',
                isAuto: false
            };

            this.experienceData.push(obj);
            this.handleRules();
        },
        //保存经验行
        handlesaveExperience(a, b) {
            console.log(a + b);
            console.log(b);
        },
        //删除经验行
        handleDeleteExperience(index) {
            console.log(index);
            this.experienceData.splice(index, 1)
            this.handleRules();
        },
        add() {
            const rule1 = new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        resolve()
                    } else {
                        return false;
                    }
                })
            })
            const rule2 = new Promise((resolve, reject) => {
                this.$refs['tableform'].validate(valid => {
                    if (valid) {
                        resolve()
                    } else {
                        return false;
                    }
                })
            })

            Promise.all([rule1, rule2]).then(() => {
                if (this.experienceData.length == 0) {
                    this.$modal.msgWarning("字段不可为空！")
                    return;
                }
                this.experienceData.forEach((field) => {
                    if (field.fieldLength) {
                        field.fieldType = `${field.fieldType}(${field.fieldLength})`
                    }
                })

                let query = {
                    dataBaseName: this.form.dataBaseName,
                    tableName: this.form.tableName,
                    tableComment: this.form.tableComment,
                    field: this.experienceData
                }
                createDatabase(query).then(res => {

                    this.$modal.msgSuccess(res.msg);
                    if (res.code === 200) {
                        this.visible = false;
                        this.$emit("ok");
                        Object.keys(this.form).forEach(key => (this.form[key] = ''));
                        this.experienceData = []
                    }
                }).catch(err => {
                    console.log(err);
                })
            })
        }


    }
}
</script>
<style scoped></style>