<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=='switch'">
                            <el-switch v-model="formData[item.name]">
                            </el-switch>
                        </template>

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

                            <el-select v-model="formData[item.name]" clearable placeholder="请选择">
                                <el-option v-for="(optionItem,index) in selectOptions[item.name]" :key="index" :label="optionItem.label" :value="optionItem.value">
                                </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,index) in selectOptions[item.name]" :key="index" :label="optionItem.label" :value="optionItem.value">
                                </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="goBackPage">取消</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.logicalValidate();
                } 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();
                    } else if (formType == 'currentTime') {
                        formDataTemp[key] = format(new Date(), 'YYYY/MM/DD HH:mm', { locale: zh });
                    } else if (formType == 'currentDate') {
                        formDataTemp[key] = format(new Date(), 'YYYY/MM/DD', { locale: zh });
                    }


                }



            }

            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)) : [];
                            }

                            if (element.formType == "loginName") {
                                res.data[element.name] = this.userInfo.username;
                            }
                            if (element.formType == "workNumber") {
                                res.data[element.name] = this.userInfo.workNumber;
                            }
                            if (element.formType == "departId") {
                                res.data[element.name] = this.userInfo.departId;
                            }
                            if (element.formType == "departId") {
                                res.data[element.name] = this.userInfo.departId;
                            }
                            if (element.formType == "departId") {
                                res.data[element.name] = this.userInfo.departId;
                            }


                        });

                        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;
                }
            }



        },
        logicalValidate() {

            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 logicalKeyStr = '';

            var logicalData = {
            }

            var advancedQuerySearchKey = '';

            this.tableColumns.forEach(element => {
                if (element.logicalKey) {
                    logicalKeyStr += element.remark + ';'
                    var tempSearchKey = 'AND' + '_,' + element.name + '_,' + '=' + '_,' + formDataTemp[element.name];
                    if (advancedQuerySearchKey) {
                        advancedQuerySearchKey = advancedQuerySearchKey + '_;' + tempSearchKey;
                    } else {
                        advancedQuerySearchKey = tempSearchKey;
                    }
                }

            });


            if (!advancedQuerySearchKey) {
                this.submit();
            } else {



                logicalData.tableName = this.tableName;
                logicalData.databasetype = this.databasetype;
                logicalData.dataSourceCode = this.dataSourceCode;
                logicalData.advancedQuery = advancedQuerySearchKey;

                this.$http.get({
                    url: '/commonQuery/one',
                    data: logicalData
                }).then(res => {
                    if (res.success) {

                        var logicalFlag = true;

                        if (res.data) {
                            if (this.formData.id) {
                                if (res.data.id != this.formData.id) {
                                    logicalFlag = false;
                                }
                            } else if (this.formData.ID) {
                                if (res.data.ID != this.formData.ID) {
                                    logicalFlag = false;
                                }
                            } else {
                                logicalFlag = false;
                            }

                        }

                        if (logicalFlag) {
                            this.submit();
                        } else {
                            this.$message.warning('逻辑关键字:' + logicalKeyStr + '验证失败')
                        }


                    } else {
                        this.$message.warning('逻辑关键字:' + logicalKeyStr + '验证失败')
                    }
                });
            }
        },

        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 == "2") {

                                    this.$http.get({
                                        url: element.optionsMethod,
                                        data: {}
                                    }).then(res => {
                                        if (res.success) {

                                            var tempOptions = [];
                                            res.data.forEach(item => {
                                                var val = {
                                                    label: item[element.optionsLabel],
                                                    value: item[element.optionsValue],
                                                }
                                                tempOptions.push(val)
                                            });

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

                                } else if (element.apiFlag == "3") {
                                    this.$http.get({
                                        url: '/commonQuery/all',
                                        data: {
                                            tableName: element.optionsMethod,
                                            databasetype: element.optionsDataBaseType,
                                            dataSourceCode: element.optionsDataSourceCode,
                                        }
                                    }).then(res => {
                                        if (res.success) {

                                            var tempOptions = [];
                                            if (res.data.length > 0) {
                                                res.data.forEach(item => {
                                                    var val = {
                                                        label: item[element.optionsLabel],
                                                        value: item[element.optionsValue],
                                                    }
                                                    tempOptions.push(val)
                                                })
                                            }

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

                                } else {
                                    var tempOptions = [];

                                    element.optionsValue.split(',').forEach(item => {
                                        var val = {
                                            label: item,
                                            value: item,
                                        }
                                        tempOptions.push(val)
                                    })
                                    this.selectOptions = {
                                        ...this.selectOptions,
                                        [element.name]: tempOptions
                                    };
                                }
                            }


                            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.goBackPage();
                }).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;
        },
        goBackPage() {
            this.$router.push({
                path: '/commonQuerys',
                query: {
                    code: this.$route.query.code,
                    column: this.$route.query.column,
                    currentPage: this.$route.query.currentPage,
                    pageNumber: this.$route.query.pageNumber,
                    advancedQuery: this.$route.query.advancedQuery,
                    searchKey: this.$route.query.filter1,
                    orderByStr: this.$route.query.orderByStr,
                }
            })
        },
    }
}
</script>
<style lang="less" scoped>
</style>
