<template>
  <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      v-loading="formLoading"
      label-width="0px"
      :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="60"/>
      <el-table-column label="巡检项目" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.itemName`" :rules="formRules.itemName" class="mb-0px!">
            <el-input v-model="row.itemName" placeholder="请输入巡检项目" disabled/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="填报类型" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item
:prop="`${$index}.reportType`" :rules="formRules.reportType"
                        class="mb-0px!">
            <el-select v-model="row.reportType" placeholder="请选择填报类型" disabled>
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_INSPECTION_REPORT_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="结果值" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item
:prop="`${$index}.reportValue`" :rules="formRules.reportValue"
                        class="mb-0px!">
            <el-input
                v-if="row.reportType == 1"
                v-model="row.reportValue"
                placeholder="请输入结果值"
                :disabled="!isEditable || row.reportType !== 1"
                @input="handleReportValueChange(row)"
            />
          </el-form-item>
        </template>

      </el-table-column>

      <el-table-column label="结果状态" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item
:prop="`${$index}.reportFlag`" :rules="formRules.reportFlag"
                        class="mb-0px!">
            <el-select v-model="row.reportFlag" placeholder="请选择结果状态" :disabled="!isEditable " >
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_INSPECTION_RESULT_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="下限" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.minValue`" :rules="formRules.minValue" class="mb-0px!" v-if="row.reportType == 1" >
            <el-input v-model="row.minValue"  disabled/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="上限" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.maxValue`" :rules="formRules.maxValue" class="mb-0px!" v-if="row.reportType == 1" >
            <el-input v-model="row.maxValue"   disabled/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="上传图片" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.pics`"  class="mb-0px!">
            <UploadImgs v-model="row.pics" :limit="5" :disabled="!isEditable" height="56px" width="56px" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="异常说明" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" :rules="formRules.remark" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入说明" :disabled="!isEditable "/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column
align="center" fixed="right" label="操作" width="60"
                       v-if="isEditable && !disabled">
        <template #default="{ row, $index }">
          <el-button @click="handleSave(row, $index)" link type="primary">保存</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <!--  <el-row justify="center" class="mt-3" v-if="!disabled">-->
  <!--    <el-button @click="handleAdd" round>+ 添加设备巡检任务内容</el-button>-->
  <!--  </el-row>-->
</template>
<script setup lang="ts">
import {getIntDictOptions, DICT_TYPE} from '@/utils/dict'
import {InspectionTasksApi} from '@/api/device/inspectiontasks'
import {Message as message} from "@/layout/components/Message";

const props = defineProps<{
  taskId: number // 巡检任务ID（主表的关联字段）
  disabled?: boolean // 是否禁用（详情模式）
  taskStatus: number
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref<any[]>([])
const formRules = reactive({
  taskId: [{required: true, message: '巡检任务ID不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref

// 添加在其他 computed 属性后面
const isEditable = computed(() => {
  // 当前只允许 taskStatus 为 3 时编辑，
  return props.taskStatus == 2;
});

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
    () => props.taskId,
    async (val) => {
      // 1. 重置表单
      formData.value = []
      // 2. val 非空，则加载数据
      if (!val) {
        return;
      }
      try {
        formLoading.value = true
        formData.value = await InspectionTasksApi.getInspectionTasksItemListByTaskId(val)
        // pics 处理,不为空时 转换为数组
        formData.value.forEach(item => { if (item.pics) { item.pics = item.pics.split(',') }})
      } finally {
        formLoading.value = false
      }
    },
    {immediate: true}
)


/** 保存按钮操作 */
const handleSave = async (row, index) => {
  // 表单校验
  const valid = await formRef.value.validateField(`${index}`)
  if (!valid) return

  try {
    formLoading.value = true
    // 调用保存接口，传递实际开始时间
    const saveData = {
      ...row,
      taskId: props.taskId
    }
    // 处理pics 字段 为逗号分隔的字符串
    if (row.pics){
      saveData.pics = row.pics.join(',')
    }

    // 使用同一个接口处理新增和更新
    const res = await InspectionTasksApi.rowCreateInspectionItemTasks(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 handleResultFlagChange = (row) => {
  // 检查是否可编辑且填报类型为2（选择框类型）
  if (isEditable.value && row.reportType === 2 && row.resultFlag !== undefined) {
    // 将 resultFlag 的值同步赋给 reportFlag
    row.reportFlag = row.resultFlag;
  }
}


/**
 * 处理结果值变化，判断是否在范围内并更新结果状态
 */
const handleReportValueChange = (row) => {
  // 检查是否可编辑且填报类型为1（输入框类型）
  if (isEditable.value && row.reportType === 1 && row.reportValue !== undefined) {
    // 判断是否在范围内
    const minValue = parseFloat(row.minValue);
    const maxValue = parseFloat(row.maxValue);
    const reportValue = parseFloat(row.reportValue);

    // 只有当上下限都存在且为有效数字时才进行范围判断
    if (!isNaN(reportValue) && !isNaN(minValue) && !isNaN(maxValue)) {
      if (reportValue >= minValue && reportValue <= maxValue) {
        // 在范围内，设置为正常状态
        row.reportFlag = 1;
      } else {
        // 超出范围，设置为异常状态
        row.reportFlag = 0;
      }
    } else if (!isNaN(reportValue)) {
      // 如果没有有效的上下限，只要有有效值就设为正常
      row.reportFlag = 1;
    }
  }
}


/** 删除按钮操作 */
const handleDelete = (index) => {
  // 详情模式下不能删除
  if (props.disabled) {
    return
  }

  formData.value.splice(index, 1)
}

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

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

defineExpose({validate, getData})
</script>
