<template>
  <el-form class="code-gen-db-form" :model="form" ref="form">
    <CodeEdit :code="form.options" ref="options" />
    <div class="el-dialog__footer">
      <pro-action @asyncHandler="handleFormatCode" text="格式化" />
      <pro-action @handler="$emit('customerClose', form)" text="取 消" />
      <pro-action @asyncHandler="handlerSave" text="保存编辑" type="primary" />
    </div>
  </el-form>
</template>

<script>
import CodeEdit from "../components/code-edit";
import { post } from "mars-pro/src/pro/request";
import dataSource from "mars-pro/src/pro/mixins/dataSource";

const defaultOptions = `{
  dbSource: {
   name: '?',
   target: '?',
  },
  tableSource: {
   name: '?',
   target: '?'
  }
}`;
export default {
  mixins: [
    dataSource("dbOptions", "/mock/api/code-gen/db/find", {
      dataField: "data.options",
      freeze: true,
      async: true,
    }),
  ],
  components: {
    CodeEdit,
  },
  data() {
    return {
      form: {
        options: defaultOptions,
      },
    };
  },
  watch: {
    "dbOptions.store.datas": function () {
      this.form.options = this.dbOptions.formatDatas
    },
  },
  created() {
    //加载数据
    this.dbOptions.loadDatas();
  },
  methods: {
    //验证数据源配置
    validateOptions() {
      const formOptions = this.$refs.options.inputCode;
      try {
        return Function(`return ${formOptions}`).call(this);
      } catch (e) {
        //
        this.$message.error(`数据源配置语法错误:
${e.message}
         `);
        return false;
      }
    },
    async handlerSave() {
      try {
        //表单校验
        await this.$refs.form.validate();
        //验证数据源配置
        if (this.validateOptions() !== false) {
          const _selectpdata = this.selectpdata || {};
          const { err } = await post("/mock/api/code-gen/db/save", {
            data: {
              ...this.form,
              options: this.$refs.options.inputCode,
              ...(_selectpdata._id ? { _id: _selectpdata._id } : {}),
            },
          }).done();

          if (!err) {
            this.$store.dbConfig.loadDatas();

            //如果是编辑, 则保存成功后 便关闭
            this.$emit("customerClose", this.form);
          }
        }
      } catch (e) {}
    },
     async handleFormatCode(){
      const formOptions = this.$refs.options.inputCode;
      this.form.options = formOptions
      if (formOptions){
        const { response } = await post("/mock/api/code-gen/user-mock/formatCode", {
           code: formOptions
          }).done();
          this.form.options = response.data.formatCode
          
      }
    }
  },
};
</script>

<style lang="scss">
.code-gen-db-form {
  .vue-codemirror {
    width: 100%;
    display: inline-block;
  }
}
</style>