<script setup lang="ts">
import { ElMessage } from 'element-plus'

import { getSurveyForm, submitSurveyForm } from '../api'

interface FormItem {
  title: string
  survey_field_id: string
  field_id: string
}
interface FieldItem {
  id: string
  name: string
}
const props = defineProps<{ id: string; formId: string }>()
const emit = defineEmits<{
  'update:modelValue': [visible: boolean]
  update: []
}>()

const fields = ref<FieldItem[]>([])
const form = ref<FormItem[]>([])
async function fetchInfo() {
  const res = await getSurveyForm({ form_id: props.formId })
  fields.value = res.data.fields || []
  form.value = res.data.form || []
}
watchEffect(fetchInfo)

async function handleSubmit() {
  await submitSurveyForm({ id: props.id, form_id: props.formId, form: JSON.stringify(form.value) })
  emit('update')
  emit('update:modelValue', false)
  ElMessage.success('保存成功')
}
</script>

<template>
  <el-dialog title="字段映射" width="500" @closed="$emit('update:modelValue', false)">
    <el-form labelWidth="240" labelPosition="left">
      <el-form-item v-for="item in form" :key="item.survey_field_id" :label="item.title">
        <el-select v-model="item.field_id" style="width: 220px">
          <el-option v-for="item in fields" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
