<template>
  <c-table :option="option">
    <template #menuLeft="{ record }">
      <button class="delivery-button" @click="() => handleClick(record)">投递</button>
    </template>
  </c-table>
  <a-modal
    v-model:visible="visible"
    title="请选择投递的职位"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
  >
    <a-form :model="form">
      <a-form-item field="post" label="职位">
        <a-select v-model="form.post">
          <!-- 动态渲染职位选项 -->
          <a-option v-for="job in jobList" :key="job.id" :value="job.id">{{
            job.jobName
          }}</a-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import option from './option'
import { addDelivery, getPositionList } from '@/api/upms/position'

// 模态框显示状态
const visible = ref(false)
// 表单数据
const form = reactive({
  name: '',
  post: ''
})
// 存储职位列表
const jobList = ref([])

// 存储当前选中行的记录
const currentRecord = ref(null)

// 点击投递按钮
const handleClick = async (record) => {
  // 保存当前选中行的记录
  currentRecord.value = record
  // 调用获取职位的方法
  await getDeliverys()
  visible.value = true
}

// 获取职位投递
const getDeliverys = async () => {
  try {
    // 根据当前选中行的记录构建请求体
    const entity2 = {
      fullName: '',
      resumeSource: '',
      positionId: ''
    }
    const response = await getPositionList(entity2)
    console.log('职位投递获取结果:', response)
    // 将获取到的职位数据赋值给 jobList
    jobList.value = response
  } catch (error) {
    console.error('获取职位失败:', error)
  }
}

// 点击确定后进行一个投递操作
const addDeliverys = async () => {
  try {
    // 根据当前选中行的记录和表单选择的职位构建请求体
    // console.log(`获取到的当前行是${JSON.stringify(currentRecord.value)}`)
    const entity = {
      fullName: currentRecord.value?.fullName || '',
      resumeSource: currentRecord.value?.resumeSource || '',
      positionId: form.post,
      id: currentRecord.value.id
    }
    const response = await addDelivery(entity)
    // 如果成功，基本什么都不会返回，结果undefined
    if (response === undefined) {
      // 弹出消息提示
      Message.success('投递成功')
    }
  } catch (error) {
    console.error('投递失败:', error)
    Message.error('投递失败，请稍后重试')
  }
}

// 模态框确认前的处理函数，确认按钮
const handleBeforeOk = async (done) => {
  console.log(form)
  // 调用 addDeliverys 方法
  await addDeliverys()
  window.setTimeout(() => {
    done()
    // 窗口关闭时间，单位毫秒
  }, 1000)
}

// 模态框取消按钮处理函数
const handleCancel = () => {
  visible.value = false
}
</script>

<style lang="scss">
.arco-modal-footer {
  text-align: center !important;
}
</style>
