<template>
  <div v-if="!props.disabled" class="device-ledger-layout">
    <div class="device-ledger-right">
      <ContentWrap>
        <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item :label="t('MoldManagement.Mold.code')" prop="code">
            <el-input
v-model="queryParams.code" :placeholder="t('MoldManagement.Mold.code')" clearable @keyup.enter="handleQuery"
              class="!w-240px" />
          </el-form-item>
          <el-form-item :label="t('MoldManagement.Mold.name')" prop="name">
            <el-input
v-model="queryParams.name" :placeholder="t('MoldManagement.Mold.name')" 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-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
<el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @selection-change="handleSelectionChange" ref="tableRef" :row-key="row => row.id">
      <el-table-column width="30" type="selection" />
      <el-table-column :label="t('MoldManagement.Mold.code')" align="center" prop="code" />
      <el-table-column :label="t('MoldManagement.Mold.name')" align="left" prop="name" />
      <el-table-column :label="t('MoldManagement.Mold.useTime')" align="center" prop="useTime" />
      <el-table-column :label="t('MoldManagement.Mold.status')" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_MOLD_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.Mold.machineName')" align="center" prop="machineName" />
      <el-table-column :label="t('MoldManagement.Mold.remark')" align="center" prop="remark" />
      <el-table-column :label="t('MoldManagement.Mold.isEnable')" align="center" prop="isEnable">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.isEnable" />
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.Mold.createTime')" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
    </el-table>
        <Pagination
:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
          @pagination="getList" />
      </ContentWrap>
    </div>
  </div>
  <div v-else>
    <ContentWrap>
      <el-table :data="props.items || []" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="产品名称" prop="productName" />
        <el-table-column label="产品条码" prop="productBarCode" />
        <el-table-column label="数量" prop="count" />
        <el-table-column label="单价" prop="productPrice" />
        <el-table-column label="备注" prop="remark" />
      </el-table>
    </ContentWrap>
  </div>
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { MoldBrandApi, MoldVO } from '@/api/erp/mold'
import { useDictStoreWithOut } from '@/store/modules/dict'


const props = defineProps<{
  items?: any[]
  disabled?: boolean
}>()

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

const loading = ref(false) // 列表的加载中
const list = ref<MoldVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  name: undefined,
  brand: undefined,
})
const queryFormRef = ref() // 搜索的表单



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

/** 查询列表 */
const getList = async () => {
  loading.value = true
  ignoreSelectionChange.value = true
  try {
    const data = await MoldBrandApi.getMoldPage({
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      code: queryParams.code,
      name: queryParams.name,
      brandId: queryParams.brand,
      statuss: [3,0]
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
    await nextTick()
    ignoreSelectionChange.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const tableRef = ref()
const selectedRows = ref<any[]>([])
const ignoreSelectionChange = ref(false)

watch(list, async () => {
  await nextTick()
  restoreSelection()
})

watch(
  () => props.items,
  async (val) => {
    if (!val || !Array.isArray(val) || val.length === 0) {
      selectedRows.value = []
      await nextTick()
      restoreSelection()
      return
    }

    const ids = (val as any[])
      .map((item) => item.productId ?? item.id)
      .filter((id) => id !== undefined && id !== null)

    const uniqIds = Array.from(new Set(ids))
    selectedRows.value = uniqIds.map((id) => ({ id }))

    await nextTick()
    restoreSelection()
  },
  { immediate: true, deep: true }
)

const restoreSelection = () => {
  if (!tableRef.value || selectedRows.value.length === 0) return
  tableRef.value.clearSelection?.()
  selectedRows.value.forEach(selectedRow => {
    const rowInTable = list.value.find(row => row.id === selectedRow.id)
    if (rowInTable) {
      tableRef.value.toggleRowSelection?.(rowInTable, true)
    }
  })
}

const handleSelectionChange = (rows: any[]) => {
  if (ignoreSelectionChange.value) return
  const currentPageIds = list.value.map((row) => row.id)
  const currentSelectedIdSet = new Set(rows.map((row) => row.id))

  selectedRows.value = selectedRows.value.filter(
    (row) => !currentPageIds.includes(row.id) || currentSelectedIdSet.has(row.id)
  )

  rows.forEach((row) => {
    if (!selectedRows.value.some((r) => r.id === row.id)) {
      selectedRows.value.push(row)
    }
  })
}

const validate = async (): Promise<boolean> => {
  if (!tableRef.value) return false
  
  try {
    await tableRef.value.validate()
    return true
  } catch (error) {
    return false
  }
}
defineExpose({ validate,selectedRows: selectedRows })

/** 初始化 **/
onMounted(async () => {
  await dictStore.setDictMap()
  dictReady.value = true
  getList()
})

</script>

<style scoped>
.device-ledger-layout {
  display: flex;
  gap: 12px;
}

.device-ledger-left {
  width: 280px;
  flex: 0 0 auto;
}

.device-ledger-right {
  flex: 1;
  min-width: 0;
}

.device-ledger-detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.device-ledger-detail-title {
  font-size: 14px;
  font-weight: 600;
}

.device-ledger-history-steps {
  padding: 8px 8px 0;
}

.device-ledger-history-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 13px;
}

.device-ledger-history-time {
  font-weight: 600;
}

.device-ledger-history-operator {
  color: var(--el-text-color-secondary);
}

.device-ledger-tab-toolbar {
  margin-bottom: 8px;
  text-align: right;
}

.device-ledger-history-items {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-top: 8px;
}

.device-ledger-history-item {
  display: flex;
  padding: 10px;
  background: var(--el-fill-color-blank);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  flex-direction: column;
  gap: 8px;
}

.device-ledger-history-item-head {
  display: flex;
  align-items: center;
  gap: 10px;
}

.device-ledger-history-item-body {
  display: flex;
  flex-direction: column;
  gap: 6px;
  width: 100%;
}

.device-ledger-history-item-row {
  display: flex;
  gap: 10px;
}

.device-ledger-history-item-label {
  width: 70px;
  flex: 0 0 70px;
  color: var(--el-text-color-secondary);
}

.device-ledger-history-item-value {
  flex: 1;
  color: var(--el-text-color-regular);
  word-break: break-word;
}

.device-ledger-history-item-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 4px;
}

.device-ledger-history-item-image {
  width: 76px;
  height: 76px;
  overflow: hidden;
  border-radius: 6px;
}

.device-ledger-history-image-error {
  display: flex;
  width: 100%;
  height: 100%;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color);
  align-items: center;
  justify-content: center;
}

.device-ledger-repair-collapse {
  padding: 8px 8px 0;
}

.device-ledger-repair-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.device-ledger-repair-name {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.device-ledger-repair-meta {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.device-ledger-history-item-text {
  color: var(--el-text-color-regular);
}
</style>
