<!--
 * @jixuanyu: jixuanyu
 * @Date: 2022-05-09 11:28:18
 * @LastEditors: jixuanyu
 * @Description: file content
-->
<template>
  <z-form class="z-form" :model="basicForm" :label-col="{ style: { width: '80px' } }">
    <z-form-item label="绑定字段" :prop="'field'" :rules="[{required: true, trigger: 'change',message: '请选择绑定字段'}]">
      <z-select v-model:value="basicForm.field" @change="handleChange">
        <z-select-option
          v-for="(item, index) in options"
          :key="index"
          :value="item.name"
          :disabled="item.disabled"
        >{{ item.comment }}（{{ item.name }}）</z-select-option>
      </z-select>
    </z-form-item>
    <z-form-item label="字段名称" :prop="'titleName'" :rules="[{required: true, trigger: 'change',message: '请输入字段名称'}]">
      <z-input v-model:value="basicForm.titleName" readonly />
    </z-form-item>
  </z-form>
</template>
<script>
import { defineComponent, toRef, computed, onBeforeMount, reactive, toRefs } from 'vue'
import { getFormField } from '@/api/form-designer/form-manager.js'
import { useRoute } from 'vue-router'
import { message } from 'zrar-ui'
export default defineComponent({
  props: {
    basicProperty: {
      type: Object,
      default: undefined
    },
    newLists: {
      type: Object,
      default: undefined
    }
  },
  setup(props) {
    onBeforeMount(() => {
      getField()
      // 2.组件挂载页面之前执行----onBeforeMount
    })
    const state = reactive({
      options: []
    })
    const router = useRoute()
    const getField = () => {
      return getFormField({ defId: router.query.defId }).then(res => {
        console.log('获取表单字段', res.data)
        state.options = res.data
      })
    }

    const currentKey = computed(() => props.basicProperty.currentKey)

    const basicForm = toRef(props, 'basicProperty')
    const formRules = {
      'label': [{
        require: true, trigger: 'change'
      }]
    }
    const handleChange = (val, option) => {
      console.log('handleChange', val, option)
      state.options.forEach(item => {
        item.disabled = false
      })
      state.options.forEach(item1 => {
        props.newLists.forEach(item2 => {
          if (item2.basicProperty.field === item1.fieldName) {
            item1.disabled = true
          }
        })
      })
      if (currentKey) {
        basicForm.value.titleName = getName(val)
      } else {
        message.error('请先选择组件！')
        basicForm.value.field = ''
      }
    }
    const getName = (value) => {
      const targetObj = state.options.find(opt => opt.name === value)
      return targetObj.comment
    }
    return {
      ...toRefs(state),
      basicForm,
      formRules,
      handleChange,
      getFormField
    }
  }
})

</script>
<style lang="scss" scoped>
.z-form {
  ::v-deep .ant-row {
    flex-wrap: nowrap;
    .ant-form-item-label {
      flex-shrink: 0;
    }
    .ant-form-item-control {
      width: calc(100% - 80px);
    }
  }
}
</style>
