<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="720px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('MoldManagement.MoldInspectionPlan.planName')" prop="planName" required>
        <el-input
          v-model="formData.planName"
          :placeholder="t('MoldManagement.MoldInspectionPlan.placeholderPlanName')"
        />
      </el-form-item>

      <el-form-item :label="t('MoldManagement.MoldInspectionPlan.planType')" prop="planType" required>
        <el-select
          v-model="formData.planType"
          :placeholder="t('MoldManagement.MoldInspectionPlan.placeholderPlanType')"
          class="!w-full"
        >
          <el-option :value="1" :label="t('MoldManagement.MoldInspectionPlan.planTypeMaintain')" />
          <el-option :value="2" :label="t('MoldManagement.MoldInspectionPlan.planTypeInspect')" />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('MoldManagement.MoldInspectionPlan.description')" prop="description">
        <el-input
          v-model="formData.description"
          :placeholder="t('MoldManagement.MoldInspectionPlan.placeholderDescription')"
          type="textarea"
        />
      </el-form-item>

      <el-form-item :label="t('MoldManagement.MoldInspectionPlan.subjectName')" prop="subjectIds">
<!--        <el-select
          v-model="formData.subjectIds"
          multiple
          filterable
          clearable
          :placeholder="t('MoldManagement.MoldInspectionPlan.placeholderSubjectSelect')"
          class="!w-full"
        >
          <el-option v-for="item in subjectOptions" :key="item.id" :label="item.subjectName" :value="item.id" />
        </el-select>-->
        <el-input :model-value="displayItemDevice" readonly clearable class="device-ledger-selection-input"
                  :placeholder="t('MoldManagement.MoldInspectionPlan.placeholderSubjectSelect')"
                  @click="openCriticalComponentDialog"   />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" @click="submitForm" :disabled="formLoading">{{ t('common.ok') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
  <TableSelectDialog
    ref="deviceSelectDialogRef"
    title="选择设备"
    :columns="deviceColumns"
    :fetch-api="fetchDeviceLedgerPage"
    row-key="id"
    @confirm="handleDeviceSelectConfirm"
    :query-params="mergedQueryParams"
    :default-selected-keys="ids"
  >
    <!-- 使用 header 插槽插入查询表单 -->
    <template #header>
      <el-form ref="searchFormRef" :model="searchParams" :inline="true" >
        <el-form-item label="设备编号" prop="deviceCode">
          <el-input v-model="searchParams.deviceCode" placeholder="请输入编号" clearable />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="searchParams.deviceName" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">{{ t('FactoryModeling.ProductInformation.searchButtonText') }}</el-button>
          <el-button @click="resetSearch">{{ t('FactoryModeling.ProductInformation.resetButtonText') }}</el-button>
        </el-form-item>
      </el-form>
    </template>
  </TableSelectDialog>
</template>

<script setup lang="ts">
import type { FormRules } from 'element-plus'
import { DvSubjectApi, DvSubjectVO } from '@/api/mold/inspectionItems'
import { PlanMaintenanceApi, PlanMaintenanceVO } from '@/api/mold/planmaintenance'
import {DeviceLedgerApi, DeviceLedgerVO} from "@/api/mes/deviceledger";
import TableSelectDialog from '@/components/TableSelectDialog/TableSelectDialog.vue'
defineOptions({ name: 'MoldInspectionPlanForm' })

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

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')

const subjectOptions = ref<DvSubjectVO[]>([])
const ensureSubjectOptionsLoaded = async () => {
  if (subjectOptions.value.length) return
  const res = await DvSubjectApi.getMoldSubjectAllList()
  const list = Array.isArray(res) ? res : res?.list
  itemList.value = (list ?? []) as DvSubjectVO[]
  subjectOptions.value = (list ?? []) as DvSubjectVO[]
}

const parseIds = (value: any): Array<number | string> => {
  if (!value) return []
  const raw = Array.isArray(value)
    ? value
    : String(value)
        .split(',')
        .map((v) => v.trim())
        .filter((v) => v !== '')

  return raw
    .map((v) => {
      if (typeof v === 'number') return v
      const s = String(v).trim()
      if (!s) return undefined
      const n = Number(s)
      if (Number.isFinite(n) && String(n) === s) return n
      return s
    })
    .filter((v): v is number | string => v !== undefined)
}
const ids = ref([])
const itemList = ref<DvSubjectVO[]>([])
const selectedDeviceRows = ref<any[]>([])
const deviceSelectDialogRef = ref(false)
const mergedQueryParams = computed(() => ({ ...searchParams }))
const deviceColumns = [
  { label: '项目编码', prop: 'subjectCode', minWidth: 140 },
  { label: '项目名称', prop: 'subjectName', minWidth: 160 },
  { label: '项目类型', prop: 'subjectType', minWidth: 140 },
  { label: '项目内容', prop: 'subjectContent', minWidth: 140 }
]

