<template>
  <div>
    <el-page-header @back="$emit('back')" content="表单配置"> </el-page-header>
    <el-form label-width="80px" size="small" style="margin-top: 10px" inline>
      <el-form-item label="表单名称">
        <el-input
          v-model="name"
          placeholder="请输入表单名称"
          style="width: 280px"
        ></el-input>
      </el-form-item>
      <el-form-item label="数据表">
        <el-select
          clearable
          filterable
          default-first-option
          v-model="tableCode"
          @change="tableCodeChange"
        >
          <el-option
            v-for="opt in tableList"
            :key="opt.code"
            :label="opt.name"
            :value="opt.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <avue-form-design
      ref="form"
      style="height: 82vh"
      :options="options"
      :showGithubStar="false"
      :include-fields="['tabs', 'group', 'title', 'dynamic']"
      :toolbar="[formEdit.type === 1 ? '' : 'save', 'preview', 'clear']"
      :custom-fields="customFields"
      :table-name="tableName"
      @handleSave="handleSave"
      @filterField="filterField"
    ></avue-form-design>
  </div>
</template>

<script>
import {
  getFieldListByCode,
  addForm,
  getFormDetail,
  getHistoryInfo,
} from "@/api/field"
import { getTableList } from "@/api/database"

export default {
  name: "FormAdd",
  props: {
    formEdit: {
      type: Object,
    },
    dbId: {},
  },
  data() {
    return {
      tableList: [],
      disabled: false,
      name: "",
      options: {},
      tableCode: "",
      tableName: null,
      customFields: [],
      customOldFields: [],
    }
  },

  methods: {
    getTableList() {
      if (!this.dbId) return
      getTableList(this.dbId).then((res) => {
        this.tableList = res.data
      })
    },
    // 获取数据表字段
    tableCodeChange(tableCode) {
      if (!tableCode) return
      this.$refs.form.customFieldsLoading = this.disabled = true
      const tableList = this.tableList
      this.tableName =
        tableList.find((_) => _.value === tableCode) &&
        tableList.find((_) => _.value === tableCode).label
      getFieldListByCode({ tableCode })
        .then((res) => {
          if (res.code === 1) {
            const customOldFields = []
            const d = res.data
            d.forEach((item) => {
              if (!item.jsonStr) return
              const field = JSON.parse(item.jsonStr)
              if (field.id) delete field.id
              customOldFields.push({
                ...field,
                tableName: item.tableName,
                tableCode: item.tableCode,
                tableId: item.tableId,
              })
            })

            this.customOldFields = customOldFields.map((_) => {
              return {
                ..._,
                notFilter: tableCode === "data_lab_detail", //  data_lab_detail 字段可以重复
              }
            })
            this.filterField()

            this.$refs.form.customFieldsLoading = this.disabled = false
          }
        })
        .catch(() => {
          this.$refs.form.customFieldsLoading = this.disabled = false
        })
    },
    // 字段和表单已有字段对比 过滤
    async filterField() {
      const { fieldList } = await this.getData()
      this.customFields = this.customOldFields.filter((field) => {
        return field.notFilter || !fieldList.find((_) => _.prop === field.prop)
      })
    },
    // 获取当前表单中数据
    async getData() {
      const form = {
        id: this.formEdit.id,
        formJson: "",
        name: this.name,
        dbId: this.dbId,
      }
      let fieldList = []
      form["formJson"] = await this.$refs.form.getData("string")
      const d = await this.$refs.form.getData()
      this.formatColumn(d.column).forEach((item) => {
        if (!fieldList.find((_) => _.prop === item.prop)) {
          fieldList.push(item)
        }
      })
      if (d.group) {
        d.group.forEach((g) => {
          this.formatColumn(g.column).forEach((item) => {
            if (!fieldList.find((_) => _.prop === item.prop)) {
              fieldList.push(item)
            }
          })
        })
      }
      return { form, fieldList }
    },
    // 提取字段list
    formatColumn(column) {
      const fieldList = []
      const deepFn = function (column = [], parent) {
        column.forEach((c) => {
          if (c.type === "dynamic") {
            const childColumn = c.children.column
            if (childColumn && childColumn.length > 0) {
              deepFn(childColumn, c)
            }
          }
          if (c.type === "group") {
            const childColumn = c.children.column
            if (childColumn && childColumn.length > 0) {
              deepFn(childColumn)
            }
          } else if (c.type !== "title") {
            fieldList.push({
              ...c,
              parentCode: parent && parent.prop,
              fieldCode: c.prop,
              fieldName: c.label,
            })
          }
        })
      }
      deepFn(column)
      return fieldList
    },

    // 保存数据
    async handleSave() {
      if (!this.name) {
        this.$message.warning("请输入表单名称")
        return
      }
      const data = await this.getData()
      const { fieldList } = data
      if (!fieldList.length) {
        this.$message.warning("没有可以保存的数据")
        return
      }
      addForm(data).then((res) => {
        if (res.code === 1) {
          this.$emit("back", true)
        }
      })
    },
    initForm() {
      const { id, type } = this.formEdit
      if (!id) return
      const API = type === 1 ? getHistoryInfo : getFormDetail
      API(id).then((res) => {
        if (res.code === 1) {
          this.options = res.data.formJson
          this.name = res.data.name
        }
      })
    },
  },
  created() {
    this.initForm()
    this.getTableList()
  },
}
</script>

<style lang="scss" scoped></style>
