<template>
  <ContentWrap>
    <el-form
        ref="formRef"
        :model="formData"
        label-width="100px"
    >
      <div class="form-section">
        <div class="section-title">报修信息</div>
        <el-row :gutter="20">
          <el-col :sm="12" :md="8">
            <el-form-item label="设备编号">
              <el-input v-model="formData.deviceNumber" disabled/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="设备名称">
              <el-input v-model="formData.deviceName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="设备类别" prop="taskName">
              <el-input v-model="formData.deviceCategoryName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="设备型号">
              <el-input v-model="formData.model" disabled/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="设备位置">
              <el-input v-model="formData.usageLocationName" disabled/>
            </el-form-item>
          </el-col>

          <el-col :sm="12" :md="8">
            <el-form-item label="故障来源" prop="faultSource">
              <el-select v-model="formData.faultSource" disabled>
                <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_REPAIR_ORDER_FAULT_SOURCE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :sm="12" :md="8">
            <el-form-item label="报修人">
              <el-input v-model="formData.reportName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="报修时间">
              <el-date-picker
                  v-model="formData.reportTime"
                  type="datetime"
                  value-format="x"
                  disabled
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="报修部门">
              <el-input v-model="formData.reportDeptName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="联系方式">
              <el-input v-model="formData.reportPhone" disabled/>
            </el-form-item>
          </el-col>




          <el-col :sm="12" :md="8">
            <el-form-item label="紧急程度" prop="faultLevel">
              <el-select v-model="formData.faultLevel" disabled>
                <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_REPAIR_ORDER_FAULT_LEVEL)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="故障类型" prop="faultSceneId">
              <el-input v-model="formData.faultSceneName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="状态" prop="state">
              <el-select v-model="formData.state" disabled>
                <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_REPAIR_ORDER_STATE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :sm="12" :md="24">
            <el-form-item label="故障图片">
              <UploadImgs v-model="faultPicsList" class="min-w-80px" disabled/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="24">
            <el-form-item label="故障说明" prop="faultContent">
              <el-input type="textarea" v-model="formData.faultContent" disabled/>
            </el-form-item>
          </el-col>


        </el-row>

      </div>
      <div class="form-section" >
        <div class="section-title">维修信息</div>
        <el-row :gutter="20">
          <el-col :sm="12" :md="8">
            <el-form-item label="维修方式" prop="repairType">
              <el-select v-model="formData.repairType" disabled>
                <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_REPAIR_ORDER_REPAIR_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :sm="12" :md="8">
            <el-form-item label="维修预计费用" prop="repairExpectedCost">
              <el-input v-model="formData.repairExpectedCost" disabled/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="费用承担部门" prop="repairCostDept">
              <el-input v-model="formData.repairCostDeptName" disabled/>
            </el-form-item>
          </el-col>


          <el-col :sm="12" :md="8" v-if="formData.repairType == 2">
            <el-form-item label="维修供应商" prop="repairCompanyName">
              <el-input v-model="formData.repairCompanyName" placeholder="请输入维修供应商" @change="updateTeam" :disabled="formData.state != 2" />
            </el-form-item>
          </el-col>

          <el-col :sm="12" :md="8" v-if="formData.repairType == 1 ">
            <el-form-item label="维修班组" prop="teamId">
              <el-select
v-model="formData.teamId"
                         placeholder="请选择"
                         @change="handleTeamChange"
                         style="width: 100%"
                         :disabled="formData.state != 2"
              >
                <el-option
                    v-for="team in repairTeamList"
                    :key="team.id"
                    :label="team.teamName"
                    :value="team.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="16" v-if="formData.repairType == 1 ">
            <el-form-item label="维修成员" prop="teamStaffIds">
              <el-select
                  v-model="selectedStaff"
                  placeholder="请选择"
                  multiple
                  @change="handleStaffChange"
                  style="width: 100%"
                  :disabled="formData.state != 2"
              >
                <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>
      </div>


      <div class="form-section" v-if="formData.state>2 " >
        <div class="section-title">接单信息</div>
        <el-row :gutter="20">
          <el-col :sm="12" :md="8" >
            <el-form-item label="维修开始时间" prop="repairStartTime">
              <el-date-picker
                  v-model="formData.repairStartTime"
                  type="datetime"
                  value-format="x"
                  placeholder="请选择"
                  style="width: 100%"
                  :disabled="formData.state != 3"
                  @change="updateTake"
              />
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8" >
            <el-form-item label="维修结束时间" prop="repairEndTime">
              <el-date-picker
                  v-model="formData.repairEndTime"
                  type="datetime"
                  value-format="x"
                  placeholder="请选择"
                  style="width: 100%"
                  :disabled="formData.state != 3"
                  @change="updateTake"
              />
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8" >
            <el-form-item label="实际用时" prop="repairHours">
              <el-input-number
