<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1400px;">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <div class="form-section">
        <div class="section-title">基本信息</div>
        <el-row :gutter="20">
          <el-col :sm="12" :md="8">
            <el-form-item label="任务编号" prop="taskNo">
              <el-input v-model="formData.taskNumber" :disabled="isExecuteMode || isReadonlyMode" />
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="formData.planName" :disabled="isExecuteMode || isReadonlyMode" />
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="formData.taskName" :disabled="isExecuteMode || isReadonlyMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :sm="12" :md="8">
            <el-form-item label="计划开始时间" prop="planStartTime">
              <el-date-picker
                v-model="formData.planStartTime"
                type="datetime"
                value-format="x"
                style="width: 100%"
                :disabled="isExecuteMode || isReadonlyMode"
              />
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="计划结束时间" prop="planEndTime">
              <el-date-picker
                v-model="formData.planEndTime"
                type="datetime"
                value-format="x"
                style="width: 100%"
                :disabled="isExecuteMode || isReadonlyMode"
              />
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="实际完成时间" prop="actualEndTime">
              <el-date-picker
                v-model="formData.actualEndTime"
                type="datetime"
                value-format="x"
                style="width: 100%"
                :disabled="isExecuteMode || isReadonlyMode"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 子表的表单 -->
      <el-tabs v-model="subTabsName">
        <el-tab-pane label="保养设备" name="deviceInfo">
          <el-row :gutter="20">
            <el-col :sm="12" :md="8">
              <el-form-item label="设备名称" prop="deviceName">
                <el-input
                  v-model="formData.deviceName"
                  :disabled="isExecuteMode || isReadonlyMode"
                />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :md="8">
              <el-form-item label="设备编码" prop="deviceNumber">
                <el-input
                  v-model="formData.deviceNumber"
                  :disabled="isExecuteMode || isReadonlyMode"
                />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :md="8">
              <el-form-item label="资产编号" prop="assetNumber">
                <el-input
                  v-model="formData.assetNumber"
                  :disabled="isExecuteMode || isReadonlyMode"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :sm="12" :md="8">
              <el-form-item label="实际开始时间" prop="actualStartTime">
                <el-date-picker
                  v-model="formData.actualStartTime"
                  type="datetime"
                  value-format="x"
                  style="width: 100%"
                  :disabled="isExecuteMode || isReadonlyMode"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 使用带背景色的标题 -->
          <div style="margin-top: 20px; background: #f5f7fa; border-radius: 4px; overflow: hidden">
            <div
              style="
                padding: 12px 20px;
                background: #f5f7fa;
                border-bottom: 1px solid #ebeef5;
                font-weight: bold;
              "
            >
              保养内容
            </div>
            <div style="padding: 20px">
              <MaintenanceTaskItemForm
                ref="maintenanceTaskItemFormRef"
                :task-id="formData.id"
                :readonly="isExecuteMode || isReadonlyMode"
              />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="保养方案" name="maintenancePlan">
          <el-row :gutter="20">
            <el-col :sm="12" :md="8">
              <el-form-item label="保养班组" prop="teamId">
                <el-select
                  v-model="formData.teamId"
                  placeholder="请选择保养班组"
                  :disabled="isExecuteMode || isReadonlyMode"
                  :clearable="true"
                  style="width: 100%"
                >
                  <el-option
                    v-for="team in maintenanceTeamList"
                    :key="team.id"
                    :label="team.teamName"
                    :value="team.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="12" :md="8">
              <el-form-item label="班组成员" prop="teamStaffIds">
                <el-select
                  v-model="formData.teamStaffIdList"
                  multiple
                  :disabled="isExecuteMode || isReadonlyMode"
                  placeholder="请选择班组成员"
                  style="width: 100%"
                >
                  <el-option
                    v-for="staff in staffList"
                    :key="staff.id"
                    :label="staff.nickname"
                    :value="staff.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :sm="12" :md="8">
              <el-form-item label="超时提醒人" prop="timeoutReminder">
                <el-select
                  v-model="formData.timeoutReminder"
                  :disabled="isExecuteMode || isReadonlyMode"
                >
                  <el-option
                    v-for="staff in staffList"
                    :key="staff.id"
                    :label="staff.nickname"
                    :value="staff.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="12" :md="8">
              <el-form-item label="任务限制工时" prop="timeoutHour">
                <el-input
                  v-model="formData.timeoutHour"
                  :disabled="isExecuteMode || isReadonlyMode"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="工时记录" name="maintenanceTaskHours">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="维修总工时(小时)" prop="planStartTime">
                <el-input
                  v-model="formData.totalMaintenanceHours"
                  :disabled="isExecuteMode || isReadonlyMode"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <MaintenanceTaskHoursForm
            ref="maintenanceTaskHoursFormRef"
            :task-id="formData.id"
            :readonly="isExecuteMode || isReadonlyMode"
            :actual-start-time="formData.actualStartTime"
            :task-status="formData.taskStatus"
          />

          <el-row :gutter="20" style="margin-top: 30px">
            <el-col :sm="12" :md="10">
              <el-form-item label="验收时间" prop="inspectionTime">
                <el-date-picker
                  v-model="formData.inspectionTime"
                  type="datetime"
                  value-format="x"
                  style="width: 100%"
                  :disabled="!isInspectionFieldEditable"
                />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :md="10">
              <el-form-item label="验收责任人" prop="inspectorName">
                <el-select
                  v-model="formData.inspectorName"
                  placeholder="请选择保养人"
                  @change="handleInspectorChange"
                  :disabled="!isInspectionFieldEditable"
                  style="width: 100%"
                >
                  <el-option
                    v-for="staff in staffList"
                    :key="staff.id"
                    :label="staff.nickname"
                    :value="staff.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="保养遗留问题" prop="inspectionDescription">
                <el-input
                  v-model="formData.inspectionDescription"
                  type="textarea"
                  :rows="4"
                  :disabled="!isInspectionFieldEditable"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!isReadonlyMode"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { MaintenanceTasksApi, MaintenanceTasksVO } from '@/api/device/maintenancetasks'
