<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" :border="true" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="保养人" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.maintainerId`" :rules="formRules.maintainerId" class="mb-0px!">
            <el-select
              v-model="row.maintainerId"
              placeholder="请选择保养人"
              style="width: 100%"
              :disabled="readonly || isTaskStatusNotExecuting"
            >
              <el-option
                v-for="staff in staffList"
                :key="staff.id"
                :label="staff.nickname"
                :value="staff.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="保养内容" min-width="300">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.content`" :rules="formRules.content" class="mb-0px!">
            <el-input v-model="row.content" placeholder="请输入保养内容" :disabled="readonly || isTaskStatusNotExecuting" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="工作时长" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.hours`" :rules="formRules.hours" class="mb-0px!">
            <el-input v-model="row.hours" placeholder="请输入工作时长" :disabled="readonly || isTaskStatusNotExecuting" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="120" v-if="!readonly && !isTaskStatusNotExecuting">
        <template #default="{ row, $index }">
          <!-- 统一显示保存和删除按钮 -->
          <el-button @click="handleSave(row, $index)" link type="primary">保存</el-button>
          <el-button @click="handleDelete(row, $index)" link type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" v-if="!readonly && !isTaskStatusNotExecuting">
    <el-button @click="handleAdd" round>+ 添加工时记录</el-button>
  </el-row>
</template>
<script setup lang="ts">
import {MaintenanceTaskHoursApi} from '@/api/device/maintenancetaskhours'
import {ref} from "vue";
import {getSimpleUserList} from '@/api/system/user'
import {Message as message} from "@/layout/components/Message";

const props = defineProps<{
  taskId: number // 任务id（主表的关联字段）
  readonly?: boolean // 是否只读模式
  actualStartTime?: number // 实际开始时间
  taskStatus?: number // 任务状态
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref<any[]>([])
const formRules = reactive({
  taskId: [{ required: true, message: '任务id不能为空', trigger: 'blur' }],
  maintainerId: [{ required: true, message: '保养人ID不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '保养内容不能为空', trigger: 'blur' }],
  hours: [{ required: true, message: '工作时长不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const staffList = ref<any[]>([]) // 用户列表

// 计算属性：当任务状态不等于2（执行中）时返回true
const isTaskStatusNotExecuting = computed(() => {
  return props.taskStatus !== 2;
});
/** 获取用户列表 */
const getStaffList = async () => {
  try {
    // 假设 UserApi.getUserList() 是获取用户列表的方法
    staffList.value = await getSimpleUserList()
  } catch (error) {
    message.error('获取用户列表失败')
  }
}

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.taskId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空且不是只读模式，则加载数据
    if (!val || props.readonly) {
      return;
    }
    try {
      formLoading.value = true
      // formData.value = await MaintenanceTasksApi.getMaintenanceTaskHoursListByTaskId(val)
    } finally {
      formLoading.value = false
    }

    // 获取用户列表
     await getStaffList();
  },
  { immediate: true }
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    taskId: undefined,
    maintainerId: undefined,
    content: undefined,
    hours: undefined,
  }
  row.taskId = props.taskId as any
  formData.value.push(row)
}

/** 保存按钮操作 */
const handleSave = async (row, index) => {
  // 表单校验
  const valid = await formRef.value.validateField(`${index}`)
  if (!valid) return
  
  try {
    formLoading.value = true
    // 调用保存接口，传递实际开始时间
    const saveData = {
      ...row,
      actualStartTime: props.actualStartTime,
      taskId: props.taskId
    }

    // 使用同一个接口处理新增和更新
    const res = await MaintenanceTaskHoursApi.taskHourRowCreate(saveData)

    // 保存成功后更新行数据，将返回的id回填到列表中
    const updatedRow = { ...row, id: res }
    formData.value.splice(index, 1, updatedRow)

    message.success('保存成功')
  } catch (err) {
    message.error('保存失败: ' + err.message)
  } finally {
    formLoading.value = false
  }
}

/** 删除按钮操作 */
const handleDelete = async (row, index) => {
  try {
    // 如果是已保存的记录，需要调用删除接口
    if (row.id) {
      await MaintenanceTaskHoursApi.deleteMaintenanceTaskHours(row.id)
    }
    // 从前端数据中移除
    formData.value.splice(index, 1)
    message.success('删除成功')
  } catch (err) {
    message.error('删除失败: ' + err.message)
  }
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}
const setData = (data) => {
  formData.value = data;
}

defineExpose({ validate, getData, setData })


</script>
