<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <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="materialName">
              <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="批次码" prop="batchCode">
              <el-input v-model="queryParams.batchCode" placeholder="请输入批次码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="库位编码" prop="locationCode">
              <el-input v-model="queryParams.locationCode" placeholder="请输入库位编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable>
                <el-option
                  v-for="item in baseStoreList"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="变动类型" prop="changeType">
              <el-select v-model="queryParams.changeType" placeholder="请选择变动类型" clearable>
                <el-option label="入库" value="INBOUND"/>
                <el-option label="出库" value="OUTBOUND"/>
<!--                <el-option label="调拨入" value="TRANSFER_IN"/>-->
<!--                <el-option label="调拨出" value="TRANSFER_OUT"/>-->
                <el-option label="退库" value="RETURN"/>
<!--                <el-option label="盘盈" value="ADJUST_INCREASE"/>-->
<!--                <el-option label="盘亏" value="ADJUST_DECREASE"/>-->
              </el-select>
            </el-form-item>
            <!--            <el-form-item label="变动日期" style="width: 308px">
                          <el-date-picker
                            v-model="dateRange"
                            value-format="YYYY-MM-DD"
                            type="daterange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            @change="handleDateChange"
                          />
                        </el-form-item>-->
            <el-form-item>
              <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="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:inventory:export']">导出台账</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="ledgerList" stripe fit>
        <el-table-column label="变动日期" align="center" prop="changeDate" v-if="columns[0].visible" width="180">
          <template #default="scope">
            {{ parseTime(scope.row.changeDate, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </template>
        </el-table-column>
        <el-table-column label="变动类型" align="center" prop="changeTypeName" v-if="columns[1].visible" width="120">
          <template #default="scope">
            <el-tag
              :type="getChangeTypeTag(scope.row.changeType)"
              effect="plain"
            >
              {{ scope.row.changeTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关联单号" align="center" prop="relatedCode" v-if="columns[2].visible" min-width="220"/>
        <el-table-column label="物料编码" align="center" prop="materialCode" v-if="columns[3].visible" min-width="150"/>
        <el-table-column label="物料名称" align="center" prop="materialName" v-if="columns[4].visible" min-width="200" show-overflow-tooltip/>
        <el-table-column label="批次码" align="center" prop="batchCode" v-if="columns[5].visible" min-width="280"/>
        <el-table-column label="仓库" align="center" prop="warehouseName" v-if="columns[6].visible" min-width="120"/>
        <el-table-column label="库位编码" align="center" prop="locationCode" v-if="columns[7].visible" min-width="120"/>
        <el-table-column label="变动数量" align="center" prop="changeQty" v-if="columns[8].visible" min-width="120">
          <template #default="scope">
            <span :class="scope.row.changeQty >= 0 ? 'text-green-600' : 'text-red-600'">
              {{ scope.row.changeQty >= 0 ? '+' : '' }}{{ scope.row.changeQty }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="结存数量" align="center" prop="balanceQty" v-if="columns[9].visible" min-width="120"/>
        <!--        <el-table-column label="操作人" align="center" prop="operatorName" v-if="columns[10].visible" width="100"/>-->
      </el-table>

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

  </div>
</template>

<script setup name="InventoryLedger" lang="ts">
import { listInventoryLedger, exportInventoryLedger } from '@/api/wms/inventoryLedger';
import { InventoryLedgerVO, InventoryLedgerQuery } from '@/api/wms/inventoryLedger/types';
import { getBaseWarehouseList } from "@/api/wms/baseWarehouse";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const ledgerList = ref<InventoryLedgerVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const dateRange = ref<[string, string]>([]);

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `变动日期`, visible: true },
  { key: 1, label: `变动类型`, visible: true },
  { key: 2, label: `关联单号`, visible: true },
  { key: 3, label: `物料编码`, visible: true },
  { key: 4, label: `物料名称`, visible: true },
  { key: 5, label: `批次码`, visible: true },
  { key: 6, label: `仓库`, visible: true },
  { key: 7, label: `库位编码`, visible: true },
  { key: 8, label: `变动数量`, visible: true },
  { key: 9, label: `结存数量`, visible: true },
  // { key: 10, label: `操作人`, visible: true },
]);

const queryParams = ref<InventoryLedgerQuery>({
  pageNum: 1,
  pageSize: 10,
  materialCode: undefined,
  materialName: undefined,
  batchCode: undefined,
  locationCode: undefined,
  warehouseId: undefined,
  changeType: undefined,
  beginTime: undefined,
  endTime: undefined
});

let baseStoreList = ref([]);

/** 查询仓库下拉列表 */
const getBaseWarehouseListsss = async () => {
  let res = await getBaseWarehouseList(null);
  baseStoreList.value = res.data;
};

/** 查询库存台账列表 */
const getList = async () => {
  loading.value = true;
  // 处理日期范围
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginTime = dateRange.value[0];
    queryParams.value.endTime = dateRange.value[1];
  } else {
    queryParams.value.beginTime = undefined;
    queryParams.value.endTime = undefined;
  }

  const res = await listInventoryLedger(queryParams.value);
  ledgerList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  dateRange.value = [];
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    materialCode: undefined,
    materialName: undefined,
    batchCode: undefined,
    locationCode: undefined,
    warehouseId: undefined,
    changeType: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 日期范围变化处理 */
const handleDateChange = (value: [string, string] | null) => {
  dateRange.value = value || [];
}

/** 获取变动类型标签样式 */
const getChangeTypeTag = (changeType: string): string => {
  const typeMap: Record<string, string> = {
    'INBOUND': 'success',    // 入库 - 绿色
    'OUTBOUND': 'danger',    // 出库 - 红色
    'TRANSFER_IN': 'primary', // 调拨入 - 蓝色
    'TRANSFER_OUT': 'warning', // 调拨出 - 橙色
    'RETURN': 'info',        // 退库 - 灰色
    'ADJUST_INCREASE': 'success', // 盘盈 - 绿色
    'ADJUST_DECREASE': 'danger'   // 盘亏 - 红色
  };
  return typeMap[changeType] || '';
}

/** 导出按钮操作 */
const handleExport = () => {
  // 处理日期范围
  const exportParams = { ...queryParams.value };
  if (dateRange.value && dateRange.value.length === 2) {
    exportParams.beginTime = dateRange.value[0];
    exportParams.endTime = dateRange.value[1];
  }

  proxy?.download('wms/inventory/ledger/export', exportParams, `inventory_ledger_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getBaseWarehouseListsss();
  getList();
});
</script>
