<template>
  <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
    <a-row :gutter="20">
      <a-col :span="24">
        <a-form-item label="接口路径:" name="resourceCode">
          <a-select
            v-model:value="form.resourceCode"
            show-search
            placeholder="请选择接口路径"
            style="width: 100%"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            :options="resourceData"
            @search="handleSearch"
            @change="handleChange"
          >
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <div class="card-title">详细信息</div>
      </a-col>
      <a-col :span="12">
        <a-form-item label="接口名称:" name="resourceName">
          <a-input v-model:value="form.resourceName" allow-clear placeholder="请输入接口名称" disabled />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="接口编码:" name="resourceCode">
          <a-input v-model:value="form.resourceCode" allow-clear placeholder="请输入接口编码" disabled />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="接口请求方式:" name="httpMethod">
          <a-input v-model:value="form.httpMethod" allow-clear placeholder="请输入接口请求方式" disabled />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script setup name="InterfaceForm">
import { reactive, ref } from 'vue';
import { InterfaceApi } from '../api/InterfaceApi';

const props = defineProps({
  // 表单数据
  form: Object,
  isUpdate: Boolean
});

// 验证规则
const rules = reactive({
  resourceCode: [{ required: true, message: '请选择接口路径', type: 'string', trigger: 'change' }]
});

// 接口列表数据
const resourceData = ref([]);

// 搜索
const handleSearch = value => {
  InterfaceApi.list({ searchText: value }).then(res => {
    resourceData.value = res.data.map(item => {
      return { ...item, value: item.resourceCode, label: item.url + ' (' + item.resourceName + ')' };
    });
  });
};

// 接口路径改变
const handleChange = val => {
  if (val) {
    let data = resourceData.value.find(item => item.resourceCode == val);
    if (data) {
      props.form.resourceName = data.resourceName;
      props.form.resourceCode = data.resourceCode;
      props.form.httpMethod = data.httpMethod;
    }
  } else {
    props.form.resourceName = '';
    props.form.resourceCode = '';
    props.form.httpMethod = '';
  }
};

// 设置详情的数据
const setResourceData = data => {
  resourceData.value = [{ value: data.resourceCode, label: data.url + ' (' + data.resourceName + ')' }];
};

defineExpose({
  setResourceData
});
</script>

<style scoped lang="less">
.card-title {
  width: 100%;
  border-left: 5px solid;
  border-color: var(--primary-color);
  padding-left: 10px;
  margin-bottom: 20px;
}
</style>
