<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1400px;" >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >

      <el-row :gutter="20">

        <el-col :sm="12" :md="12">
          <el-form-item label="报修设备" prop="deviceId">
            <el-select
                v-model="formData.deviceId"
                placeholder="请选择设备"
                clearable
                filterable
                @change="handleDeviceChange($event)"
            >
              <el-option
                  v-for="device in deviceList"
                  :key="device.id"
                  :label="device.deviceName"
                  :value="device.id"
              />
            </el-select>

          </el-form-item>
        </el-col>

        <el-col :sm="12" :md="12">
          <el-form-item label="报修时间" prop="reportTime">
            <el-date-picker
                v-model="formData.reportTime"
                type="datetime"
                value-format="x"
                placeholder="选择报修时间"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :sm="12" :md="12">
          <el-form-item label="报修人" prop="reportId">
            <el-select
                v-model="formData.reportId"
                placeholder="请选择"
                style="width: 100%"
                filterable
                clearable
            >
              <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="12">
          <el-form-item label="报修部门" prop="reportDeptId">
            <el-tree-select
                v-model="formData.reportDeptId"
                :data="deptTree"
                :props="defaultProps"
                check-strictly
                node-key="id"
                placeholder="请选择报修部门"
                filterable
            />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :md="12">
          <el-form-item label="联系方式" prop="reportPhone">
            <el-input v-model="formData.reportPhone" placeholder="请输入联系方式" />
          </el-form-item>
        </el-col>

        <el-col :sm="12" :md="12">
          <el-form-item label="故障来源" prop="faultSource">
            <el-select v-model="formData.faultSource" placeholder="请选择故障来源">
              <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="12">
          <el-form-item label="紧急程度" prop="faultLevel">
            <el-select v-model="formData.faultLevel" placeholder="请选择紧急程度">
              <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="12">
          <el-form-item label="故障类型" prop="faultSceneId">
            <el-select
                v-model="formData.faultSceneId"
                placeholder="请选择"
                style="width: 100%"
                filterable
                clearable
            >
              <el-option
                  v-for="item in faultSceneList"
                  :key="item.id"
                  :label="item.sceneName"
                  :value="item.id"
              />
            </el-select>

          </el-form-item>
        </el-col>

        <el-col :sm="12" :md="24">
          <el-form-item label="故障图片" prop="faultPics">
            <UploadImgs v-model="formData.faultPics" class="min-w-80px" />
          </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" placeholder="请输入故障说明" />
          </el-form-item>
        </el-col>

        <el-col :sm="12" :md="12" >
          <el-form-item label="维修预计费用" prop="repairExpectedCost">
            <el-input v-model="formData.repairExpectedCost" placeholder="请输入维修预计费用" />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :md="12" >
          <el-form-item label="费用承担部门" prop="repairCostDept">
            <el-tree-select
                v-model="formData.repairCostDept"
                :data="deptTree"
                :props="defaultProps"
                check-strictly
                node-key="id"
                placeholder="请选择"
                filterable
            />
          </el-form-item>
        </el-col>

        <el-col :sm="12" :md="24">
          <el-form-item label="维修方式" prop="repairType">
            <el-select v-model="formData.repairType" placeholder="请选择维修方式">
              <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="12" v-if="formData.repairType == 2">
          <el-form-item label="维修供应商" prop="repairCompanyName">
            <el-input v-model="formData.repairCompanyName" placeholder="请输入维修供应商" />
          </el-form-item>
        </el-col>


      </el-row>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { RepairOrderApi, RepairOrderVO } from '@/api/device/repairorder'
import * as DeptApi from '@/api/system/dept'
import { defaultProps, handleTree } from '@/utils/tree'
import {RepairFaultSceneApi, RepairFaultSceneVO} from "@/api/device/repairfaultscene";
import {getSimpleUserList} from '@/api/system/user'
import {ref} from "vue";
import {InfoApi, InfoVO  } from "@/api/device/info";

/** 设备维修工单 表单 */
defineOptions({ name: 'RepairOrderForm' })

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 formData = ref({
  id: undefined,
  deviceId: undefined,
  reportId: undefined,
  reportTime: undefined,
  reportDeptId: undefined,
  reportPhone: undefined,
  faultLevel: undefined,
  faultSceneId: undefined,
  faultPics: 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 formRules = reactive({
  deviceId: [{ required: true, message: '报修设备不能为空', trigger: 'blur' }],
  reportId: [{ required: true, message: '报修人不能为空', trigger: 'blur' }],
  reportPhone: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
  repairType: [{ required: true, message: '维修方式不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()


  await Promise.all([
    deptTree.value = handleTree(await DeptApi.getSimpleDeptList()),
  ]);

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RepairOrderApi.getRepairOrder(id)
      // 故障图片字符串转为数组
      formData.value.faultPics = formData.value.faultPics ? formData.value.faultPics.split(',') : []
    } finally {
      formLoading.value = false
    }
  }

  await getDeviceList();
  await getStaffList();
  await getFaultSceneList();
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RepairOrderVO
    // 故障图片数组转为字符串
    data.faultPics = data.faultPics ? data.faultPics.join(',') : ''

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceId: undefined,
    reportId: undefined,
    reportTime: undefined,
    reportDeptId: undefined,
    reportPhone: undefined,
    faultLevel: undefined,
    faultSceneId: undefined,
    faultPics: undefined,
    faultContent: undefined,
    faultSource: 2,  // 默认为设备报修
    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,
  }
  formRef.value?.resetFields()
}


const deviceList = ref<any[]>([])
/** 获取设备列表 */
const getDeviceList = async () => {
  try {
    const res = await InfoApi.getInfoPage({
      pageNo: 1,
      pageSize: 100,
    })
    deviceList.value = res.list || []
  } catch (error) {
    console.error('获取设备列表失败:', error)
  }
}
const handleDeviceChange = (deviceId) => {
    if (deviceId) {
        const selectedDevice = deviceList.value.find(device => device.id === deviceId)
        if (selectedDevice) {
            formData.value.deviceName = selectedDevice.deviceName
        }
    }
}

const deptTree = ref<Tree[]>([]) // 树形结构
const faultSceneList = ref<RepairFaultSceneVO[]>([]) //
const getFaultSceneList = async () => {
  try {
    let result = await RepairFaultSceneApi.getRepairFaultScenePage({
      pageNo: 1,
      pageSize: 99,
    })
    faultSceneList.value = result.list || [];
  } catch (error) {
    message.error('获取故障类型列表失败')
  }
}
const staffList = ref<any[]>([]) // 用户列表
/** 获取用户列表 */
const getStaffList = async () => {
  try {
    // 假设 UserApi.getUserList() 是获取用户列表的方法
    staffList.value = await getSimpleUserList()
  } catch (error) {
    message.error('获取用户列表失败')
  }
}
</script>