import { MaintenanceTaskHoursApi } from '@/api/device/maintenancetaskhours'
import { MaintenanceTeamApi } from '@/api/device/maintenanceteam'
import { getSimpleUserList } from '@/api/system/user'

import MaintenanceTaskConsumableForm from './components/MaintenanceTaskConsumableForm.vue'
import MaintenanceTaskItemForm from './components/MaintenanceTaskItemForm.vue'
import MaintenanceTaskHoursForm from './components/MaintenanceTaskHoursForm.vue'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'

/** 设备保养任务 表单 */
defineOptions({ name: 'MaintenanceTasksForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const isExecuteMode = computed(() => formType.value === 'execute') // 是否为保养执行模式
const isReadonlyMode = computed(() => formType.value === 'detail') // 是否为详情查看模式

// 判断是否为验收相关字段可编辑状态
const isInspectionFieldEditable = computed(() => {
  // 只有在验收中状态时，验收相关字段才可以编辑
  return formData.value.taskStatus === 3 || isExecuteMode.value
})

const formData = ref({
  id: undefined,
  taskNo: undefined,
  taskName: undefined,
  maintenancePlan: undefined, // 添加保养方案字段
  teamStaffIdList: []
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('deviceInfo')
const maintenanceTaskConsumableFormRef = ref()
const maintenanceTaskItemFormRef = ref()
const maintenanceTaskHoursFormRef = ref()

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

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'execute' ? '保养执行' : t('action.' + type)
  formType.value = type
  resetForm()
  // 获取用户列表
  await getStaffList()
  // 获取班组
  await getTeamList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const res = await MaintenanceTasksApi.getMaintenanceTasks(id)
      formData.value = res

      // 处理班组成员ID字符串，转换为数组
      if (res.teamStaffIds && typeof res.teamStaffIds === 'string') {
        formData.value.teamStaffIdList = res.teamStaffIds
          .split(',')
          .map((id) => parseInt(id, 10))
          .filter((id) => !isNaN(id))
      } else if (Array.isArray(res.teamStaffIds)) {
        formData.value.teamStaffIdList = res.teamStaffIds
      } else {
        formData.value.teamStaffIdList = []
      }

      // 将子表数据传递给对应的子组件
      nextTick(() => {
        if (res.taskHoursList && maintenanceTaskHoursFormRef.value) {
          maintenanceTaskHoursFormRef.value.setData(res.taskHoursList)
        }
        if (res.consumableList && maintenanceTaskConsumableFormRef.value) {
          maintenanceTaskConsumableFormRef.value.setData(res.consumableList)
        }
        if (res.planItemList && maintenanceTaskItemFormRef.value) {
          maintenanceTaskItemFormRef.value.setData(res.planItemList)
        }
      })
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!isExecuteMode.value) {
    await formRef.value.validate()
  }

  // 校验子表单（只校验工时记录）
  try {
    await maintenanceTaskHoursFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'maintenanceTaskHours'
    return
  }

  // 提交请求（只提交工时记录）
  formLoading.value = true
  try {
    const data = {
      taskId: formData.value.id,
      taskHoursList: maintenanceTaskHoursFormRef.value.getData()
    } as any
    // 获取所有子表的数据
    // data.maintenanceTaskItem = maintenanceTaskItemFormRef.value.getData()
    // data.maintenanceTaskConsumable = maintenanceTaskConsumableFormRef.value.getData()
    // data.maintenanceTaskHours = maintenanceTaskHoursFormRef.value.getData()

    if (formType.value === 'create') {
      await MaintenanceTaskHoursApi.updateMaintenanceTaskHours(data)
      message.success(t('common.createSuccess'))
    } else {
      await MaintenanceTaskHoursApi.updateMaintenanceTaskHours(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    taskNo: undefined,
    taskName: undefined,
    maintenancePlan: undefined,
    teamStaffIdList: []
  }
  formRef.value?.resetFields()
}

/** 获取用户列表 */
const getStaffList = async () => {
  try {
    staffList.value = await getSimpleUserList()
  } catch (error) {
    message.error('获取用户列表失败')
  }
}

// 查询班组列表
const getTeamList = async () => {
  let result = await MaintenanceTeamApi.getMaintenanceTeamPage({
    pageNo: 1,
    pageSize: 100,
    state: 0
  })
  maintenanceTeamList.value = result.list || []
}

// 选择标准事件
const handleInspectorChange = async (val) => {
  if (!val) {
    return
  }
  // 根据选中的用户ID找到对应的用户信息
  const selectedStaff = staffList.value.find((staff) => staff.id === val)
  if (selectedStaff) {
    // 将ID和名称分别赋值给对应的表单字段
    formData.value.inspectorId = val.id
    formData.value.inspectorName = selectedStaff.nickname
  }
}
</script>

<style scoped>
.form-section {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #409eff;
  margin-bottom: 15px;
  padding-left: 5px;
  border-left: 3px solid #409eff;
}

.el-divider {
  margin: 10px 0;
}

.el-form-item {
  margin-bottom: 15px;
}
</style>
