<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="920px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="16">
        <!-- <el-col :span="24">
          <el-form-item label="资产编号" prop="id">
            <el-input v-model="formData.id" placeholder="系统自动生成" disabled />
          </el-form-item>
        </el-col> -->

        <el-col :span="12">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.deviceCode')" prop="deviceCode" required>
            <el-input :disabled = "formType == 'update'" v-model="formData.deviceCode" :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceCode')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.deviceName')" prop="deviceName" required>
            <el-input v-model="formData.deviceName" :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceName')" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.deviceType')" prop="deviceType" required>
            <el-tree-select
              v-model="formData.deviceType"
              :data="deviceTypeTree"
              :props="treeSelectProps"
              check-strictly
              default-expand-all
              value-key="id"
              :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceType')"
              class="!w-full"
            />
          </el-form-item>
        </el-col>

        <!-- <el-col :span="12">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.deviceBrand')" prop="deviceBrand">
            <el-input v-model="formData.deviceBrand" placeholder="请输入品牌" />
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.deviceModel')" prop="deviceModel">
            <el-input v-model="formData.deviceModel" :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceModel')" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.deviceSpec')" prop="deviceSpec">
            <el-input v-model="formData.deviceSpec" :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceSpec')" />
          </el-form-item>
        </el-col>

        <!-- <el-col :span="12">
          <el-form-item label="供应商" prop="supplier">
            <el-input v-model="formData.supplier" placeholder="请输入供应商" /> -->
            <!--
            <el-select v-model="formData.supplier" placeholder="请选择供应商" clearable filterable class="!w-full">
              <el-option v-for="item in supplierOptions" :key="item" :label="item" :value="item" />
            </el-select>
            -->
          <!-- </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属车间" prop="workshop">
            <el-input v-model="formData.workshop" placeholder="请输入所属车间" /> -->
            <!--
            <el-tree-select
              v-model="formData.workshop"
              :data="deptTree"
              :props="treeSelectProps"
              check-strictly
              default-expand-all
              value-key="id"
              placeholder="请选择所属车间"
              class="!w-full"
            />
            -->
          <!-- </el-form-item>
        </el-col> -->

        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.productionDate')" prop="productionDate" required>
            <el-date-picker v-model="formData.productionDate" type="date" value-format="YYYY-MM-DD" :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderProductionDate')" class="!w-full" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.factoryEntryDate')" prop="factoryEntryDate" required>
            <el-date-picker v-model="formData.factoryEntryDate" type="date" value-format="YYYY-MM-DD" :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderFactoryEntryDate')" class="!w-full" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.deviceLocation')" prop="deviceLocation">
            <el-input v-model="formData.deviceLocation" :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceLocation')" />
          </el-form-item>
        </el-col>

        <!-- <el-col :span="24">
          <el-form-item label="所属系统组织" prop="systemOrg">
            <el-input v-model="formData.systemOrg" placeholder="请输入所属系统组织" /> -->
            <!--
            <el-tree-select
              v-model="formData.systemOrg"
              :data="deptTree"
              :props="treeSelectProps"
              check-strictly
              default-expand-all
              value-key="id"
              placeholder="请选择部门"
              class="!w-full"
            />
            -->
          <!-- </el-form-item>
        </el-col> -->

        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.deviceManagerName')" prop="deviceManagerIds">
            <el-select
              v-model="formData.deviceManagerIds"
              multiple
              filterable
              clearable
              :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderDeviceManagerIds')"
              class="!w-full"
            >
              <el-option v-for="item in users" :key="item.id" :label="item.nickname" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.dvName')" prop="dvId">
        <el-select v-model="formData.dvId" filterable :placeholder="t('EquipmentManagement.EquipmentLedger.dvId')">
          <el-option
            v-for="item in deviceList"
            :key="item.id"
            :label="item.deviceName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.criticalComponent')" prop="componentIds">
            <el-cascader
              v-model="criticalComponentCascaderValue"
              :options="criticalComponentPagedOptions"
              :props="cascaderProps"
              filterable
              clearable
              collapse-tags
              :show-all-levels="false"
              :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderComponentIds')"
              class="!w-full"
              @change="handleCriticalComponentChange"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.sparePart')" prop="beijianIds">
            <el-cascader
              v-model="beijianCascaderValue"
              :options="beijianPagedOptions"
              :props="cascaderProps"
              filterable
              clearable
              collapse-tags
              :show-all-levels="false"
              :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderBeijianIds')"
              class="!w-full"
              @change="handleBeijianChange"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.fileUrl')" prop="fileUrl">
            <UploadFile :is-show-tip="false" v-model="formData.fileUrl" :limit="1" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('EquipmentManagement.EquipmentLedger.remark')" prop="remark">
            <el-input v-model="formData.remark" :placeholder="t('EquipmentManagement.EquipmentLedger.placeholderRemark')" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('common.ok') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>

