<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑维修记录' : '新建维修记录'"
    width="700px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="资产" prop="assetId">
        <el-select
          v-model="formData.assetId"
          placeholder="请选择资产"
          filterable
          :disabled="isEdit"
        >
          <el-option
            v-for="asset in assets"
            :key="asset.id"
            :label="`${asset.assetCode} - ${asset.assetName}`"
            :value="asset.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="故障类型" prop="faultType">
        <el-select v-model="formData.faultType" placeholder="请选择">
          <el-option
            v-for="(item, key) in FAULT_TYPE"
            :key="key"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="优先级" prop="priority">
        <el-radio-group v-model="formData.priority">
          <el-radio label="low">低</el-radio>
          <el-radio label="medium">中</el-radio>
          <el-radio label="high">高</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="维修类型" prop="maintenanceType">
        <el-radio-group v-model="formData.maintenanceType">
          <el-radio label="self_repair">自行维修</el-radio>
          <el-radio label="vendor_repair">厂商维修</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="故障描述" prop="faultDescription">
        <el-input
          v-model="formData.faultDescription"
          type="textarea"
          :rows="4"
          placeholder="请详细描述故障情况"
          maxlength="1000"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="维修人员" prop="maintenancePersonnel">
        <el-input
          v-model="formData.maintenancePersonnel"
          placeholder="请输入维修人员姓名"
        />
      </el-form-item>

      <el-form-item label="维修费用" prop="maintenanceCost">
        <el-input-number
          v-model="formData.maintenanceCost"
          :min="0"
          :precision="2"
          :step="100"
          controls-position="right"
        />
        <span style="margin-left: 8px">元</span>
      </el-form-item>

      <el-form-item label="维修时间">
        <el-date-picker
          v-model="maintenanceDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="维修备注">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入维修备注"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="维修照片">
        <el-upload
          v-model:file-list="photoList"
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :limit="5"
          accept="image/*"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { createMaintenanceRecord, updateMaintenanceRecord, getAssetList } from '@/api'
import { FAULT_TYPE } from '@/utils/constants'

interface Props {
  modelValue: boolean
  recordId?: number | null
  assetId?: number | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.recordId)

const formRef = ref()
const submitting = ref(false)
const assets = ref<any[]>([])
const maintenanceDateRange = ref<string[]>([])
const photoList = ref<any[]>([])

const formData = reactive({
  assetId: undefined,
  faultType: 'hardware',
  priority: 'medium',
  maintenanceType: 'self_repair',
  faultDescription: '',
  maintenancePersonnel: '',
  maintenanceCost: 0,
  remark: ''
})

const formRules = {
  assetId: [
    { required: true, message: '请选择资产', trigger: 'change' }
  ],
  faultType: [
    { required: true, message: '请选择故障类型', trigger: 'change' }
  ],
  faultDescription: [
    { required: true, message: '请输入故障描述', trigger: 'blur' },
    { min: 10, max: 1000, message: '描述长度在 10 到 1000 个字符', trigger: 'blur' }
  ]
}

// 获取资产列表
const fetchAssets = async () => {
  try {
    const data = await getAssetList({
      page: 1,
      page_size: 1000,
      status: 'in_use'
    })
    assets.value = data.items
  } catch (error) {
    console.error('获取资产列表失败', error)
  }
}

// 提交
const handleSubmit = async () => {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return

  submitting.value = true

  try {
    const data = {
      ...formData,
      startDate: maintenanceDateRange.value[0],
      endDate: maintenanceDateRange.value[1]
    }

    if (isEdit.value) {
      await updateMaintenanceRecord(props.recordId!, data)
      ElMessage.success('更新成功')
    } else {
      await createMaintenanceRecord(data)
      ElMessage.success('创建成功')
    }

    emit('success')
    handleClose()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  setTimeout(() => {
    formRef.value?.resetFields()
    maintenanceDateRange.value = []
    photoList.value = []
    Object.assign(formData, {
      assetId: undefined,
      faultType: 'hardware',
      priority: 'medium',
      maintenanceType: 'self_repair',
      faultDescription: '',
      maintenancePersonnel: '',
      maintenanceCost: 0,
      remark: ''
    })
  }, 300)
}

// 初始化
fetchAssets()
</script>

<style scoped lang="scss">
:deep(.el-input-number) {
  width: 200px;
}
</style>
