<template>
  <ContentWrap>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="isDetailMode"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planId">
            <el-input v-model="formData.planName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-select v-model="formData.taskStatus" placeholder="请选择是否整改" disabled>
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_INSPECTION_TASKS_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务编号" prop="taskNumber">
            <el-input v-model="formData.taskNumber" placeholder="请输入任务编号" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="formData.taskName" placeholder="请输入任务名称" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开始巡检人" prop="actualName">
            <el-select v-model="formData.actualName" placeholder="请输入开始巡检人" disabled>
              <el-option
                v-for="user in staffList"
                :key="user.id"
                :label="user.nickname"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="验收责任人" prop="inspectorName">
            <el-select
              v-model="formData.inspectorName"
              placeholder="请输入验收责任人"
              clearable
              disabled
            >
              <el-option
                v-for="user in staffList"
                :key="user.id"
                :label="user.nickname"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="超时提醒人" prop="timeoutReminderId">
            <el-select
              v-model="formData.timeoutReminder"
              placeholder="请选择任务超时提醒人"
              clearable
              disabled
            >
              <el-option
                v-for="user in staffList"
                :key="user.id"
                :label="user.nickname"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="要求时限" prop="timeoutHour">
            <el-input v-model="formData.timeoutHour" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="任务执行" name="inspectionTasksItem">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="实际开始时间" prop="actualStartTime">
              <el-date-picker
                v-model="formData.actualStartTime"
                type="datetime"
                value-format="x"
                placeholder="选择实际开始时间"
                :disabled="formData.taskStatus != 2"
                @change="updateExecute"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div
          style="margin-top: 5px; border-radius: 4px; overflow: hidden"
          v-if="formData.taskStatus > 1"
        >
          <div style="padding: 12px 20px; border-bottom: 1px solid #ebeef5; font-weight: bold">
            巡检内容
          </div>
          <div style="padding: 20px">
            <InspectionTasksItemForm
              ref="inspectionTasksItemFormRef"
              :task-id="formData.id"
              :task-status="formData.taskStatus"
            />
          </div>
        </div>

        <div
          style="margin-top: 20px; border-radius: 4px; overflow: hidden"
          v-if="formData.taskStatus > 2"
        >
          <div style="padding: 12px 20px; border-bottom: 1px solid #ebeef5; font-weight: bold">
            巡检完成
          </div>
          <div style="padding: 20px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="完成巡检" prop="rectifyFlag">
                  <el-radio-group v-model="formData.rectifyFlag" :disabled="!isEditable">
                    <el-radio :label="0" class="no-problem-radio">
                      <span class="radio-label no-problem-label">无问题</span>
                    </el-radio>
                    <el-radio :label="1" class="need-rectify-radio">
                      <span class="radio-label need-rectify-label">需整改</span>
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="实际完成时间" prop="actualEndTime">
                  <el-date-picker
                    v-model="formData.actualEndTime"
                    type="datetime"
                    value-format="x"
                    placeholder="选择实际完成时间"
                    +
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="10" v-if="formData.rectifyFlag === 1">
                <el-form-item label="整改内容" prop="rectifyContent">
                  <el-input
                    v-model="formData.rectifyContent"
                    type="textarea"
                    :disabled="!isEditable"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="现场图片" prop="inspectionPics">
                  <UploadImg v-model="formData.inspectionPics" :disabled="!isEditable" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="巡检范围" name="inspectionScope">
        <!-- 使用带背景色的标题 -->
        <div style="margin-top: 20px; border-radius: 4px; overflow: hidden">
          <div style="padding: 20px">
            <el-table :data="formData.deviceInfoList" style="width: 100%">
              <el-table-column prop="deviceNumber" label="设备编码" />
              <el-table-column prop="deviceName" label="设备名称" />
              <el-table-column prop="deviceType" label="设备类别" />
              <el-table-column prop="usageLocationName" label="功能位置" />
            </el-table>
          </div>
        </div>
        <!-- 新增的巡检方案 -->
        <div style="margin-top: 20px; border-radius: 4px; overflow: hidden">
          <div style="padding: 12px; border-bottom: 1px solid #ebeef5"> 巡检方案 </div>

          <div style="padding: 20px">
            <el-form :model="formData" :disabled="isDetailMode" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="计划开始时间" prop="planStartTime">
                    <el-date-picker
                      v-model="formData.planStartTime"
                      type="datetime"
                      value-format="x"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="巡检周期" prop="periodOneNum">
                    <el-input v-model="formData.periodOneNum" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="周期类型" prop="periodOneType">
                    <el-select
                      v-model="formData.periodOneType"
                      placeholder="请选择周期类型"
                      disabled
                    >
                      <el-option
                        v-for="dict in getIntDictOptions(
                          DICT_TYPE.DEVICE_MAINTENANCE_PERIOD_ONE_TYPE
                        )"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="巡检人员" prop="inspector">
                    <el-select v-model="formData.inspector" placeholder="请选择巡检人员" disabled>
                      <el-option
                        v-for="user in staffList"
                        :key="user.id"
                        :label="user.nickname"
                        :value="user.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="时间要求" prop="timeoutHour">
                    <el-input
                      v-model="formData.timeoutHour"
                      placeholder="请输入时间要求"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计划完成时间" prop="planEndTime">
                    <el-date-picker
                      v-model="formData.planEndTime"
                      type="datetime"
                      value-format="x"
                      disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { InspectionTasksApi } from '@/api/device/inspectiontasks'