</template>
<script setup lang="ts">
import { DeviceLedgerApi, DeviceLedgerVO } from '@/api/mes/deviceledger'
import { CriticalComponentApi } from '@/api/mes/criticalComponent'
import { DeviceTypeApi, DeviceTypeTreeVO } from '@/api/mes/devicetype'
import { getSimpleUserList, UserVO } from '@/api/system/user'
import { formatDate } from '@/utils/formatTime'
import type { FormRules } from 'element-plus'
import { ProductApi } from '@/api/erp/product/product'
import { DeviceApi,DeviceVO } from '@/api/iot/device'

/** 设备类型 表单 */
defineOptions({ name: 'DeviceLedgerForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const deviceList = ref<DeviceVO[]>([]) // 列表

const parseIdsValue = (value: any): number[] => {
  if (!value) return []
  if (Array.isArray(value)) return value.map((v) => Number(v)).filter((v) => !Number.isNaN(v))
  return String(value)
    .split(',')
    .map((v) => Number(v.trim()))
    .filter((v) => !Number.isNaN(v))
}

const normalizeYmd = (value: any): string | undefined => {
  if (value === null || value === undefined || value === '') return undefined
  if (typeof value === 'string') {
    const trimmed = value.trim()
    const matched = trimmed.match(/^(\d{4}-\d{2}-\d{2})/)
    if (matched?.[1]) return matched[1]
    const parsed = Date.parse(trimmed)
    if (!Number.isNaN(parsed)) return formatDate(new Date(parsed), 'YYYY-MM-DD')
    return trimmed
  }
  if (typeof value === 'number') return formatDate(new Date(value), 'YYYY-MM-DD')
  if (value instanceof Date) return formatDate(value, 'YYYY-MM-DD')
  return formatDate(new Date(value), 'YYYY-MM-DD')
}

const initFormData = () => ({
  id: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  deviceStatus: undefined,
  deviceBrand: undefined,
  deviceModel: undefined,
  deviceSpec: undefined,
  deviceType: undefined,
  supplier: undefined,
  workshop: undefined,
  deviceLocation: undefined,
  systemOrg: undefined,
  deviceManagerIds: [] as number[],
  productionDate: undefined,
  factoryEntryDate: undefined,
  remark: undefined,
  componentIds: [] as number[],
  beijianIds: [] as number[],
  fileUrl: undefined,
  sort: undefined,
  dvId: undefined
})

const formData = ref({
  ...initFormData()
})
const formRules = reactive<FormRules>({
  deviceCode: [{ required: true, message: t('EquipmentManagement.EquipmentLedger.placeholderDeviceCode'), trigger: 'blur' }],
  deviceName: [{ required: true, message: t('EquipmentManagement.EquipmentLedger.placeholderDeviceName'), trigger: 'blur' }],
  deviceType: [{ required: true, message: t('EquipmentManagement.EquipmentLedger.placeholderDeviceType'), trigger: 'change' }],
  productionDate: [{ required: true, message: t('EquipmentManagement.EquipmentLedger.placeholderProductionDate'), trigger: 'change' }],
  factoryEntryDate: [{ required: true, message: t('EquipmentManagement.EquipmentLedger.placeholderFactoryEntryDate'), trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

const treeSelectProps = { label: 'name', children: 'children' }
const deviceTypeTree = ref<DeviceTypeTreeVO[]>([])
const users = ref<UserVO[]>([])
const criticalComponentOptions = ref<{ label: string; value: number }[]>([])
const beijianOptions = ref<{ label: string; value: number }[]>([])
const PAGE_SIZE = 10

const buildPagedOptions = (options: { label: string; value: number }[]) => {
  const result: { label: string; value: string; children: { label: string; value: number }[] }[] = []
  for (let i = 0; i < options.length; i += PAGE_SIZE) {
    const pageIndex = result.length + 1
    result.push({
      label: String(pageIndex),
      value: `page-${pageIndex}`,
      children: options.slice(i, i + PAGE_SIZE).map((item) => ({
        label: item.label,
        value: item.value
      }))
    })
  }
  return result
}

const cascaderProps = { multiple: true, emitPath: false, checkStrictly: false }

const criticalComponentCascaderValue = ref<(number | string)[]>([])
const beijianCascaderValue = ref<(number | string)[]>([])

const criticalComponentPagedOptions = computed(() => buildPagedOptions(criticalComponentOptions.value))
const beijianPagedOptions = computed(() => buildPagedOptions(beijianOptions.value))

const ensureOptionsLoaded = async () => {
  const [deviceTypeRes, userRes, criticalRes, beijianRes] = await Promise.all([
    DeviceTypeApi.getDeviceTypeTree({ pageNo: 1, pageSize: 10 }),
    getSimpleUserList(),
    CriticalComponentApi.getCriticalComponentList(),
    ProductApi.getComponentSimpleList()
  ])
  deviceTypeTree.value = deviceTypeRes
  users.value = userRes ?? []
  criticalComponentOptions.value = (criticalRes ?? []).map((item: any) => {
    const code = item.code ? String(item.code) : ''
    const name = item.name ? String(item.name) : ''
    const label = code && name ? `${code}-${name}` : name || code || String(item.id)
    return { label, value: Number(item.id) }
  })
  beijianOptions.value = (beijianRes ?? []).map((item: any) => {
    const code = item.barCode ? String(item.barCode) : ''
    const name = item.name ? String(item.name) : ''
    const label = code && name ? `${code}-${name}` : name || code || String(item.id)
    return { label, value: Number(item.id) }
  })
}

watch(
  () => formData.value.componentIds,
  (ids) => {
    criticalComponentCascaderValue.value = Array.isArray(ids) ? [...ids] : []
  },
  { immediate: true }
)

watch(
  () => formData.value.beijianIds,
  (ids) => {
    beijianCascaderValue.value = Array.isArray(ids) ? [...ids] : []
  },
  { immediate: true }
)

const handleCriticalComponentChange = (values: (number | string)[]) => {
  const validIds = new Set<number>()
  const validMap = new Set(criticalComponentOptions.value.map((item) => item.value))
  for (const v of values) {
    const num = Number(v)
    if (!Number.isNaN(num) && validMap.has(num)) {
      validIds.add(num)
    }
  }
  formData.value.componentIds = Array.from(validIds)
  criticalComponentCascaderValue.value = Array.from(validIds)
}

const handleBeijianChange = (values: (number | string)[]) => {
  const validIds = new Set<number>()
  const validMap = new Set(beijianOptions.value.map((item) => item.value))
  for (const v of values) {
    const num = Number(v)
    if (!Number.isNaN(num) && validMap.has(num)) {
      validIds.add(num)
    }
  }
  formData.value.beijianIds = Array.from(validIds)
  beijianCascaderValue.value = Array.from(validIds)
}

/** 打开弹窗 */
const open = async (type: string, id?: number, defaultDeviceTypeId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await ensureOptionsLoaded()
  if (type === 'create' && defaultDeviceTypeId) {
    formData.value.deviceType = defaultDeviceTypeId
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const detail = await DeviceLedgerApi.getDeviceLedger(id)
      formData.value = {
        ...initFormData(),
        ...(detail as any),
        deviceManagerIds: parseIdsValue((detail as any)?.deviceManager),
        productionDate: normalizeYmd((detail as any)?.productionDate),
        factoryEntryDate: normalizeYmd((detail as any)?.factoryEntryDate),
        componentIds: parseIdsValue((detail as any)?.componentId),
        beijianIds: parseIdsValue((detail as any)?.beijianId),
      }
    } finally {
      formLoading.value = false
    }
  }
  if (type == 'create' || typeof formData.value.dvId != 'number') {
    deviceList.value = await DeviceApi.getDeviceListByNoUsed()
  } else {
    deviceList.value = await DeviceApi.getDeviceList2ByNoUsed(formData.value.dvId)
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...(formData.value as any),
      productionDate: normalizeYmd(formData.value.productionDate),
      factoryEntryDate: normalizeYmd(formData.value.factoryEntryDate),
      deviceManager: formData.value.deviceManagerIds?.length ? formData.value.deviceManagerIds.join(',') : undefined,
      componentId: formData.value.componentIds?.length ? formData.value.componentIds.join(',') : undefined,
      beijianId: formData.value.beijianIds?.length ? formData.value.beijianIds.join(',') : undefined
    } as unknown as DeviceLedgerVO
    delete (data as any).deviceManagerIds
    delete (data as any).componentIds
    delete (data as any).beijianIds
    if (formType.value === 'create') {
      await DeviceLedgerApi.createDeviceLedger(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceLedgerApi.updateDeviceLedger(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = initFormData()
  formRef.value?.resetFields()
}
</script>

<style scoped>
.device-ledger-manager {
  display: flex;
  width: 100%;
  gap: 12px;
}

.device-ledger-manager :deep(.el-input) {
  flex: 1;
}
</style>
