<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"></el-input>
        </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="select_item" label="下拉框选项">
          <div class="select-item">
            <div class="select-item__header">
              <span>键</span>
              <span>值</span>
            </div>

            <div class="select-item__body" v-for="(i, index) in selectItem">
              <div><el-input v-model="i.key" size="mini"></el-input></div>
              <div><el-input v-model="i.value" size="mini"></el-input></div>
              <div>
                <el-button
                  type="danger"
                  size="mini"
                  circle
                  icon="el-icon-delete"
                  @click="selectItem.splice(index, 1)"
                ></el-button>
              </div>
            </div>

            <el-button
              type="primary"
              size="mini"
              circle
              icon="el-icon-plus"
              @click="selectItem.push({ key: '', value: '' })"
            ></el-button>
          </div>
        </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 label="表单是否显示" prop="list_show">
          <el-switch
            v-model="selectedForm.form_show"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item label="是否固定" prop="is_fix">
          <el-select
            v-model="selectedForm.is_fix"
            clearable
            :popper-append-to-body="false"
            placeholder="请选择固定方式"
            style="width: 100%"
          >
            <el-option
              v-for="item in [
                { value: 'left', label: '左' },
                { value: 'right', label: '右' },
              ]"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="width" label="列宽">
          <el-input-number
            clearable
            :controls="false"
            v-model="selectedForm.width"
            placeholder="不输入为自动计算"
            style="width: 100%"
          ></el-input-number>
        </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, realTableIndex } from "@/api/system/customForm";
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: "请输入字段名称" }
        ],
      },

      selectItem: [], //自定义下拉内容，先绑定数组后转为对象
      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 resReal = await realTableIndex();
      const res = await formIndex({ page: 1, page_size: 999 });
      this.forms = [
        ...res.data,
        ...resReal.map((i) => {
          return { name: i, table_name: i };
        }),
      ];
    },

    saveField() {
      this.selectedForm.select_item = {}
      this.selectItem.forEach(i => {
        this.selectedForm.select_item[i.key] = i.value;
      })

      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) {
        this.selectItem = [];
        if(newVal.select_item && typeof newVal.select_item === "object") {
          for(let key in newVal.select_item) {
            this.selectItem.push({
              key,
              value: newVal.select_item[key]
            })
          }
        }

        console.log(111,this.selectItem)
      }
    }
  },
  created() {
    this.getForms();

    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">
::v-deep .el-input-number.is-without-controls .el-input__inner {
  text-align: left;
}

.select-item {
  text-align: center;

  &__header {
    font-weight: 600;
    display: flex;

    & > span {
      flex-basis: 30%;

      & + span {
        margin-left: 10px;
      }
    }
  }
  &__body {
    display: flex;

    & > div {
      flex-basis: 30%;

      & + div {
        margin-left: 10px;
      }
    }
  }
}
</style>