import InspectionTasksItemForm from './components/InspectionTasksItemForm.vue'
import { propTypes } from '@/utils/propTypes'
import { getSimpleUserList } from '@/api/system/user'
import { ref } from 'vue'
import { RepairOrderVO } from '@/api/device/repairorder'
import { MaintenanceTasksApi } from '@/api/device/maintenancetasks'

/** 设备巡检任务 表单 */
defineOptions({ name: 'InspectionTasksDetail' })

const { query } = useRoute() // 查询参数

const props = defineProps({
  processInstanceId: propTypes.string.def(undefined)
})
const queryId = query.id as unknown as string // 从 URL 传递过来的 id 编号

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  planId: undefined,
  taskNumber: undefined,
  taskName: undefined,
  planStartTime: undefined,
  planEndTime: undefined,
  actualStartTime: undefined,
  actualEndTime: undefined,
  rectifyFlag: undefined,
  taskStatus: undefined,
  inspectionPics: undefined,
  rectifyContent: undefined,
  actualId: undefined,
  actualName: undefined,
  inspectorId: undefined,
  inspectorName: undefined,
  processInstanceId: undefined,
  inspectionPlanData: {
    actualStartTime: undefined,
    inspectionCycle: undefined,
    cycleType: undefined,
    inspector: undefined,
    timeRequirement: undefined,
    taskDeadline: undefined
  },
  deviceList: {}
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref

const staffList = ref([]) // 用户列表

// 计算是否为详情模式
const isDetailMode = computed(() => {
  return formType.value === 'detail'
})

/** 子表的表单 */
const subTabsName = ref('inspectionTasksItem')
const inspectionTasksItemFormRef = ref()

