<template>
  <Dialog
    v-model="dialogVisible"
    title="选择物料"
    style="width: 1400px; min-height: 300px; padding: 0"
  >
    <div
      ref="measureSpan"
      style="
        position: absolute;
        top: -9999px;
        left: -9999px;
        padding: 0 12px;
        font:
          13px Arial,
          'PingFang SC',
          'Microsoft YaHei',
          sans-serif;
        white-space: nowrap;
        visibility: hidden;
      "
    >
    </div>

    <!-- 设备分类和BOM节点信息显示 -->
    <div style="padding: 5px 15px; margin: 0; background: #f5f7fa; border-radius: 4px">
      <el-row>
        <el-col :span="8">
          <span style="margin-right: 8px; font-size: 13px; font-weight: bold">设备编码：</span>
          <span style="font-size: 13px">{{ deviceCode }}</span>
        </el-col>
        <el-col :span="8">
          <span style="margin-right: 8px; font-size: 13px; font-weight: bold">设备名称：</span>
          <span style="font-size: 13px">{{ deviceName }}</span>
        </el-col>
        <el-col :span="8">
          <span style="margin-right: 8px; font-size: 13px; font-weight: bold"
            >{{ bomNodeLabel }}：</span
          >
          <span style="font-size: 13px">{{ bomNodeName }}</span>
        </el-col>
      </el-row>
    </div>

    <!-- 可折叠的区域 展示当前保养项 已经绑定的物料-->
    <div v-if="showFoldArea" style="margin-bottom: 2px">
      <el-button
        type="text"
        @click="showMaterialArea = !showMaterialArea"
        style="padding-left: 8px; margin-bottom: 2px; font-size: 13px"
      >
        {{ showMaterialArea ? '隐藏保养项物料' : '显示保养项物料' }}
      </el-button>

      <div
        v-show="showMaterialArea"
        style="padding: 5px 8px; background: #f5f7fa; border-radius: 4px"
      >
        <template v-if="deviceBomMaterials.length === 0">
          <div style="padding: 8px; font-size: 13px; color: #999; text-align: center">
            无绑定物料
          </div>
        </template>
        <template v-else>
          <!-- 表头 -->
          <div
            style="
              display: grid;
              padding-bottom: 6px;
              margin-bottom: 8px;
              font-size: 13px;
              font-weight: bold;
              border-bottom: 1px solid #e4e7ed;
              grid-template-columns: 1fr 1fr 1fr 1fr;
              gap: 12px;
            "
          >
            <div>物料编码</div>
            <div>物料名称</div>
            <div>数量</div>
            <div>单位</div>
          </div>
          <!-- 内容区 -->
          <div
            v-for="(item, index) in deviceBomMaterials"
            :key="index"
            style="
              display: grid;
              padding: 6px 0;
              font-size: 13px;
              border-bottom: 1px dashed #ebeef5;
              grid-template-columns: 1fr 1fr 1fr 1fr;
              gap: 8px;
            "
          >
            <div style="word-break: break-all">{{ item.code || '-' }}</div>
            <div style="word-break: break-all">{{ item.name || '-' }}</div>
            <div>{{ item.quantity !== undefined ? item.quantity : '-' }}</div>
            <div style="word-break: break-all">{{ item.unit || '-' }}</div>
          </div>
        </template>
      </div>
    </div>

    <ContentWrap style="padding: 0">
      <el-form
        class="-mb-5px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
        style="font-size: 13px"
      >
        <el-form-item
          :label="t('workOrderMaterial.materialName')"
          prop="materialName"
          style="margin-bottom: 2px"
        >
          <el-input
            v-model="queryParams.materialName"
            :placeholder="t('workOrderMaterial.nameHolder')"
            clearable
            @keyup.enter="handleQuery"
            size="small"
          />
        </el-form-item>
        <el-form-item
          :label="t('workOrderMaterial.materialCode')"
          prop="materialCode"
          style="margin-bottom: 2px"
        >
          <el-input
            v-model="queryParams.materialCode"
            :placeholder="t('workOrderMaterial.codeHolder')"
            clearable
            @keyup.enter="handleQuery"
            size="small"
          />
        </el-form-item>

        <el-form-item style="margin-bottom: 2px">
          <el-button @click="handleQuery" size="small"
            ><Icon icon="ep:search" class="mr-5px" /> {{ t('workOrderMaterial.search') }}</el-button
          >
          <el-button @click="resetQuery" size="small"
            ><Icon icon="ep:refresh" class="mr-5px" /> {{ t('workOrderMaterial.reset') }}</el-button
          >
          <el-button @click="handleConfirm" class="custom-green-button" size="small"
            ><Icon icon="ep:check" class="mr-5px" /> {{ t('workOrderMaterial.confirm') }}</el-button
          >
          <!-- <el-button @click="handleView" type="warning" size="small"
            ><Icon icon="ep:plus" class="mr-5px" />
            {{ t('workOrderMaterial.added') }}</el-button
          > -->
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap style="padding: 0; margin-bottom: 0">
      <el-table
        v-loading="loading"
        :data="list"
        :stripe="true"
        ref="tableRef"
        class="adaptive-table"
        @row-click="handleRowClick"
        :row-class-name="rowClassName"
        size="small"
      >
        <el-table-column width="60" :label="t('workOrderMaterial.select')">
          <template #default="{ row }">
            <el-checkbox
              :model-value="
                selectedRows.some(
                  (item) =>
                    item.factoryId === row.factoryId &&
                    item.costCenterId === row.costCenterId &&
                    item.storageLocationId === row.storageLocationId &&
                    item.materialCode === row.materialCode
                )
              "
              @click.stop="toggleRow(row)"
              class="no-label-radio"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="t('workOrderMaterial.factory')"
          align="center"
          prop="factoryId"
          class="!w-100px"
          v-if="false"
        />
        <el-table-column
          :label="t('workOrderMaterial.factory')"
          align="center"
          prop="factory"
          :width="flexColumnWidth('factory', t('workOrderMaterial.factory'))"
        />
        <el-table-column
          :label="t('workOrderMaterial.costCenter')"
          align="center"
          prop="costCenterId"
          class="!w-100px"
          v-if="false"
        />
        <el-table-column
          :label="t('workOrderMaterial.costCenter')"
          align="center"
          prop="costCenter"
          :width="flexColumnWidth('costCenter', t('workOrderMaterial.costCenter'))"
        />
        <el-table-column
          :label="t('workOrderMaterial.storageLocation')"
          align="center"
          prop="storageLocationId"
          class="!w-100px"
          v-if="false"
        />
        <el-table-column
          :label="t('workOrderMaterial.storageLocation')"
          align="center"
          prop="projectDepartment"
          :width="flexColumnWidth('projectDepartment', t('workOrderMaterial.storageLocation'))"
        />
        <el-table-column
          :label="t('workOrderMaterial.materialCode')"
          align="center"
          prop="materialCode"
          :width="flexColumnWidth('materialCode', t('workOrderMaterial.materialCode'))"
        />
        <el-table-column
          :label="t('workOrderMaterial.materialName')"
          align="center"
          prop="materialName"
          :class-name="'material-name-cell'"
          :width="materialNameWidth"
        />
        <el-table-column
          :label="t('workOrderMaterial.ConsumptionQuantity')"
          align="center"
          prop="quantity"
          :width="flexColumnWidth('quantity', t('workOrderMaterial.ConsumptionQuantity'), 20)"
        >
          <template #default="scope">
            <el-input
              type="number"
              :controls="false"
              v-model="scope.row.quantity"
              @click.stop=""
              @focus="handleInputFocus(scope.row)"
              @blur="(event) => handleQuantityBlur(event, scope.row)"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="t('workOrderMaterial.unit')"
          align="center"
          prop="unit"
          :width="flexColumnWidth('unit', t('workOrderMaterial.unit'))"
        />
        <el-table-column
          :label="t('workOrderMaterial.unitPrice')"
          align="center"
          prop="unitPrice"
          :width="flexColumnWidth('unitPrice', t('workOrderMaterial.unitPrice'))"
        />
        <el-table-column
          :label="t('workOrderMaterial.total')"
          align="center"
          prop="totalInventoryQuantity"
          :width="flexColumnWidth('totalInventoryQuantity', t('workOrderMaterial.total'))"
        />
        <el-table-column
          :label="t('workOrderMaterial.source')"
          align="center"
          prop="materialSource"
          :width="flexColumnWidth('materialSource', t('workOrderMaterial.source'))"
        />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        style="padding: 0 0 5px; margin-bottom: 5px"
      />
    </ContentWrap>
  </Dialog>
  <MaintainMaterialDrawer
    ref="showDrawer"
    :model-value="drawerVisible"
    @update:model-value="(val) => (drawerVisible = val)"
    @add="handleChildSubmit"
  />
