<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :width="800">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工单编号" prop="workOrderCode">
            <el-select
              v-model="formData.workOrderCode"
              placeholder="请选择工单编号"
              filterable
              allow-create
              default-first-option
              :disabled="formType === 'view'"
              @change="handleWorkOrderChange"
              class="w-full"
            >
              <el-option
                v-for="item in workOrderOptions"
                :key="item.id"
                :label="`${item.code} - ${item.productName}`"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="消耗时间" prop="consumptionTime">
            <el-date-picker
              v-model="formData.consumptionTime"
              type="datetime"
              placeholder="选择消耗时间"
              :disabled="formType === 'view'"
              value-format="YYYY-MM-DDTHH:mm:ss"
              class="w-full"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="煤消耗量" prop="coalConsumption">
            <div class="flex items-center gap-2">
              <el-input-number
                v-model="formData.coalConsumption"
                :min="0"
                :step="0.01"
                :precision="2"
                :disabled="formType === 'view'"
                class="flex-1"
              />
              <span class="text-gray-500">吨</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="蒸汽产量" prop="steamOutput">
            <div class="flex items-center gap-2">
              <el-input-number
                v-model="formData.steamOutput"
                :min="0"
                :step="0.01"
                :precision="2"
                :disabled="formType === 'view'"
                class="flex-1"
              />
              <span class="text-gray-500">吨</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用电量" prop="electricityConsumption">
            <div class="flex items-center gap-2">
              <el-input-number
                v-model="formData.electricityConsumption"
                :min="0"
                :step="0.1"
                :precision="1"
                :disabled="formType === 'view'"
                class="flex-1"
              />
              <span class="text-gray-500">千瓦时</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用水量" prop="waterConsumption">
            <div class="flex items-center gap-2">
              <el-input-number
                v-model="formData.waterConsumption"
                :min="0"
                :step="0.1"
                :precision="1"
                :disabled="formType === 'view'"
                class="flex-1"
              />
              <span class="text-gray-500">立方米</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注"
          :disabled="formType === 'view'"
          :rows="3"
        />
      </el-form-item>

      <!-- 审核信息显示（仅在查看模式下显示） -->
      <template v-if="formType === 'view' && formData.auditStatus !== 0">
        <el-divider content-position="left">审核信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="审核状态">
              <dict-tag :type="DICT_TYPE.MES_ENERGY_AUDIT_STATUS" :value="formData.auditStatus" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核人">
              <span>{{ formData.auditorName || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核时间">
              <span>{{ formatDate(formData.auditTime) || '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="审核意见">
          <span>{{ formData.auditRemark || '-' }}</span>
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="formType !== 'view'">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import {
  getEnergyConsumption,
  createEnergyConsumption,
  updateEnergyConsumption
} from '@/api/mes/energy/consumption'
import { YVHgetWorkOrderSimpleList } from '@/api/mes/production/workorder'

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  code: '',
  workOrderId: undefined,
  workOrderCode: '',
  consumptionTime: '',
  coalConsumption: undefined,
  steamOutput: undefined,
  electricityConsumption: undefined,
  waterConsumption: undefined,
  remark: '',
  auditStatus: 0,
  auditorName: '',
  auditTime: '',
  auditRemark: ''
})
const formRules = reactive({
  workOrderCode: [{ required: true, message: '工单编号不能为空', trigger: 'blur' }],
  consumptionTime: [{ required: true, message: '消耗时间不能为空', trigger: 'blur' }],
  coalConsumption: [{ required: true, message: '煤消耗量不能为空', trigger: 'blur' }],
  steamOutput: [{ required: true, message: '蒸汽产量不能为空', trigger: 'blur' }],
  electricityConsumption: [{ required: true, message: '用电量不能为空', trigger: 'blur' }],
  waterConsumption: [{ required: true, message: '用水量不能为空', trigger: 'blur' }]
})
const formRef = ref()
const workOrderOptions = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '添加能源消耗记录' : type === 'update' ? '修改能源消耗记录' : '查看能源消耗记录'
  formType.value = type
  resetForm()

  // 获取工单列表
  await getWorkOrderList()

  if (id) {
    formLoading.value = true
    try {
      const data = await getEnergyConsumption(id)
      Object.assign(formData.value, data)
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增时设置默认消耗时间为当前时间
    formData.value.consumptionTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
  }
}

/** 获取工单列表 */
const getWorkOrderList = async () => {
  try {
    const data = await YVHgetWorkOrderSimpleList({ status: 4 }) // 只获取已完成的工单
    workOrderOptions.value = Array.isArray(data) ? data : []
  } catch (error) {
    console.error('获取工单列表失败', error)
    message.error('获取工单列表失败')
  }
}

/** 工单选择变更处理 */
const handleWorkOrderChange = (value: string) => {
  const selectedWorkOrder = workOrderOptions.value.find((item: any) => item.code === value)
  if (selectedWorkOrder) {
    formData.value.workOrderId = selectedWorkOrder.id
    formData.value.code = selectedWorkOrder.code
  } else {
    formData.value.workOrderId = undefined
    formData.value.code = value
  }
}

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  const valid = await formRef.value.validate()
  if (!valid) return

  formLoading.value = true
  try {
    const data = { ...formData.value }
    if (formType.value === 'create') {
      await createEnergyConsumption(data)
      message.success(t('common.createSuccess'))
    } else {
      await updateEnergyConsumption(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: '',
    workOrderId: undefined,
    workOrderCode: '',
    consumptionTime: '',
    coalConsumption: undefined,
    steamOutput: undefined,
    electricityConsumption: undefined,
    waterConsumption: undefined,
    remark: '',
    auditStatus: 0,
    auditorName: '',
    auditTime: '',
    auditRemark: ''
  }
  formRef.value?.resetFields()
}

defineExpose({ open })
</script>