/** 打开弹窗 */
const open = async () => {
  let processInstanceId = props.processInstanceId || queryId
  dialogVisible.value = true
  resetForm()
  // 设置数据
  if (processInstanceId) {
    formLoading.value = true
    try {
      const res = await InspectionTasksApi.getInspectionTasksByProcessId(processInstanceId)
      formData.value = res
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 添加在其他 computed 属性后面
const isEditable = computed(() => {
  // 当前只允许 taskStatus 为 3 时编辑，后续如有其他可编辑状态可在此处扩展
  return formData.value.taskStatus === 3
})

/** 获取用户列表 */
const getStaffList = async () => {
  try {
    // 假设 UserApi.getUserList() 是获取用户列表的方法
    staffList.value = await getSimpleUserList()
  } catch (error) {
    message.error('获取用户列表失败')
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planId: undefined,
    taskNumber: undefined,
    taskName: undefined,
    planStartTime: undefined,
    planEndTime: undefined,
    actualStartTime: undefined,
    actualEndTime: undefined,
    rectifyFlag: undefined,
    taskStatus: undefined,
    inspectionPics: undefined,
    rectifyContent: undefined,
    actualId: undefined,
    actualName: undefined,
    inspectorId: undefined,
    inspectorName: undefined,
    processInstanceId: undefined,
    inspectionPlanData: {
      actualStartTime: undefined,
      inspectionCycle: undefined,
      cycleType: undefined,
      inspector: undefined,
      timeRequirement: undefined,
      taskDeadline: undefined
    }
  }
  formRef.value?.resetFields()
}

let finishTimer = null

// 监听相关字段变化，自动调用 inspectionFinish 接口
watch(
  () => [
    formData.value.rectifyFlag,
    formData.value.rectifyContent,
    formData.value.actualEndTime,
    formData.value.inspectionPics
  ],
  (newValues, oldValues) => {
    // 检查是否是编辑模式且有实际变更
    if (isEditable.value) {
      const [newRectifyFlag, newRectifyContent, newActualEndTime, newInspectionPics] = newValues
      const [oldRectifyFlag, oldRectifyContent, oldActualEndTime, oldInspectionPics] = oldValues

      // 确保不是初始加载时的触发（有实际变更才调用接口）
      if (
        (oldRectifyFlag !== undefined ||
          oldRectifyContent !== undefined ||
          oldActualEndTime !== undefined ||
          oldInspectionPics !== undefined) &&
        (newRectifyFlag !== oldRectifyFlag ||
          newRectifyContent !== oldRectifyContent ||
          newActualEndTime !== oldActualEndTime ||
          JSON.stringify(newInspectionPics) !== JSON.stringify(oldInspectionPics))
      ) {
        // 清除之前的定时器
        if (finishTimer) {
          clearTimeout(finishTimer)
        }

        // 设置新的定时器，延迟500ms调用接口
        finishTimer = setTimeout(() => {
          handleInspectionFinish()
        }, 500)
      }
    }
  },
  { deep: true }
)

// 调用 inspectionFinish 接口的方法
const handleInspectionFinish = async () => {
  try {
    formLoading.value = true
    const params = {
      id: formData.value.id,
      rectifyFlag: formData.value.rectifyFlag,
      rectifyContent: formData.value.rectifyContent,
      actualEndTime: formData.value.actualEndTime,
      inspectionPics: formData.value.inspectionPics
    }
    console.log('请求入参params:', params)
    await InspectionTasksApi.inspectionFinish(params)
    // message.success('巡检完成信息已更新')
  } catch (error) {
    message.error('巡检完成信息更新失败: ' + error.message)
  } finally {
    formLoading.value = false
  }
}

const updateExecute = async () => {
  // 校验表单
  try {
    const data = formData.value as unknown as InspectionTasksVO
    await InspectionTasksApi.updateExecute(data)
  } finally {
  }
}

/** 初始化 **/
onMounted(() => {
  open()
  // 获取用户列表
  getStaffList()
})
</script>

<style scoped>
/* 无问题单选按钮样式 - 绿色 */
.no-problem-radio {
  color: #67c23a !important;
}

.no-problem-radio .el-radio__input.is-checked + .el-radio__label {
  color: #67c23a !important;
}

/* 需整改单选按钮样式 - 红色 */
.need-rectify-radio {
  color: #f56c6c !important;
}

.need-rectify-radio .el-radio__input.is-checked + .el-radio__label {
  color: #f56c6c !important;
}

/* 选中状态下的单选按钮颜色 */
.no-problem-radio .el-radio__input.is-checked .el-radio__inner {
  border-color: #67c23a !important;
  background: #67c23a !important;
}

.need-rectify-radio .el-radio__input.is-checked .el-radio__inner {
  border-color: #f56c6c !important;
  background: #f56c6c !important;
}

/* 单选按钮标签基础样式 */
.radio-label {
  display: inline-block;
  padding: 2px 3px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.2s ease;
  margin-right: 8px;
  line-height: 1; /* 设置行高为1，避免额外高度 */
  height: 20px; /* 明确设置高度 */
  vertical-align: middle; /* 垂直居中对齐 */
}

/* 无问题标签样式 */
.no-problem-label {
  background-color: #67c23a;
  color: white;
  border: 1px solid #67c23a;
}

/* 需整改标签样式 */
.need-rectify-label {
  background-color: #f56c6c;
  color: white;
  border: 1px solid #f56c6c;
}

/* 选中状态下的标签样式 */
.no-problem-radio .el-radio__input.is-checked + .el-radio__label .radio-label {
  background-color: #67c23a;
  color: white;
  border-color: #67c23a;
}

.need-rectify-radio .el-radio__input.is-checked + .el-radio__label .radio-label {
  background-color: #f56c6c;
  color: white;
  border-color: #f56c6c;
}
</style>
