<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="60px">
      <el-form-item label="名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="类型" prop="planType">
        <el-select v-model="queryParams.planType" placeholder="请选择类型" clearable class="!w-240px">
          <el-option :value="1" label="保养" />
          <el-option :value="2" label="点检" />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入描述"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['mes:plan-maintenance:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="danger" plain @click="handleBatchDelete" v-hasPermi="['mes:plan-maintenance:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['mes:plan-maintenance:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>

    <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="序号" align="center" width="80">
                <template #default="s2">
                  {{ s2.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="编码" align="center" prop="subjectCode" />
              <el-table-column label="名称" align="center" prop="subjectName" />
              <el-table-column label="检验方式" 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="判定基准" align="center" prop="judgmentCriteria" />
            </el-table>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="序号" align="center" width="80">
        <template #default="scope">
          {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="planName" min-width="160" />
      <el-table-column label="类型" 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="描述" align="center" prop="description" min-width="220" />
      <el-table-column label="创建人" align="center" prop="creatorName" width="140" />
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180" />
      <el-table-column label="更新时间" align="center" prop="updateTime" :formatter="dateFormatter" width="180" />
      <el-table-column label="操作" 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']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mes:plan-maintenance: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 '保养'
  if (v === 2) return '点检'
  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('请选择需要删除的数据')
    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, '方案维护.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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