const fetchDeviceLedgerPage = async (params: Record<string, any>) => {
  const res = await DvSubjectApi.getDvSubjectPage({
    ...params,
  })

  const list = res.list || []

  // 合并已选数据（防止分页丢失）
  const selectedMap = new Map(
    selectedDeviceRows.value.map((item) => [item.id, item])
  )

  return {
    ...res,
    list: list.map((item) => ({
      ...item,
      ...selectedMap.get(item.id)
    }))
  }
}
// 1. 自定义表单的查询参数
const searchParams = reactive({
  subjectCode: undefined,
  subjectName: undefined,
})
const displayItemDevice = computed( () => {
  if (!ids.value.length)return ''
  if (!itemList.value.length) {
    return formData.value.subjectIds ? String(formData.value.subjectIds) : ''
  }
  const map = new Map(itemList.value.map((item) => [item.id, item.subjectName]))
  const names = ids.value
    .map((id) => map.get(id))
    .filter((name) => name)
  return names.join(',')
})

const openCriticalComponentDialog = async () => {
  searchParams.subjectCode=''
  searchParams.subjectName=''
  const rows = selectedDeviceRows.value.length


  //deviceSelectDialogRef.value?.open(rows)
  let initIds= formData.value.subjectIds!=undefined?formData.value.subjectIds.toString().split(","):[]
  deviceSelectDialogRef.value?.open([], {
    defaultSelectedKeys: initIds
  })
  ids.value=initIds.map((id) => Number(id))
}

const handleDeviceSelectConfirm = (payload: { ids: (number | string)[]; rows: any[] }) => {
  formData.value.subjectIds = payload.rows
    .map((item) => {
      const id = Number(item.id)
      if (!Number.isFinite(id)) return undefined
      return {
        id,
        name: item.subjectName || item.name || item.code || `设备ID:${id}`
      }
    })
    .filter((item): item is { id: number; name: string } => Boolean(item))
  selectedDeviceRows.value = payload.rows
  formData.value.subjectIds = payload.ids.join(',')
  ids.value = payload.ids.map((id) => Number(id))
}

const handleSearch = () => {
  // 触发弹窗内部重新加载数据
  deviceSelectDialogRef.value?.reload?.()
}
const searchFormRef = ref()
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
const initFormData = () => ({
  id: undefined as PlanMaintenanceVO['id'],
  planName: '' as string,
  planType: undefined as any,
  description: '' as string,
  subjectIds: [] as Array<number | string>
})

const formData = ref(initFormData())
const formRules = reactive<FormRules>({
  planName: [
    {
      required: true,
      message: t('MoldManagement.MoldInspectionPlan.validatorPlanNameRequired'),
      trigger: 'blur'
    }
  ],
  planType: [
    {
      required: true,
      message: t('MoldManagement.MoldInspectionPlan.validatorPlanTypeRequired'),
      trigger: 'change'
    }
  ],
  subjectIds: [
    {
      required: true,
      message: t('MoldManagement.MoldInspectionPlan.validatorSubjectIdsRequired'),
      trigger: 'change'
    }
  ]
})
const formRef = ref()

const open = async (type: 'create' | 'update', row?: Partial<PlanMaintenanceVO>) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await ensureSubjectOptionsLoaded()

  if (type === 'update' && row) {
    formData.value = {
      ...initFormData(),
      id: row.id,
      planName: (row.planName as any) ?? '',
      planType: (row.planType as any) ?? undefined,
      description: (row.description as any) ?? '',
      subjectIds: parseIds((row as any).subjectIds ?? (row as any).subjectIdS)
    }
    ids.value=parseIds((row as any).subjectIds ?? (row as any).subjectIdS)
  }else{
    ids.value=[]
  }
}

defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = {
      id: formData.value.id,
      planName: formData.value.planName,
      planType: formData.value.planType,
      description: formData.value.description,
      subjectIdS: formData.value.subjectIds ? String(formData.value.subjectIds) : undefined
    }
    if (formType.value === 'create') {
      await PlanMaintenanceApi.createPlanMaintenance(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlanMaintenanceApi.updatePlanMaintenance(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = initFormData()
  formRef.value?.resetFields()
}
</script>