:min="1" v-model="formData.repairHours" placeholder="请输入实际用时"
                               :disabled="formData.state != 3" @change="updateTake"
              />
            </el-form-item>
          </el-col>

          <el-col :sm="12" :md="8" >
            <el-form-item label="处理人" >
              <el-input :disabled="true" v-model="formData.takeName" />
            </el-form-item>
          </el-col>

          <el-col :sm="12" :md="8" >
            <el-form-item label="处理人部门" >
              <el-input :disabled="true" v-model="formData.takeDeptName" />
            </el-form-item>
          </el-col>

          <el-col :sm="12" :md="8" >
            <el-form-item label="维修结果" prop="repairResult">
              <el-select
v-model="formData.repairResult" placeholder="请选择"
                         :disabled="formData.state != 3" @change="updateTake"
              >
                <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_REPAIR_ORDER_REPAIR_RESULT)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
      </div>

      <div class="form-section" v-if="formData.state>3 ">
        <div class="section-title">验收信息</div>
        <el-row :gutter="20">
          <el-col :sm="12" :md="8" >
            <el-form-item label="验收结果" prop="inspectionResult">
              <el-select
v-model="formData.inspectionResult" placeholder="请选择"
                         :disabled="formData.state != 4" @change="updateInspection"
              >
                <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_REPAIR_ORDER_INSPECTION_RESULT)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8" >
            <el-form-item label="评价得分" prop="inspectionScore">
              <el-select
v-model="formData.inspectionScore" placeholder="请选择"
                         :disabled="formData.state != 4" @change="updateInspection"
              >
                <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_REPAIR_ORDER_INSPECTION_SCORE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8" >
            <el-form-item label="验收时间" prop="inspectionTime">
              <el-date-picker
                  v-model="formData.inspectionTime"
                  type="datetime"
                  value-format="x"
                  placeholder="请选择"
                  style="width: 100%"
                  :disabled="formData.state != 4"
                  @change="updateInspection"
              />
            </el-form-item>
          </el-col>


        </el-row>
      </div>


    </el-form>
  </ContentWrap>
</template>
<script lang="ts" setup>

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 {RepairTeamApi} from "@/api/device/repairteam";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {defaultProps} from "@/utils/tree";
import {t} from "@wangeditor/editor";
import {useUserStore} from "@/store/modules/user";

defineOptions({name: 'RepairOrderDetail'})

const formData = ref({
  id: undefined,
  deviceId: undefined,
  reportId: undefined,
  reportTime: undefined,
  reportDeptId: undefined,
  reportPhone: undefined,
  faultLevel: undefined,
  faultSceneId: undefined,
  faultContent: undefined,
  faultSource: undefined,
  state: undefined,
  repairType: undefined,
  dispatchId: undefined,
  dispatchTime: undefined,
  teamId: undefined,
  teamStaffIds: undefined,
  teamStaffNames: undefined,
  takeId: undefined,
  takeDept: undefined,
  takeTime: undefined,
  repairCompanyName: undefined,
  repairExpectedCost: undefined,
  repairCostDept: undefined,
  repairStartTime: undefined,
  repairEndTime: undefined,
  repairHours: undefined,
  repairResult: undefined,
  inspectorId: undefined,
  inspectionTime: undefined,
})


const {query} = useRoute() // 查询参数
const message = useMessage() // 消息弹窗