</template>

<script setup lang="ts">
import { IotMaintainMaterialVO } from '@/api/pms/maintain/material'
import * as WorkOrderBomMaterialApi from '@/api/pms/iotmainworkorderbommaterial'
import { defineExpose, ref } from 'vue'
import MaintainMaterialDrawer from '@/views/pms/maintain/material/MaintainMaterialDrawer.vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
// const emit = defineEmits(['choose']) // 定义 success 事件，用于操作成功后的回调
// 调整 emit 类型
const emit = defineEmits<{
  (e: 'choose', value: WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO[]): void
  (e: 'close'): void
}>()
// 跟踪新添加的行的索引
const lastAddedIndex = ref<number | null>(null)
const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const list = ref<WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const tableRef = ref()
const tableContainer = ref<HTMLElement | null>(null) // 表格容器引用
const selectedRows = ref<WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO[]>([]) // 多选数据（存储所有选中行的数组）

// 物料名称列宽度（作为基准列）
const materialNameWidth = ref<number | string>(0)

// 测量容器引用
const measureSpan = ref<HTMLDivElement | null>(null)

const showMaterialArea = ref(false) // 控制A区域显示状态
const deviceBomMaterials = ref<any[]>([]) // 存储绑定物料数据

const deviceName = ref('') // 设备名称
const deviceCode = ref('') // 设备编码
const bomNodeName = ref('') // 保养项 or 维修项 名称
const bomNodeLabel = ref('') // 保养项 or 维修项 名称

