<template>
  <div style="padding: 0 10px; height: 100%; overflow: scroll">
    <template v-if="selectedForm">
      <el-form
        :rules="formRule"
        ref="form"
        :model="selectedForm"
        label-width="80px"
      >
        <el-form-item prop="name" label="字段名称">
          <el-input
            v-model="selectedForm.name"
            placeholder="请输入字段名称"
            @input="inputHandler"
          ></el-input>
        </el-form-item>
        <el-form-item required prop="field" label="字段标识">
          <el-input v-model="selectedForm.field" disabled></el-input>
        </el-form-item>
        <el-form-item label="关联方式">
          <el-select
            v-model="linkType"
            clearable
            :popper-append-to-body="false"
            placeholder="请选择关联方式"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in ['关联表', '数据字典']"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="parameter_id"
          label="数据字典"
          v-show="linkType === '数据字典'"
        >
          <el-select
            v-model="selectedForm.parameter_id"
            clearable
            :popper-append-to-body="false"
            placeholder="请选择数据字典"
            style="width: 100%"
          >
            <el-option
              v-for="item in parameters"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="link_table_name"
          label="关联表"
          v-show="linkType === '关联表'"
        >
          <el-select
            v-model="selectedForm.link_table_name"
            clearable
            :popper-append-to-body="false"
            placeholder="请选择关联表"
            style="width: 100%"
          >
            <el-option
              v-for="item in forms"
              :key="item.id"
              :label="item.name"
              :value="item.table_name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="link_relation"
          label="关联类型"
          v-show="linkType === '关联表'"
        >
          <el-select
            v-model="selectedForm.link_relation"
            :popper-append-to-body="false"
            placeholder="请选择关联类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in [
                { value: 'hasOne', label: '一对一' },
                { value: 'hasMany', label: '一对多' },
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="help" label="帮助文字">
          <el-input
            v-model="selectedForm.help"
            placeholder="请输入帮助文字"
          ></el-input>
        </el-form-item>
        <el-form-item prop="validation" label="校验规则">
          <el-select
            v-model="selectedForm.validation"
            clearable
            multiple
            collapse-tags
            :popper-append-to-body="false"
            placeholder="请选择校验规则"
            style="width: 100%"
          >
            <el-option
              v-for="(value, key) in rules"
              :key="key"
              :label="value"
              :value="key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否显示" prop="list_show">
          <el-switch
            v-model="selectedForm.list_show"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveField">保存</el-button>
          <el-button
            @click="
              (linkType = ''),
                $store.commit('form/CLEAR_SELECTED'),
                $store.commit('form/CLEAR_SELECTED_INDEX')
            "
            >清除</el-button
          >
          <el-popover
            trigger="hover"
            ref="el-popover"
            placement="top"
            width="160"
          >
            <p>确定删除字段吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="$refs['el-popover'].doClose()"
                >取消</el-button
              >
              <el-button
                type="primary"
                size="mini"
                @click="
                  $store.commit('form/SPLICE_FORM_LIST', {
                    index: selectedIndex,
                    length: 1,
                  }),
                    $store.commit('form/CLEAR_SELECTED_INDEX'),
                    $store.commit('form/CLEAR_SELECTED'),
                    $refs['el-popover'].doClose()
                "
                >确定</el-button
              >
            </div>
            <el-button
              type="danger"
              slot="reference"
              @click="$refs['el-popover'].doShow()"
              style="margin-left: 10px"
              >删除</el-button
            >
          </el-popover>
        </el-form-item>
      </el-form>
    </template>
    <template v-else>
      <el-empty
        style="position: relative; top: 50%; transform: translateY(-50%)"
        description="暂无选择"
      ></el-empty>
    </template>
  </div>
</template>

<script>
import { index as formIndex } from "@/api/system/customForm";
import { listparameter } from "@/api/system/dictionary";
import { translate } from "@/api/system/customFormField";
import { debounce } from "@/utils";

import { mapState } from "vuex";

export default {
  props: {
    rules: Object,
    types: Array,
  },
  data() {
    return {
      linkType: "",
      debouncedInputHandler: null,
      formRule: {
        name: [
          { required: true, message: "请输入字段名称" },
          {
            validator: this.checkChinese,
          },
        ],
      },

      parameters: [], //数据字典
      forms: [], //表
    };
  },
  methods: {
    checkChinese(rule, value, callback) {
      const reg = /^[\u4e00-\u9fa5]+$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入中文姓名"));
      }
    },
    inputHandler(e) {
      this.debouncedInputHandler(e);
    },

    async getForms() {
      const res = await formIndex({ page: 1, page_size: 999 });
      this.forms = res.data;
    },
    async getParameters() {
      const res = await listparameter({ page: 1, page_size: 999 });
      this.parameters = res.data;
    },

    saveField() {
      this.$store.commit("form/SPLICE_FORM_LIST", {
        index: this.selectedIndex,
        length: 1,
        config: this.selectedForm,
      });
      this.$store.commit("form/CLEAR_SELECTED");
      this.$store.commit("form/CLEAR_SELECTED_INDEX");
    },
  },
  computed: {
    ...mapState("form", ["selectedForm", "formList", "selectedIndex"]),
  },
  watch: {
    selectedForm(newVal) {
      if (newVal?.parameter_id) {
        this.linkType = "数据字典";
      } else if (newVal?.link_table_name) {
        this.linkType = "关联表";
      } else {
        this.linkType = "";
      }
    },
  },
  created() {
    this.getForms();
    this.getParameters();

    this.debouncedInputHandler = debounce((e) => {
      if (e) {
        this.checkChinese("", e, (err) => {
          if (!err) {
            translate({
              str: e,
            }).then((en) => {
              this.selectedForm.field = en.pinyin;
            });
          }
        });
      }
    }, 1000);
  },
};
</script>

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