<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      min-label-width="80px"
    >
      <el-form-item :label="t('EquipmentManagement.CapacityReport.deviceCode')" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          :placeholder="t('EquipmentManagement.CapacityReport.placeholderDeviceCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.CapacityReport.deviceName')" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          :placeholder="t('EquipmentManagement.CapacityReport.placeholderDeviceName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.CapacityReport.deviceType')" prop="deviceType">
        <el-input
          v-model="queryParams.deviceType"
          :placeholder="t('EquipmentManagement.CapacityReport.placeholderDeviceType')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.CapacityReport.deviceStatus')" prop="deviceStatus">
        <el-select
          v-model="queryParams.deviceStatus"
          :placeholder="t('EquipmentManagement.CapacityReport.placeholderDeviceStatus')"
          clearable
          class="!w-240px"
        >
          <el-option :label="t('EquipmentManagement.EquipmentLedger.normal')" :value="0" />
          <el-option :label="t('EquipmentManagement.EquipmentLedger.stop')" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.CapacityReport.workshop')" prop="workshop">
        <el-input
          v-model="queryParams.workshop"
          :placeholder="t('EquipmentManagement.CapacityReport.placeholderWorkshop')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> {{ t('common.query') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> {{ t('common.reset') }}
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> {{ t('EquipmentManagement.EquipmentLedger.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :row-key="(row) => row.id"
      @select-all="handleSelectAll"
      @select="handleSelect"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="t('EquipmentManagement.CapacityReport.deviceCode')" align="center" prop="deviceCode" sortable />
      <el-table-column :label="t('EquipmentManagement.CapacityReport.deviceName')" align="center" prop="deviceName" sortable />
      <el-table-column :label="t('EquipmentManagement.CapacityReport.deviceType')" align="center" prop="typeName" sortable />
      <el-table-column :label="t('EquipmentManagement.CapacityReport.deviceStatus')" align="center" prop="deviceStatus" sortable>
        <template #default="scope">
          <el-switch
            :model-value="isDeviceLedgerEnabled(scope.row)"
            :loading="Boolean(deviceStatusUpdatingMap[scope.row.id])"
            inline-prompt
            @change="(val) => handleDeviceStatusChange(scope.row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column :label="t('EquipmentManagement.CapacityReport.ratedCapacity')" align="center" prop="ratedCapacity" sortable />
      <el-table-column :label="t('EquipmentManagement.CapacityReport.reportCapacity')" align="center" prop="reportCapacity" sortable />
      <el-table-column :label="t('EquipmentManagement.CapacityReport.actualCapacity')" align="center" prop="actualCapacity" sortable />
      <el-table-column :label="t('EquipmentManagement.CapacityReport.workshop')" align="center" prop="workshopName" sortable />
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import download from '@/utils/download'
import { DeviceLedgerApi, CapacityReportVO } from '@/api/mes/device-ledger'

defineOptions({ name: 'CapacityReport' })

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

const loading = ref(true)
const list = ref<CapacityReportVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceCode: undefined,
  deviceName: undefined,
  deviceType: undefined,
  deviceStatus: undefined,
  workshop: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)
const selectedIds = ref<number[]>([])
const deviceStatusUpdatingMap = ref<Record<number, boolean>>({})

const isDeviceLedgerEnabled = (row: CapacityReportVO) => {
  return Number(row.deviceStatus) === 0
}

const handleDeviceStatusChange = async (row: CapacityReportVO, value: boolean) => {
  if (!row?.id) return
  const oldValue = Number(row.deviceStatus)
  const nextValue = value ? 0 : 1
  row.deviceStatus = nextValue
  deviceStatusUpdatingMap.value[row.id] = true
  try {
    await DeviceLedgerApi.updateDeviceLedger({
      id: row.id,
      deviceStatus: nextValue
    })
    message.success(t('common.updateSuccess'))
  } catch {
    row.deviceStatus = oldValue
    message.error(t('common.updateFail'))
  } finally {
    deviceStatusUpdatingMap.value[row.id] = false
  }
}

const getList = async () => {
  loading.value = true
  try {
    const data = await DeviceLedgerApi.getCapacityReportPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  selectedIds.value = []
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  selectedIds.value = []
  handleQuery()
}

const handleSelectAll = (val: boolean) => {
  if (val) {
    selectedIds.value = list.value.map(item => item.id)
  } else {
    selectedIds.value = []
  }
}

const handleSelect = (val: boolean, row: CapacityReportVO) => {
  if (val) {
    selectedIds.value.push(row.id)
  } else {
    const index = selectedIds.value.indexOf(row.id)
    if (index > -1) {
      selectedIds.value.splice(index, 1)
    }
  }
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params: { ids?: string } = {}
    if (selectedIds.value.length > 0) {
      params.ids = selectedIds.value.join(',')
    }
    const data = await DeviceLedgerApi.exportCapacityReport(params)
    download.excel(data, t('EquipmentManagement.CapacityReport.exportFilename'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

onMounted(() => {
  getList()
})
</script>
