<template>
  <ContentWrap>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <div class="form-section">
        <el-row :gutter="20">
          <el-col :sm="12" :md="8">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="formData.planName" :disabled="isDetailMode"/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="任务编号" prop="taskNo">
              <el-input v-model="formData.taskNumber" :disabled="isDetailMode"/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="formData.taskName" :disabled="isDetailMode"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :sm="12" :md="8">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="formData.deviceName" :disabled="isDetailMode"/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="设备编码" prop="deviceNumber">
              <el-input v-model="formData.deviceNumber" :disabled="isDetailMode"/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="资产编号" prop="assetType">
              <el-input v-model="formData.assetNumber" :disabled="isDetailMode"/>
            </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="isDetailMode"
              />
            </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="isDetailMode"
              />
            </el-form-item>
          </el-col>

        </el-row>

      </div>

      <!-- 子表的表单 -->
      <el-tabs v-model="subTabsName">
        <el-tab-pane label="保养设备" name="deviceInfo">
          <div class="form-section">
            <div class="section-title">保养内容</div>
          <MaintenanceTaskItemForm
            ref="maintenanceTaskItemFormRef"
            :task-id="formData.id"
            :readonly="isDetailMode"
          />
          </div>

          <div class="form-section" v-if="formData.taskStatus > 1">
            <div class="section-title">执行信息</div>
          <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="formData.taskStatus != 2 "
                  @change="updateExecute"
                />
              </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="formData.taskStatus != 2 "
                  @change="updateExecute"
                />
              </el-form-item>
            </el-col>
<!--            <el-col :span="8">
              <el-form-item label="总工时" >
                <el-input type="number" v-model="formData.totalMaintenanceHours" placeholder="维修总工时(小时)"
                          :disabled="formData.taskStatus != 2 && formData.taskStatus != 3" />
              </el-form-item>
            </el-col>-->
          </el-row>
          <div style="padding-top: 10px;">
          <MaintenanceTaskHoursForm
            ref="maintenanceTaskHoursFormRef"
            :task-id="formData.id"
            :readonly="false"
            :actual-start-time="formData.actualStartTime"
            :task-status="formData.taskStatus"
          />
          </div>
          </div>

          <div class="form-section" v-if="formData.taskStatus > 2">
            <div class="section-title">验收信息</div>
          <el-row :gutter="20" style="margin-top: 30px;">
            <el-col :sm="12" :md="8">
              <el-form-item label="验收时间" prop="inspectionTime">
                <el-date-picker
                  v-model="formData.inspectionTime"
                  type="datetime"
                  value-format="x"
                  style="width: 100%"
                  :disabled="!isInspectionFieldEditable"

                  @change="updateCheck"
                />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="保养遗留问题" prop="inspectionDescription">
                <el-input
                  v-model="formData.inspectionDescription"
                  type="textarea"
                  :rows="4"
                  :disabled="!isInspectionFieldEditable"
                  @change="updateCheck"
                />
              </el-form-item>
            </el-col>
          </el-row>
          </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="isDetailMode" :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="isDetailMode"
                  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="isDetailMode">
                  <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="isDetailMode"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>

      </el-tabs>
    </el-form>
  </ContentWrap>
</template>
<script lang="ts" setup>
import {MaintenanceTasksApi} from '@/api/device/maintenancetasks'
import { MaintenanceTeamApi } from '@/api/device/maintenanceteam'

import MaintenanceTaskItemForm from './components/MaintenanceTaskItemForm.vue'
import MaintenanceTaskHoursForm from './components/MaintenanceTaskHoursForm.vue'
import {propTypes} from '@/utils/propTypes'
import {getSimpleUserList} from "@/api/system/user";
import {Message as message} from "@/layout/components/Message";
import {ref} from "vue";
import {RepairOrderApi, RepairOrderVO} from "@/api/device/repairorder";
import {t} from "@wangeditor/editor";

defineOptions({name: 'MaintenanceTasksDetail'})

const formData = ref({
  id: undefined,
  taskNo: undefined,
  taskName: undefined,
  maintenancePlan: undefined, // 添加保养方案字段
  teamStaffIdList: []
})
/** 子表的表单 */
const subTabsName = ref('deviceInfo')
const maintenanceTaskConsumableFormRef = ref()
const maintenanceTaskItemFormRef = ref()
const maintenanceTaskHoursFormRef = ref()


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

const props = defineProps({
  processInstanceId: propTypes.string.def(undefined)
})
const detailLoading = ref(false) // 表单的加载中
const detailData = ref<any>({}) // 详情数据
const queryId = query.id as unknown as number // 从 URL 传递过来的 id 编号
// 任务状态 0-新建 1-审批中 2-执行中 3-验收中 10-完成
// 判断是否为验收相关字段可编辑状态
const isInspectionFieldEditable = computed(() => {
  // 只有在验收中状态时，验收相关字段才可以编辑
  return formData.value.taskStatus === 3;
});

const isDetailMode = computed(() => !!queryId)

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


// 修改open方法，添加ID字符串到数组的转换
const open = async () => {
  let processInstanceId = props.processInstanceId || queryId
  // 修改时，设置数据
  if (processInstanceId) {
    detailLoading.value = true
    try {
      const res = await MaintenanceTasksApi.getMaintenanceTasksByProcessId(processInstanceId)
      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 {
      detailLoading.value = false
    }
  }
}

defineExpose({open}) // 提供 open 方法，用于打开弹窗
/** 获取用户列表 */
const getStaffList = async () => {
  try {
    staffList.value = await getSimpleUserList()
  } catch (error) {
    message.error('获取用户列表失败')
  }
}

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

/** 初始化 **/
onMounted(() => {
  open()
  // 获取用户列表
  getStaffList();
  // 获取班组
  getTeamList();
})

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

</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;
}

.qrcode-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 5px;
}

.qrcode-placeholder {
  color: #909399;
  font-size: 12px;
  text-align: center;
}

:deep(.max-dialog .el-dialog) {
  max-width: 100%;
  height: 100vh;
  margin: 0 !important;
  display: flex;
  flex-direction: column;
}

:deep(.max-dialog .el-dialog__body) {
  flex: 1;
  overflow: hidden;
  padding: 0;
}
</style>
