<template>
  <div style="padding: 0 10px; height: 100%; overflow: scroll">
    <template v-if="showForm">
      <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="sort" label="排序">
          <el-input
            v-model="selectedForm.sort"
            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="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>
          <el-button type="primary" @click="saveField">保存</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="destroyField"
                >确定</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 { save,destroy } from "@/api/course/form";
import { translate } from "@/api/system/customFormField";
import { debounce } from "@/utils";


export default {
  props: {
    rules: Object,
    types: Array,
  },
  data() {
    return {
      showForm:false,
      debouncedInputHandler: null,
      formRule: {
        name: [
          { required: true, message: "请输入字段名称" }
        ],
      },
      selectedForm:{}, // 选择的表单item数据
      selectedIndex:0, // 选择的表单item index

      selectItem: [], //自定义下拉内容，先绑定数组后转为对象
      validation:[], //效验规则
      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);
    },


    saveField() {
      this.selectedForm.select_item = []
      this.selectItem.forEach(i => {
        this.selectedForm.select_item[i.key] = i.value;
      })
      this.selectedForm.rule = this.validation.join(",")
      console.log("this.selectedForm",this.selectedForm)
      save(this.selectedForm).then(res=>{
        console.log("res",res)
        this.$Message.success('保存成功')
        this.$emit("refreshFormItem",'save')
      })
    },

    destroyField () {
      if(this.selectedForm.id){
        destroy({
          id:this.selectedForm.id
        }).then(res=>{
          this.$Message.success('删除成功')
          this.showForm = false
          this.$emit("refreshFormItem",'DelId',this.selectedIndex)
        })
      }else{
         this.$Message.success('删除成功')
         this.showForm = false
         this.$emit("refreshFormItem",'Del',this.selectedIndex)
      }
    }
  },
  watch: {
    selectedForm(newVal) {
      console.log("newval",newVal)
      if(newVal) {
        this.selectItem = [];
        if(newVal.select_item && typeof newVal.select_item === "Array") {
          for(let key in newVal.select_item) {
            this.selectItem.push({
              key,
              value: newVal.select_item[key]
            })
          }
        }
        this.validation = []
        if(newVal.rule){
          this.validation = newVal.rule.split(',')
        }

      }
    }
  },
  created() {
    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>
