<template>
  <ContentWrap>
    <!-- 统计卡片 -->
    <div class="stock-check__header">
      <div v-for="card in statusCards" :key="card.key" class="stock-check__stat"
        :class="{ 'is-active': currentStatusKey === card.key }" @click="changeStatus(card.key, card.statusValue, card.checkStatusValue)">
        <div class="stock-check__stat-title">{{ card.label }}</div>
        <div class="stock-check__stat-value">{{ card.value }}</div>
      </div>
    </div>
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="auto"
      class="-mb-15px"
    >
      <el-form-item :label="t('ErpStock.Check.no')" prop="no">
        <el-input
          v-model="queryParams.no"
          :placeholder="t('ErpStock.Check.placeholderNo')"
          clearable
          class="!w-240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.Check.warehouse')" prop="warehouseId">
        <el-select
          v-model="queryParams.warehouseId"
          :placeholder="t('ErpStock.Check.placeholderWarehouse')"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('ErpStock.Check.checkTime')" prop="checkTime">
        <el-date-picker
          v-model="queryParams.checkTime"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('ErpStock.Check.status')" prop="status" v-show="showAllFilters">
        <el-select
          v-model="queryParams.status"
          :placeholder="t('ErpStock.Check.placeholderStatus')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ERP_AUDIT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="filterCount > 3">
        <el-button type="text" class="text-primary" @click="toggleFilters">
          <Icon :icon="showAllFilters ? 'ep:arrow-up' : 'ep:arrow-down'" class="mr-5px" />
          {{ showAllFilters ? t('FactoryModeling.FactoryStructure.collapseText') :
            t('FactoryModeling.FactoryStructure.expandText') }}
        </el-button>
      </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-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:stock-check:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.create') }}
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="selectionList.length === 0"
          @click="handleDelete(selectionList.map((item) => item.id))"
        >
          <Icon icon="ep:delete" class="mr-5px" />
          {{ t('action.batchDelete') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :max-height="planTableMaxHeight"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="45" />
      <el-table-column :label="t('ErpStock.Check.no')" prop="no" align="center" min-width="150" />
      <el-table-column
        :label="t('ErpStock.Check.productNames')"
        prop="productNames"
        min-width="180"
        show-overflow-tooltip
      />
      <el-table-column :label="t('ErpStock.Check.warehouse')" min-width="140" show-overflow-tooltip>
        <template #default="{ row }">
          {{ getWarehouseNames(row) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('ErpStock.Check.checkTime')"
        prop="checkTime"
        :formatter="dateFormatter"
        min-width="170"
      />
      <el-table-column :label="t('ErpStock.Check.status')" prop="status" align="center" min-width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_AUDIT_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="t('ErpStock.Check.checkStatus')" prop="checkStatus" align="center" min-width="100">
        <template #default="scope">
          <el-tag :type="Number(scope.row.checkStatus) === 1 ? 'success' : 'info'">
            {{
              Number(scope.row.checkStatus) === 1
                ? t('ErpStock.Check.checkStatusChecked')
                : t('ErpStock.Check.checkStatusUnchecked')
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('ErpStock.Check.creator')"
        prop="creatorName"
        align="center"
        min-width="120"
      />
      <el-table-column
        label="创建时间"
        prop="createTime"
        :formatter="dateFormatter"
        min-width="170"
      />
      <el-table-column :label="t('ErpStock.Check.auditUserName')" prop="auditUserName" align="center" min-width="120" />
      <el-table-column
        :label="t('ErpStock.Check.remark')"
        prop="remark"
        min-width="160"
        show-overflow-tooltip
      />
      <el-table-column :label="t('common.operate')" align="center" fixed="right" width="320">
        <template #default="scope">
          <el-button
            v-if="!isAuditDisabled && Number(scope.row.status) === 10 && Number(scope.row.checkStatus) === 1"
            link
            type="primary"
            @click="openAuditDialog(scope.row, 20)"
          >
            {{ t('ErpStock.Check.auditApprove') }}
          </el-button>
          <el-button
            v-if="!isAuditDisabled && Number(scope.row.status) === 10 && Number(scope.row.checkStatus) === 1"
            link
            type="danger"
            @click="openAuditDialog(scope.row, 1)"
          >
            {{ t('ErpStock.Check.auditReject') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('detail', scope.row.id)"
          >
            {{ t('action.detail') }}
          </el-button>
          <el-button
            link
            type="primary"
            :disabled="isEditDisabled(scope.row)"
            @click="openForm('update', scope.row.id, scope.row)"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            v-if="(isAuditDisabled ? [0, 1, 10] : [0, 1]).includes(Number(scope.row.status)) && Number(scope.row.checkStatus) === 1"
            link
            type="primary"
            @click="openSubmitDialog(scope.row)"
          >
            {{ t('ErpStock.Check.submit') }}
          </el-button>
          <el-button
            v-if="Number(scope.row.checkStatus) !== 1 || Number(scope.row.status) === 1"
            link
            type="warning"
            :disabled="scope.row.status === 20"
            @click="openForm('check', scope.row.id)"
          >
            {{ t('ErpStock.Check.inventoryCheck') }}
          </el-button>
          <el-button
            link
            type="danger"
            :disabled="scope.row.status === 20"
            @click="handleDelete([scope.row.id])"
          >
            {{ t('action.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>

  <Dialog :title="submitActionText" v-model="submitDialogVisible" width="500">
    <el-form :model="submitForm" label-width="auto">
      <el-form-item :label="t('ErpStock.Check.submitRemark')" prop="remark">
        <el-input
          v-model="submitForm.remark"
          type="textarea"
          :rows="3"
          :placeholder="t('ErpStock.Check.placeholderSubmitRemark')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="submitLoading" @click="handleSubmit">
        {{ t('common.ok') }}
      </el-button>
      <el-button @click="submitDialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>

  <Dialog :title="auditDialogTitle" v-model="auditDialogVisible" width="500">
    <el-form :model="auditForm" label-width="auto">
      <el-form-item :label="t('ErpStock.Check.auditRemark')" prop="remark">
        <el-input
          v-model="auditForm.remark"
          type="textarea"
          :rows="3"
          :placeholder="t('ErpStock.Check.placeholderAuditRemark')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="auditLoading" @click="handleAudit">
        {{ t('common.ok') }}
      </el-button>
      <el-button @click="auditDialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>

  <StockCheckExecutionForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { StockCheckApi, type StockCheckVO } from '@/api/erp/stock/check'
import { WarehouseApi, type WarehouseVO } from '@/api/erp/stock/warehouse'

import * as ConfigApi from '@/api/infra/config'
import StockCheckExecutionForm from './components/StockCheckExecutionForm.vue'

defineOptions({ name: 'ErpStockCheckExecution' })

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

const loading = ref(false)
const list = ref<StockCheckVO[]>([])
const total = ref(0)
const tableRef = ref()
const planTableMaxHeight = ref(520)
const planPaginationRef = ref<HTMLElement>()

const updatePlanTableMaxHeight = async () => {
  await nextTick()
  const tableTop = tableRef.value?.$el?.getBoundingClientRect().top ?? 0
  const paginationHeight = planPaginationRef.value?.getBoundingClientRect().height ?? 72
  const pageBottomGap = 56
  const availableHeight = window.innerHeight - tableTop - paginationHeight - pageBottomGap
  planTableMaxHeight.value = Math.min(window.innerHeight, Math.max(240, Math.floor(availableHeight)))
}
const warehouseList = ref<WarehouseVO[]>([])
const selectionList = ref<StockCheckVO[]>([])
const queryFormRef = ref()
const currentStatusKey = ref('all')
const counters = reactive({
  allCount: 0,
  waitSubmitCount: 0,
  rejectedCount: 0,
  auditingCount: 0,
  approvedCount: 0,
  checkedCount: 0,
  uncheckedCount: 0
})
const statusCards = computed(() => [
  { key: 'all', label: t('ErpStock.Check.all'), value: counters.allCount, statusValue: undefined, checkStatusValue: undefined },
  { key: 'waitSubmit', label: t('ErpStock.Check.waitSubmit'), value: counters.waitSubmitCount, statusValue: 0, checkStatusValue: undefined },
  { key: 'rejected', label: t('ErpStock.Check.rejected'), value: counters.rejectedCount, statusValue: 1, checkStatusValue: undefined },
  { key: 'auditing', label: t('ErpStock.Check.auditing'), value: counters.auditingCount, statusValue: 10, checkStatusValue: undefined },
  { key: 'approved', label: t('ErpStock.Check.approved'), value: counters.approvedCount, statusValue: 20, checkStatusValue: undefined },
  { key: 'checked', label: t('ErpStock.Check.checked'), value: counters.checkedCount, statusValue: undefined, checkStatusValue: 1 },
  { key: 'unchecked', label: t('ErpStock.Check.unchecked'), value: counters.uncheckedCount, statusValue: undefined, checkStatusValue: 0 }
])
const changeStatus = (key: string, statusValue: number | undefined, checkStatusValue: number | undefined) => {
  currentStatusKey.value = key
  queryParams.status = statusValue
  queryParams.checkStatus = checkStatusValue
  handleQuery()
}
const showAllFilters = ref(false)
const filterCount = 4
const toggleFilters = () => {
  showAllFilters.value = !showAllFilters.value
  updatePlanTableMaxHeight()
}
const formRef = ref()
const submitDialogVisible = ref(false)
const submitLoading = ref(false)
const submitForm = reactive({
  id: undefined as number | undefined,
  remark: undefined as string | undefined
})
const isAuditDisabled = ref(false)
const submitActionText = computed(() =>
  t('ErpStock.Check.submit')
)
const auditDialogVisible = ref(false)
const auditLoading = ref(false)
const auditForm = reactive({
  id: undefined as number | undefined,
  status: undefined as number | undefined,
  remark: undefined as string | undefined
})
const auditDialogTitle = computed(() =>
  auditForm.status === 20 ? t('ErpStock.Check.auditApprove') : t('ErpStock.Check.auditReject')
)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined as string | undefined,
  warehouseId: undefined as number | undefined,
  checkTime: [] as string[],
  status: undefined as number | undefined,
  checkStatus: undefined as number | undefined
})

const getList = async () => {
  loading.value = true
  try {
    const data = await StockCheckApi.getStockCheckPage(queryParams)
    list.value = data?.list || []
    total.value = data?.total || 0
    counters.allCount = Number(data?.allCount ?? data?.total ?? 0)
    counters.waitSubmitCount = Number(data?.waitSubmitCount ?? 0)
    counters.rejectedCount = Number(data?.rejectedCount ?? 0)
    counters.auditingCount = Number(data?.auditingCount ?? 0)
    counters.approvedCount = Number(data?.approvedCount ?? 0)
    counters.checkedCount = Number(data?.checkedCount ?? 0)
    counters.uncheckedCount = Number(data?.uncheckedCount ?? 0)
  } finally {
    loading.value = false
    updatePlanTableMaxHeight()
  }
}

const loadAuditConfig = async () => {
  try {
    const data = await ConfigApi.getConfigPage({ pageNo: 1, pageSize: 10, key: 'inventoryAudit' } as PageParam & { key: string })
    const auditConfig = data?.list?.find((item) => item?.key === 'inventoryAudit')
    isAuditDisabled.value = auditConfig?.value === '0'
  } catch {
    isAuditDisabled.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  currentStatusKey.value = 'all'
  queryFormRef.value?.resetFields()
  handleQuery()
}

const isEditDisabled = (row: StockCheckVO) => {
  return Number(row.status) === 20 || (Number(row.checkStatus) === 1 && Number(row.status) !== 1)
}

const openForm = (type: string, id?: number, row?: StockCheckVO) => {
  if (type === 'update' && row && isEditDisabled(row)) {
    return
  }
  formRef.value.open(type, id)
}

const handleDelete = async (ids: number[]) => {
  if (ids.length === 0) {
    return
  }
  try {
    await message.delConfirm()
    await StockCheckApi.deleteStockCheck(ids)
    message.success(t('common.delSuccess'))
    selectionList.value = selectionList.value.filter((item) => !ids.includes(item.id))
    await getList()
  } catch {}
}

const handleSelectionChange = (rows: StockCheckVO[]) => {
  selectionList.value = rows
}

const openSubmitDialog = (row: StockCheckVO) => {
  const hasIncompleteItem = (row.items || []).some(
    (item) => item.actualCount === undefined || item.actualCount === null || item.actualCount === ''
  )
  if (hasIncompleteItem) {
    message.warning(t('ErpStock.Check.validatorCompleteCheckInfo'))
    return
  }
  submitForm.id = row.id
  submitForm.remark = undefined
  submitDialogVisible.value = true
}

const handleSubmit = async () => {
  if (!submitForm.id) {
    return
  }
  submitLoading.value = true
  try {
    if (isAuditDisabled.value) {
      await StockCheckApi.auditStockCheck({
        id: submitForm.id,
        status: 20,
        remark: submitForm.remark
      })
      message.success(t('ErpStock.Check.auditApproveSuccess'))
      submitDialogVisible.value = false
      await getList()
      return
    }
    const data: { id: number; remark?: string } = {
      id: submitForm.id,
      remark: submitForm.remark
    }
    await StockCheckApi.submitStockCheck(data)
    message.success(t('ErpStock.Check.submitSuccess'))
    submitDialogVisible.value = false
    await getList()
  } finally {
    submitLoading.value = false
  }
}

const openAuditDialog = (row: StockCheckVO, status: number) => {
  auditForm.id = row.id
  auditForm.status = status
  auditForm.remark = undefined
  auditDialogVisible.value = true
}

const handleAudit = async () => {
  if (!auditForm.id || !auditForm.status) {
    return
  }
  auditLoading.value = true
  try {
    await StockCheckApi.auditStockCheck({
      id: auditForm.id,
      status: auditForm.status,
      remark: auditForm.remark
    })
    message.success(
      auditForm.status === 20
        ? t('ErpStock.Check.auditApproveSuccess')
        : t('ErpStock.Check.auditRejectSuccess')
    )
    auditDialogVisible.value = false
    await getList()
  } finally {
    auditLoading.value = false
  }
}

const getWarehouseNames = (row: StockCheckVO) => {
  const names = Array.from(new Set((row.items || []).map((item) => item.warehouseName).filter(Boolean)))
  return names.length ? names.join('、') : '-'
}

onMounted(async () => {
  const [warehouses] = await Promise.all([
    WarehouseApi.getWarehouseSimpleList(),
    loadAuditConfig()
  ])
  warehouseList.value = warehouses || []
  await getList()
  updatePlanTableMaxHeight()
  window.addEventListener('resize', updatePlanTableMaxHeight)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', updatePlanTableMaxHeight)
})
</script>

<style scoped lang="scss">
.stock-check__header {
  display: grid;
  grid-template-columns: repeat(7, minmax(0, 1fr));
  gap: 12px;
  width: 100%;
  margin-bottom: 16px;
}

.stock-check__stat {
  padding: 16px 18px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 12px;
  cursor: pointer;
  transition: box-shadow 0.2s ease;
  background: #fff;

  &:hover {
    box-shadow: 0 10px 24px rgba(64, 158, 255, 0.12);
  }

  &.is-active {
    border-color: var(--el-color-primary);
    box-shadow: 0 10px 24px rgba(64, 158, 255, 0.12);
  }
}

.stock-check__stat-title {
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.stock-check__stat-value {
  margin-top: 8px;
  color: var(--el-text-color-primary);
  font-size: 28px;
  font-weight: 700;
  line-height: 1;
}
</style>
