<template>
  <div class="p-2 wcs-inoutrecord-page">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px] inoutrecord-search-wrap">
        <el-card class="inoutrecord-search-card" shadow="hover">
          <el-form ref="queryFormRef" class="inoutrecord-query-form" :model="queryParams" :inline="true">
            <el-form-item label="出入库方向" prop="inoutFlag">
              <el-select v-model="queryParams.inoutFlag" placeholder="请选择方向" clearable>
                <el-option v-for="dict in inout_flag" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
            <el-form-item label="物料类型" prop="materialType">
              <el-input v-model="queryParams.materialType" placeholder="请输入物料类型" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="物料编号" prop="materialCode">
              <el-input v-model="queryParams.materialCode" placeholder="请输入物料编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable filterable>
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="formatWarehouseLabel(item)"
                  :value="String(item.warehouseId)"
                />
              </el-select>
            </el-form-item>
            <el-form-item class="inoutrecord-date-range" label="创建时间">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </el-form-item>
            <el-form-item class="inoutrecord-query-actions">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wcs:inoutrecord:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="inoutrecordList">
        <el-table-column v-if="columns[0].visible" type="index" label="序号" width="60" align="center" />
        <el-table-column v-if="columns[1].visible" label="出入库方向" align="center" prop="inoutFlag" width="120">
          <template #default="scope">
            <dict-tag :options="inout_flag" :value="scope.row.inoutFlag" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[2].visible" label="物料类型" align="center" prop="materialType" min-width="120" />
        <el-table-column
          v-if="columns[3].visible"
          label="物料编号"
          align="center"
          prop="materialCode"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column v-if="columns[4].visible" label="仓库" align="center" prop="warehouseId" min-width="140">
          <template #default="scope">
            <span>{{ getWarehouseName(scope.row.warehouseId) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[5].visible" label="出入库人员" align="center" prop="createuser" width="120" />
        <el-table-column v-if="columns[6].visible" label="创建时间" align="center" prop="createTime" width="170">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[7].visible" label="更新时间" align="center" prop="updateTime" width="170">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['wcs:inoutrecord:query']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <el-dialog class="inoutrecord-detail-dialog" title="出入库记录详情" v-model="detailOpen" width="720px" append-to-body>
      <el-descriptions v-if="currentRecord" class="inoutrecord-detail-descriptions" :column="2" border>
        <el-descriptions-item label="出入库方向">
          <dict-tag :options="inout_flag" :value="currentRecord.inoutFlag" />
        </el-descriptions-item>
        <el-descriptions-item label="仓库">{{ getWarehouseName(currentRecord.warehouseId) }}</el-descriptions-item>
        <el-descriptions-item label="物料类型">{{ currentRecord.materialType }}</el-descriptions-item>
        <el-descriptions-item label="物料编号">{{ currentRecord.materialCode }}</el-descriptions-item>
        <el-descriptions-item label="出入库人员">{{ currentRecord.createuser }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(currentRecord.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{ parseTime(currentRecord.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup name="Inoutrecord" lang="ts">
import { getInoutrecord, listInoutrecord } from '@/api/wcs/inoutrecord';
import { InoutrecordQuery, InoutrecordVO } from '@/api/wcs/inoutrecord/types';
import { listWarehouse } from '@/api/wcs/warehouse';
import { WarehouseVO } from '@/api/wcs/warehouse/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { inout_flag } = toRefs<any>(proxy?.useDict('inout_flag'));

const inoutrecordList = ref<InoutrecordVO[]>([]);
const warehouseOptions = ref<WarehouseVO[]>([]);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const dateRange = ref<[string, string]>(['', '']);
const detailOpen = ref(false);
const currentRecord = ref<InoutrecordVO>();

const queryFormRef = ref<ElFormInstance>();

const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: '出入库方向', visible: true, children: [] },
  { key: 2, label: '物料类型', visible: true, children: [] },
  { key: 3, label: '物料编号', visible: true, children: [] },
  { key: 4, label: '仓库', visible: true, children: [] },
  { key: 5, label: '出入库人员', visible: true, children: [] },
  { key: 6, label: '创建时间', visible: true, children: [] },
  { key: 7, label: '更新时间', visible: true, children: [] }
]);

const queryParams = ref<InoutrecordQuery>({
  pageNum: 1,
  pageSize: 10,
  inoutFlag: undefined,
  materialType: undefined,
  materialCode: undefined,
  warehouseId: undefined,
  params: {}
});

const buildQueryParams = () => {
  // 后端按 params.beginCreateTime/endCreateTime 过滤，前端统一在查询前组装，避免表单字段污染BO。
  queryParams.value.params = {
    beginCreateTime: dateRange.value?.[0] || undefined,
    endCreateTime: dateRange.value?.[1] || undefined
  };
  return queryParams.value;
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listInoutrecord(buildQueryParams());
    inoutrecordList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const getWarehouseOptions = async () => {
  const res = await listWarehouse({ pageNum: 1, pageSize: 1000 });
  warehouseOptions.value = res.rows || [];
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleDetail = async (row: InoutrecordVO) => {
  const res = await getInoutrecord(row.id);
  currentRecord.value = res.data;
  detailOpen.value = true;
};

const handleExport = () => {
  proxy?.download('wcs/inoutrecord/export', { ...buildQueryParams() }, `inoutrecord_${new Date().getTime()}.xlsx`);
};

const getWarehouseName = (warehouseId?: string) => {
  const warehouse = warehouseOptions.value.find((item) => String(item.warehouseId) === String(warehouseId));
  return warehouse ? `${warehouse.warehouseName}（${warehouse.warehouseId}）` : warehouseId || '';
};

const formatWarehouseLabel = (item: WarehouseVO) => {
  return `${item.warehouseName || '未命名仓库'}（${item.warehouseId}）`;
};

onMounted(async () => {
  await getWarehouseOptions();
  await getList();
});
</script>

<style scoped lang="scss">
.wcs-inoutrecord-page {
  /* 出入库记录常按时间段回溯，日期范围独立占宽，避免开始/结束时间被压缩。 */
  :deep(.inoutrecord-search-card) {
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 8px;
    box-shadow: 0 8px 22px rgb(15 23 42 / 6%);
  }

  :deep(.inoutrecord-search-card .el-card__body) {
    padding: 16px 18px 6px;
  }

  :deep(.inoutrecord-query-form) {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
    column-gap: 16px;
    align-items: start;
  }

  :deep(.inoutrecord-query-form .el-form-item) {
    margin-right: 0;
    margin-bottom: 12px;
  }

  :deep(.inoutrecord-query-form .el-form-item__label) {
    justify-content: flex-start;
    width: 96px;
    color: var(--el-text-color-regular);
  }

  :deep(.inoutrecord-query-form .el-input),
  :deep(.inoutrecord-query-form .el-select),
  :deep(.inoutrecord-query-form .el-date-editor) {
    width: 100%;
  }

  :deep(.inoutrecord-date-range) {
    grid-column: span 2;
  }

  :deep(.inoutrecord-query-actions) {
    grid-column: 1 / -1;
  }

  :deep(.inoutrecord-query-actions .el-form-item__content) {
    justify-content: flex-end;
    gap: 8px;
  }
}

:global(.inoutrecord-detail-dialog) {
  width: min(720px, calc(100vw - 32px)) !important;
}

:global(.inoutrecord-detail-dialog .el-dialog__header) {
  padding: 18px 22px 14px;
  background: linear-gradient(90deg, rgb(37 99 235 / 8%), rgb(20 184 166 / 6%));
}

:global(.inoutrecord-detail-dialog .el-dialog__body) {
  padding: 20px 24px 24px !important;
}

:global(.inoutrecord-detail-dialog .inoutrecord-detail-descriptions) {
  --el-descriptions-table-border: 1px solid var(--el-border-color-lighter);
}

:global(.inoutrecord-detail-dialog .el-descriptions__label) {
  width: 118px;
  color: var(--el-text-color-regular);
  background: var(--el-fill-color-lighter) !important;
}

:global(.inoutrecord-detail-dialog .el-descriptions__content) {
  color: var(--el-text-color-primary);
}

@media (max-width: 768px) {
  .wcs-inoutrecord-page {
    :deep(.inoutrecord-query-form) {
      grid-template-columns: 1fr;
    }

    :deep(.inoutrecord-date-range) {
      grid-column: 1;
    }
  }
}
</style>