const props = defineProps({
  processInstanceId: propTypes.string.def(undefined)
})
const detailLoading = ref(false) // 表单的加载中
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>([]) // 用户列表
const faultPicsList = ref([]) // 用户列表


// 修改open方法，添加ID字符串到数组的转换
const open = async () => {

  // 获取班组
  await getTeamList();
  // 获取用户列表
  await getStaffList();

  let processInstanceId = props.processInstanceId || queryId

  if (processInstanceId) {
    detailLoading.value = true
    try {
      const res = await RepairOrderApi.getRepairOrderByProcessId(processInstanceId)
      formData.value = res

      // 处理班组成员ID字符串，转换为数组
      if (formData.value.teamStaffIds) {
        // 将逗号分隔的ID字符串转换为数组
        selectedStaff.value = formData.value.teamStaffIds.split(',').map(id => parseInt(id, 10))
      }
      if (!formData.value.repairResult){
        formData.value.repairResult = 1;
      }
      if (formData.value.faultPics){
        // 图片转换成数组
        faultPicsList.value = formData.value.faultPics.split(',').map(pic => pic.trim())
      }
    } finally {
      detailLoading.value = false
    }
  }
}

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

// 查询班组列表
const repairTeamList = ref([]) // 标准列表
const getTeamList = async () => {
  let result = await RepairTeamApi.getRepairTeamPage({
    pageNo: 1,
    pageSize: 100,
    state: 0
  });
  repairTeamList.value = result.list || [];
}
// 选择班组事件
const selectedStaff = ref([]) // 选中的用户
const handleTeamChange = async (val) => {
  if (!val) {
    // 如果清空了班组选择，则清空班组成员选择
    selectedStaff.value = []
    formData.value.teamStaffIds = undefined
    formData.value.teamStaffNames = undefined
    //
    await updateTeam();
    return
  }

  try {
    // 获取班组详情
    const teamDetail = await RepairTeamApi.getRepairTeam(val)
    // 从班组详情中提取成员信息
    if (teamDetail && teamDetail.teamStaffIds) {
      // 设置选中的成员ID列表（需要将字符串转换为数组）
      selectedStaff.value = teamDetail.teamStaffIds.split(',').map(id => parseInt(id, 10))

      // 设置班组成员ID和名称（直接使用返回的值）
      formData.value.teamStaffIds = teamDetail.teamStaffIds
      formData.value.teamStaffNames = teamDetail.teamStaffNames
    } else {
      // 如果没有成员信息，则清空选择
      selectedStaff.value = []
      formData.value.teamStaffIds = undefined
      formData.value.teamStaffNames = undefined
    }
  } catch (error) {
    message.error('获取班组详情失败')
    // 出错时清空班组成员选择
    selectedStaff.value = []
    formData.value.teamStaffIds = undefined
    formData.value.teamStaffNames = undefined
  }
}
/** 处理班组成员选择变化 */
const handleStaffChange = (val) => {
  // 根据选中的用户ID获取对应的用户信息
  const selectedUsers = staffList.value.filter(user => val.includes(user.id))

  // 设置ID字符串（逗号拼接）
  formData.value.teamStaffIds = selectedUsers.map(user => user.id).join(',')

  // 设置名称字符串（逗号拼接）
  formData.value.teamStaffNames = selectedUsers.map(user => user.nickname).join(',')

  //
  updateTeam();
}

/** 初始化 **/
onMounted(() => {
  open()
})
/**
 * 派单-修改维修成员信息
 */
const updateTeam = async () => {
  // 校验表单
  try {
    formData.value.faultPics = "";
    const data = formData.value as unknown as RepairOrderVO
    await RepairOrderApi.updateTeam(data)
  } finally {
  }
}
/**
 * 维修-接单信息录入
 */
const updateTake = async () => {
  // 校验表单
  try {
    formData.value.faultPics = "";
    const data = formData.value as unknown as RepairOrderVO
    await RepairOrderApi.updateTake(data)
  } finally {
  }
}
/**
 * 维修-接单信息录入
 */
const updateInspection = async () => {
  // 校验表单
  try {
    formData.value.faultPics = "";
    const data = formData.value as unknown as RepairOrderVO
    await RepairOrderApi.updateInspection(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;
}
</style>