// 控制折叠区域的响应式变量
const showFoldArea = ref(false)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deptId: 0,
  bomNodeId: 0,
  deviceId: 0,
  name: '',
  code: '',
  materialCode: '',
  materialName: ''
})

// 保存初始查询参数用于重置
const defaultQueryParams = {
  materialName: '',
  materialCode: '',
  pageNo: 1,
  pageSize: 10
}

const drawerVisible = ref<boolean>(false)
const showDrawer = ref()
const handleView = () => {
  drawerVisible.value = true
  showDrawer.value.openDrawer()
}
const addMaterial = ref(null)

const handleChildSubmit = (formData) => {
  const modified = removeOnesFromKeys(formData)
  modified.materialName = modified.name
  modified.materialCode = modified.code
  modified.materialSource = '手动添加'
  modified.quantity = modified.depleteCount
  modified.unitPrice = modified.price
  addMaterial.value = modified
  list.value.unshift(modified)
  total.value = total.value + 1

  // 将新添加的行添加到选中列表
  selectedRows.value.push(modified)
  // 设置新添加行的索引
  lastAddedIndex.value = 0
}

const removeOnesFromKeys = (obj: Record<string, any>) => {
  return Object.keys(obj).reduce(
    (acc, key) => {
      const newKey = key.replace(/1/g, '') // 替换所有 1
      acc[newKey] = obj[key]
      return acc
    },
    {} as Record<string, any>
  )
}
// 点击整行选中
const handleRowClick = (row) => {
  toggleRow(row)
}
const open = async (deptId: number, bomNodeId: number, row: any, type: string) => {
  console.log('传递过来的数据：', row.deviceId)
  Object.assign(queryParams, defaultQueryParams)

  // 根据type设置折叠区域显隐
  showFoldArea.value = type === 'maintenance'

  selectedRows.value = []
  dialogVisible.value = true
  queryParams.deptId = deptId
  queryParams.bomNodeId = bomNodeId
  queryParams.deviceId = row.deviceId
  if (type === 'repair') {
    queryParams.deviceId = row.deviceId
  }
  deviceName.value = row.deviceName
  deviceCode.value = row.deviceCode
  bomNodeName.value = row.name
  if (type === 'maintenance') {
    bomNodeLabel.value = '保养项'
  } else if (type === 'repair') {
    bomNodeLabel.value = '维修项'
  }

  // 初始化BOM节点绑定的物料区域
  deviceBomMaterials.value = row.deviceBomMaterials || []
  showMaterialArea.value = false // 初始状态隐藏A区域
  await getList()
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 文本宽度测量
const getTextWidth = (text: string) => {
  if (!measureSpan.value) return 0
  measureSpan.value.innerText = text
  return measureSpan.value.offsetWidth
}

// 列宽计算方法
const flexColumnWidth = (prop: string, label: string, extra: number = 0) => {
  if (!list.value || list.value.length === 0) {
    return getTextWidth(label) + extra
  }

  const contentList = list.value.map((item) => {
    const value = item[prop]
    if (value == null) return ' '
    return typeof value === 'number' ? value.toString() : value
  })

  contentList.push(label)
  const maxWidth = Math.max(...contentList.map((text) => getTextWidth(text)))
  return Math.min(maxWidth + extra, 400)
}

// 计算所有列的总宽度（物料名称列除外）
const calculateTotalColumnWidth = () => {
  const columns = [
    // 复选框列（固定60px）
    60,
    // 工厂列
    flexColumnWidth('factory', t('workOrderMaterial.factory')),
    // 成本中心列
    flexColumnWidth('costCenter', t('workOrderMaterial.costCenter')),
    // 库存地点列
    flexColumnWidth('projectDepartment', t('workOrderMaterial.storageLocation')),
    // 物料编码列
    flexColumnWidth('materialCode', t('workOrderMaterial.materialCode')),
    // 消耗数量列
    flexColumnWidth('quantity', t('workOrderMaterial.ConsumptionQuantity'), 20),
    // 单位列
    flexColumnWidth('unit', t('workOrderMaterial.unit')),
    // 单价列
    flexColumnWidth('unitPrice', t('workOrderMaterial.unitPrice')),
    // 总库存数量列
    flexColumnWidth('totalInventoryQuantity', t('workOrderMaterial.total')),
    // 来源列
    flexColumnWidth('materialSource', t('workOrderMaterial.source'))
  ]

  return columns.reduce((total, width) => total + width, 0)
}

// 调整物料名称列宽度（作为基准列）
const adjustMaterialNameWidth = () => {
  nextTick(() => {
    if (!tableContainer.value) return

    // 获取表格容器的宽度
    const containerWidth = tableContainer.value.$el.clientWidth

    // 计算所有列的总宽度（物料名称列除外）
    const totalWidth = calculateTotalColumnWidth()

    // 计算可用空间（预留20px用于边框和滚动条）
    const availableSpace = containerWidth - totalWidth - 20

    if (availableSpace > 0) {
      // 如果空间足够，分配剩余空间给物料名称列
      materialNameWidth.value = Math.max(
        flexColumnWidth('materialName', t('workOrderMaterial.materialName')),
        availableSpace
      )
    } else {
      // 如果空间不足，按内容自适应
      materialNameWidth.value = flexColumnWidth('materialName', t('workOrderMaterial.materialName'))
    }
  })
}

const getList = async () => {
  loading.value = true
  try {
    // queryParams.deptId = props.deptId
    const data =
      await WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialApi.workOrderMaterials(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
    // 数据加载完成后调整基准列宽度
    nextTick(() => {
      adjustMaterialNameWidth()
    })
  }
}

// 确认选择
const handleConfirm = () => {
  // 检查是否有未通过校验的行
  const invalidRows = selectedRows.value.filter((row) => {
    const quantity = parseFloat(row.quantity)
    return isNaN(quantity) || quantity <= 0
  })

  if (invalidRows.length > 0) {
    ElMessage.error('存在无效的 消耗数量，请检查')
    return
  }

  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个物料')
    return
  }
  const filters = selectedRows.value.filter(
    (item) => item.quantity === null || item.quantity === undefined
  )
  if (filters.length > 0) {
    message.error('消耗数量必填')
    return
  }
  emit(
    'choose',
    selectedRows.value.map((row) => ({
      ...row,
      // 确保返回必要字段
      id: row.id,
      materialCode: row.materialCode,
      materialName: row.materialName,
      unitPrice: row.unitPrice,
      unit: row.unit,
      quantity: row.quantity
    }))
  )
  dialogVisible.value = false
  handleClose()
}

// 关闭时清空选择
const handleClose = () => {
  tableRef.value?.clearSelection()
  selectedRows.value = []
  emit('close')
}

const rowClassName = ({ row }: { row: any }) => {
  let className = ''
  if (row.bomMaterialFlag === 'Y') {
    className = ''
  }
  if (row.materialSource === '本地库存' && row.bomMaterialFlag != 'Y') {
    className = ''
  }
  if (row.materialSource === 'sap库存') {
    className = ''
  }
  return className
}

// 多选 切换行选中状态
const toggleRow = (row) => {
  // 创建复合唯一标识
  const getRowUniqueKey = (row) => {
    return `${row.factoryId}_${row.costCenterId}_${row.storageLocationId}_${row.materialCode}`
  }

  const currentKey = getRowUniqueKey(row)
  const index = selectedRows.value.findIndex((item) => getRowUniqueKey(item) === currentKey)

  if (index > -1) {
    selectedRows.value.splice(index, 1) // 取消选中
  } else {
    selectedRows.value.push(row) // 选中
  }
}

// 处理 消耗数量 quantity 输入框失焦事件
const handleQuantityBlur = (event: Event, row: any) => {
  const inputValue = (event.target as HTMLInputElement).value
  let num = parseFloat(inputValue)
  // 处理无效值
  if (isNaN(num)) {
    row.quantity = 0
    return
  }
  // 处理小于等于0的情况
  if (num <= 0) {
    row.quantity = 0
    return
  }
  // 保留两位小数
  row.quantity = parseFloat(num.toFixed(4))
}

// 处理输入框焦点事件（自动选中当前行）
const handleInputFocus = (row: WorkOrderBomMaterialApi.IotMainWorkOrderBomMaterialVO) => {
  const getRowUniqueKey = (row) => {
    return `${row.factoryId}_${row.costCenterId}_${row.storageLocationId}_${row.materialCode}`
  }
  const currentKey = getRowUniqueKey(row)
  // 如果未选中则添加到选中列表
  const exists = selectedRows.value.some((item) => getRowUniqueKey(item) === currentKey)
  if (!exists) {
    selectedRows.value.push(row)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const choose = (row: IotMaintainMaterialVO) => {
  emit('choose', row)
  dialogVisible.value = false
}
/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  Object.assign(queryParams, defaultQueryParams)
  handleQuery()
}

// 窗口大小改变时重新计算列宽
const handleResize = () => {
  adjustMaterialNameWidth()
}

onMounted(() => {
  // 添加窗口大小变化监听器
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口大小变化监听器
  window.removeEventListener('resize', handleResize)
})
</script>
<style lang="scss" scoped>
.no-label-radio .el-radio__label {
  display: none;
}

.no-label-radio .el-radio__inner {
  margin-right: 0;
}

/* 自定义淡绿色按钮 */
:deep(.custom-green-button) {
  color: #67c23a;
  background-color: #e1f3d8;
  border-color: #e1f3d8;
}

/* 悬停效果 */
:deep(.custom-green-button:hover) {
  color: #5daf34;
  background-color: #d1e8c0;
  border-color: #d1e8c0;
}

/* 点击效果 */
:deep(.custom-green-button:active) {
  background-color: #c2dca8;
  border-color: #c2dca8;
}

:deep(.el-table .row-green-bg) {
  background-color: #f0f9eb !important; /* Element Plus 绿色背景 */
}

:deep(.el-table .bg-blue-5) {
  background-color: #3fa5de !important; /* Element Plus 绿色背景 */
}

// 表格自适应样式
:deep(.adaptive-table) {
  width: 100%;
  font-size: 13px;

  .el-table__cell {
    padding: 4px 0;

    .cell {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap; /* 禁止换行 */
    }
  }
  // 确保基准列使用可用空间
  .material-name-cell .cell {
    display: block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .el-table__row {
    height: 36px;
  }
}

// 移除溢出提示（防止省略号）
:deep(.el-tooltip) {
  overflow: visible !important;
}

// 调整表格表头样式
:deep(.adaptive-table .el-table__header) {
  th {
    padding: 6px 0;

    .cell {
      font-size: 13px;
      font-weight: bold;
    }
  }
}

// 调整分页组件样式
:deep(.el-pagination) {
  padding: 8px 0;

  .btn-prev,
  .btn-next,
  .number {
    height: 28px;
    min-width: 28px;
    line-height: 28px;
  }
}

// 调整输入框高度
:deep(.el-input__inner) {
  height: 28px;
  line-height: 28px;
}

// 调整按钮样式
:deep(.el-button) {
  padding: 8px 12px;
}

// 调整表单标签样式
:deep(.el-form-item__label) {
  height: 28px;
  font-size: 13px;
  line-height: 28px;
}
</style>
