<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item :label="t('EquipmentManagement.PlanMaintenance.planName')" prop="planName">
        <el-input
          v-model="queryParams.planName"
          :placeholder="t('EquipmentManagement.PlanMaintenance.placeholderPlanName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.PlanMaintenance.planType')" prop="planType">
        <el-select
          v-model="queryParams.planType"
          :placeholder="t('EquipmentManagement.PlanMaintenance.placeholderPlanType')"
          clearable
          class="!w-240px"
        >
          <el-option :value="1" :label="t('EquipmentManagement.PlanMaintenance.planTypeMaintain')" />
          <el-option :value="2" :label="t('EquipmentManagement.PlanMaintenance.planTypeInspect')" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.PlanMaintenance.description')" prop="description">
        <el-input
          v-model="queryParams.description"
          :placeholder="t('EquipmentManagement.PlanMaintenance.placeholderDescription')"
          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="primary" plain @click="openForm('create')" v-hasPermi="['mes:plan-maintenance:create']">
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.add') }}
        </el-button>
        <el-button type="danger" plain @click="handleBatchDelete" v-hasPermi="['mes:plan-maintenance:delete']">
          <Icon icon="ep:delete" class="mr-5px" />
          {{ t('EquipmentManagement.PlanMaintenance.batchDelete') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['mes:plan-maintenance:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('action.export') }}
        </el-button>
      </el-form-item>
    </el-form>
</ContentWrap>
  <ContentWrap>
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="list"
      row-key="id"
      :stripe="true"
      :show-overflow-tooltip="true"
      @expand-change="handleExpandChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" fixed="left" reserve-selection />
      <el-table-column type="expand" width="48">
        <template #default="scope">
          <div class="p-12px">
            <el-table
              v-loading="subjectLoadingMap[String(scope.row.id)]"
              :data="subjectListMap[String(scope.row.id)] ?? []"
              :stripe="true"
              :show-overflow-tooltip="true"
              size="small"
            >
              <el-table-column :label="t('EquipmentManagement.PlanMaintenance.index')" align="center" width="80">
                <template #default="s2">
                  {{ s2.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column :label="t('EquipmentManagement.PlanMaintenance.subjectCode')" align="center" prop="subjectCode" />
              <el-table-column :label="t('EquipmentManagement.PlanMaintenance.subjectName')" align="center" prop="subjectName" />
              <el-table-column :label="t('EquipmentManagement.PlanMaintenance.inspectionMethod')" align="center" prop="inspectionMethod" width="120">
                <template #default="s2">
                  <span v-if="s2.row.inspectionMethod === undefined || s2.row.inspectionMethod === null || s2.row.inspectionMethod === ''">-</span>
                  <el-tag
                    v-else
                    effect="light"
                    :type="getTagType('Inspection_method', s2.row.inspectionMethod)"
                    :color="getTagColor('Inspection_method', s2.row.inspectionMethod)"
                    :style="getTagStyle('Inspection_method', s2.row.inspectionMethod)"
                    disable-transitions
                  >
                    {{ getTagLabel('Inspection_method', s2.row.inspectionMethod) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column :label="t('EquipmentManagement.PlanMaintenance.judgmentCriteria')" align="center" prop="judgmentCriteria" />
            </el-table>
          </div>
        </template>
      </el-table-column>

      <el-table-column :label="t('EquipmentManagement.PlanMaintenance.index')" align="center" width="80">
        <template #default="scope">
          {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="t('EquipmentManagement.PlanMaintenance.planName')" align="center" prop="planName" min-width="160" />
      <el-table-column :label="t('EquipmentManagement.PlanMaintenance.planType')" align="center" prop="planType" width="110">
        <template #default="scope">
          <el-tag effect="light" :type="getPlanTypeTagType(scope.row.planType)">
            {{ getPlanTypeLabel(scope.row.planType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('EquipmentManagement.PlanMaintenance.description')" align="center" prop="description" min-width="220" />
      <el-table-column :label="t('EquipmentManagement.PlanMaintenance.creatorName')" align="center" prop="creatorName" width="140" />
      <el-table-column :label="t('EquipmentManagement.PlanMaintenance.createTime')" align="center" prop="createTime" :formatter="dateFormatter" width="180" />
      <!-- <el-table-column :label="t('EquipmentManagement.PlanMaintenance.updateTime')" align="center" prop="updateTime" :formatter="dateFormatter" width="180" /> -->
      <el-table-column :label="t('EquipmentManagement.PlanMaintenance.operate')" align="center" fixed="right" width="160">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row)" v-hasPermi="['mes:plan-maintenance:update']">
            {{ t('action.update') }}
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mes:plan-maintenance:delete']">
            {{ t('action.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <PlanMaintenanceForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { PlanMaintenanceApi, PlanMaintenanceSubjectVO, PlanMaintenanceVO } from '@/api/mes/planmaintenance'
import PlanMaintenanceForm from './PlanMaintenanceForm.vue'
import { isHexColor } from '@/utils/color'
import { useDictStoreWithOut } from '@/store/modules/dict'

defineOptions({ name: 'PlanMaintenance' })

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

const dictStore = useDictStoreWithOut()
const dictReady = ref(false)

const loading = ref(false)
const list = ref<PlanMaintenanceVO[]>([])
const total = ref(0)
const exportLoading = ref(false)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  planName: undefined as string | undefined,
  planType: undefined as number | undefined,
  description: undefined as string | undefined
})

const queryFormRef = ref()

const tableRef = ref()
const selectedIds = ref<(number | string)[]>([])
const handleSelectionChange = (rows: any[]) => {
  selectedIds.value = rows?.map((row) => row.id).filter((id) => id !== undefined && id !== null && id !== '') ?? []
}

const subjectListMap = ref<Record<string, PlanMaintenanceSubjectVO[]>>({})
const subjectLoadingMap = ref<Record<string, boolean>>({})

const getTagDict = (dictType: string, value: any) => {
  if (!dictReady.value) return undefined
  const v = value === '' || value === null || value === undefined ? undefined : String(value)
  if (!v) return undefined
  return getStrDictOptions(dictType).find((d) => d.value === v)
}

const getTagLabel = (dictType: string, value: any) => {
  const found = getTagDict(dictType, value)
  return found?.label ?? (value ?? '')
}

const getTagType = (dictType: string, value: any) => {
  const found = getTagDict(dictType, value)
  const type = found?.colorType
  if (type + '' === 'primary' || type + '' === 'default') return '' as any
  return (type ?? '') as any
}

const getTagColor = (dictType: string, value: any) => {
  const found = getTagDict(dictType, value)
  if (found?.cssClass && isHexColor(found.cssClass)) return found.cssClass
  return ''
}

const getTagStyle = (dictType: string, value: any) => {
  const color = getTagColor(dictType, value)
  if (!color) return ''
  return 'color: #fff'
}

const normalizeList = (res: any): { list: any[]; total: number } => {
  if (Array.isArray(res)) return { list: res, total: res.length }
  return { list: res?.list ?? [], total: res?.total ?? 0 }
}

const getList = async () => {
  loading.value = true
  try {
    const res = await PlanMaintenanceApi.getPlanMaintenancePage({
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      planName: queryParams.planName,
      planType: queryParams.planType,
      description: queryParams.description
    })
    const normalized = normalizeList(res)
    list.value = normalized.list as PlanMaintenanceVO[]
    total.value = normalized.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

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

const ensureSubjectListLoaded = async (id: number | string) => {
  const key = String(id)
  if (!key) return
  if (subjectListMap.value[key]) return
  subjectLoadingMap.value[key] = true
  try {
    const res = await PlanMaintenanceApi.getSubjectList(id)
    const data = Array.isArray(res) ? res : res?.list ?? res ?? []
    subjectListMap.value[key] = (data ?? []) as PlanMaintenanceSubjectVO[]
  } finally {
    subjectLoadingMap.value[key] = false
  }
}

const handleExpandChange = async (row: PlanMaintenanceVO, expandedRows: PlanMaintenanceVO[]) => {
  const isExpanded = expandedRows.some((r) => String(r.id) === String(row.id))
  if (!isExpanded) return
  if (row?.id === undefined || row?.id === null || row?.id === '') return
  await ensureSubjectListLoaded(row.id)
}

const getPlanTypeLabel = (value: any) => {
  const v = value === '' || value === null || value === undefined ? undefined : Number(value)
  if (v === 1) return t('EquipmentManagement.PlanMaintenance.planTypeMaintain')
  if (v === 2) return t('EquipmentManagement.PlanMaintenance.planTypeInspect')
  return value ?? ''
}

const getPlanTypeTagType = (value: any) => {
  const v = value === '' || value === null || value === undefined ? undefined : Number(value)
  if (v === 1) return 'success'
  if (v === 2) return 'primary'
  return ''
}

const formRef = ref()
const openForm = (type: 'create' | 'update', row?: PlanMaintenanceVO) => {
  formRef.value?.open(type, row)
}

const buildIdsParam = (ids: number | string | Array<number | string>) => {
  return Array.isArray(ids) ? ids.join(',') : String(ids)
}

const handleDelete = async (ids: number | string | Array<number | string>) => {
  try {
    await message.delConfirm()
    await PlanMaintenanceApi.deletePlanMaintenance(buildIdsParam(ids))
    message.success(t('common.delSuccess'))
    selectedIds.value = []
    tableRef.value?.clearSelection?.()
    await getList()
  } catch {}
}

const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    message.error(t('EquipmentManagement.PlanMaintenance.selectDeleteTip'))
    return
  }
  await handleDelete(selectedIds.value)
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params: any = {
      ...queryParams,
      ids: selectedIds.value.length ? selectedIds.value.join(',') : undefined
    }
    const data = await PlanMaintenanceApi.exportPlanMaintenance(params)
    download.excel(data, t('EquipmentManagement.PlanMaintenance.exportFilename'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

onMounted(async () => {
  await dictStore.setDictMap()
  dictReady.value = true
  getList()
})
</script>
