<template>
    <div class="edit-view">
        <div class="edit-view__content-wrapper">
            <div class="edit-view__content-section">
                <el-form
                    :model="formData"
                    :rules="rules"
                    ref="form"
                    label-width="120px"
                    label-position="right"
                    size="small"
                    style="max-width: 500px"
                >
                    <el-form-item prop="levelOne" label="一级指标">
                        <el-input v-model="formData.levelOne"></el-input>
                    </el-form-item>
                    <el-form-item prop="levelTwo" label="二级指标">
                        <el-input v-model="formData.levelTwo"></el-input>
                    </el-form-item>
                    <el-form-item prop="levelThree" label="三级指标">
                        <el-input v-model="formData.levelThree"></el-input>
                    </el-form-item>
                    <el-form-item prop="unit" label="单位">
                        <el-input v-model="formData.unit"></el-input>
                    </el-form-item>
                    <el-form-item prop="source" label="数据来源">
                        <el-input v-model="formData.source"></el-input>
                    </el-form-item>
                    <el-form-item prop="calcMethod" label="计算方法">
                        <el-input v-model="formData.calcMethod"></el-input>
                    </el-form-item>
                    <el-form-item prop="remark" label="指标说明">
                        <el-input v-model="formData.remark"></el-input>
                    </el-form-item>
                    <el-form-item prop="formula" label="计算公式">
                        <el-input
                            v-model="formData.formula"
                            type="textarea"
                            :autosize="{ minRows: 2 }"
                            @blur="blur"
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="extend" label="数据库连接" style="width: 600px">
                        <el-table :data="extend">
                            <el-table-column label="公式参数" prop="key" width="100"> </el-table-column>
                            <el-table-column label="数据库字段" prop="value">
                                <template v-slot="{ row, $index }">
                                    <el-input v-model="extend[$index].value"></el-input>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="onSave" :loading="saving" type="primary">保存</el-button>
                        <el-button @click="onDelete" :loading="saving" type="danger" v-if="formData.id"
                            >删除
                        </el-button>
                        <el-button @click="$router.go(-1)">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    name: 'MetricEdit',
    created() {
        if (this.$route.query.id) {
            this.$http
                .get('metric/get/' + this.$route.query.id)
                .then(res => {
                    this.formData = res;
                    if (res.extend) {
                        this.extend = Object.keys(res.extend).map(key => {
                            return {
                                key,
                                value: res.extend[key]
                            };
                        });
                    }
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        }
    },
    data() {
        return {
            saving: false,
            formData: {},
            rules: {
                levelOne: [
                    {
                        required: true,
                        message: '请输入一级指标',
                        trigger: 'blur'
                    }
                ],
                levelTwo: [
                    {
                        required: true,
                        message: '请输入二级指标',
                        trigger: 'blur'
                    }
                ],
                levelThree: [
                    {
                        required: true,
                        message: '请输入三级指标',
                        trigger: 'blur'
                    }
                ]
            },
            extend: []
        };
    },
    methods: {
        onSave() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.submit();
                } else {
                    return false;
                }
            });
        },
        submit() {
            let data = { ...this.formData, extend: {} };

            this.extend.forEach(i => {
                data.extend[i.key] = i.value;
            });
            this.saving = true;
            this.$http
                .post('/metric/save', data, { body: 'json' })
                .then(res => {
                    this.saving = false;
                    this.$message.success('成功');
                    this.$router.go(-1);
                })
                .catch(e => {
                    console.log(e);
                    this.saving = false;
                    this.$message.error(e.error);
                });
        },
        onDelete() {
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
                .then(() => {
                    return this.$http.post(`/metric/del/${this.formData.id}`);
                })
                .then(() => {
                    this.$message.success('删除成功');
                    this.$router.go(-1);
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        console.log(e);
                        this.$message.error(e.error);
                    }
                });
        },
        blur() {
            console.log(this.formData.formula);
            var re = /\$\{(.*?)\}/g;
            var s = this.formData.formula;
            var m;
            let keys = [];
            do {
                m = re.exec(s);
                if (m) {
                    let key = m[1];
                    keys.push(key);
                    if (!this.extend.find(i => i.key === key)) {
                        this.extend.push({ key, value: '' });
                    }
                }
            } while (m);
            this.extend = this.extend.filter(i => keys.findIndex(j => j === i.key) > -1);
        }
    }
};
</script>
<style lang="less" scoped></style>
