<template>
  <div>
    <el-dialog v-model="inventoryDialog.visible.value" :title="inventoryDialog.title.value" width="80%" append-to-body>
      <el-row :gutter="20">
        <el-col :span="24">
          <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" label-width="100px">
                  <el-form-item label="仓库" prop="warehouseId" v-if="!prop.warehouseId">
                    <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable filterable>
                      <el-option
                        v-for="warehouse in warehouseList"
                        :key="warehouse.warehouseId"
                        :label="warehouse.warehouseName"
                        :value="warehouse.warehouseId"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="物料编码" prop="materialCode">
                    <el-input v-model="queryParams.productCode" placeholder="请输入物料编码" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="物料名称" prop="materialName">
                    <el-input v-model="queryParams.productName" placeholder="请输入物料名称" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="品牌" prop="externalBrand">
                    <el-input v-model="queryParams.externalBrand" placeholder="请输入品牌" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="批次号" prop="batchNumber">
                    <el-input v-model="queryParams.batchNumber" placeholder="请输入批次号" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="项目" prop="projectId">
                    <el-select v-model="queryParams.projectId" placeholder="请选择项目" filterable clearable>
                      <el-option
                        v-for="item in projectInfoList"
                        :key="item.projectId"
                        :label="`${item.projectCode} - ${item.projectName}`"
                        :value="item.projectId"
                      ></el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery" :loading="loading">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
          </transition>

          <el-card shadow="hover">
            <template v-if="prop.multiple" #header>
              <el-tag
                v-for="inventory in selectInventoryList"
                :key="inventory.inventoryDetailsId"
                closable
                style="margin: 2px"
                @close="handleCloseTag(inventory)"
              >
                {{ inventory.productName }} ({{ inventory.batchNumber }})
              </el-tag>
            </template>

            <vxe-table
              ref="tableRef"
              height="400px"
              border
              show-overflow
              :data="inventoryDetailsList"
              :row-config="{ keyField: 'inventoryDetailsId', isHover: true }"
              :checkbox-config="{ reserve: true, trigger: 'row', highlight: true, showHeader: prop.multiple }"
              @checkbox-all="handleCheckboxAll"
              @checkbox-change="handleCheckboxChange"
            >
              <vxe-column type="checkbox" width="50" align="center" />
              <vxe-column key="warehouseName" title="仓库" align="center" field="warehouseName" width="220px" />
              <vxe-column key="batchNumber" title="批次号" align="center" field="batchNumber" />
              <vxe-column key="productCode" title="物料编码" align="center" field="productCode" />
              <vxe-column key="productName" title="物料名称" align="center" field="productName" />
              <vxe-column key="productSpe" title="物料描述" align="center" field="productSpe" />
              <vxe-column key="externalBrand" title="品牌" align="center" field="externalBrand" />
              <vxe-column key="inventoryAmount" title="库存数量" align="center" field="inventoryAmount" />
              <vxe-column key="lockedStock" title="锁定库存" align="center" width="100">
                <template #default="{ row }">
                  {{ row.lockedAmount || 0 }}
                </template>
              </vxe-column>
              <!--<vxe-column key="unitPrice" title="单价" align="center" field="unitPrice" />-->
            </vxe-table>

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

      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listInventoryDetails } from '@/api/wms/inventoryDetails';
import { getWmsWarehouseInfoList } from '@/api/wms/warehouseInfo';
import { InventoryDetailsQuery, InventoryDetailsVO } from '@/api/wms/inventoryDetails/types';
import { VxeTableInstance } from 'vxe-table';
import useDialog from '@/hooks/useDialog';
import { computed, getCurrentInstance, nextTick, ref, watch } from 'vue';
import { getErpProjectInfoList } from '@/api/oa/erp/projectInfo';
import { countUnOutStockDetails } from '@/api/wms/outStockDetails';

interface PropType {
  modelValue?: InventoryDetailsVO[] | InventoryDetailsVO | undefined;
  multiple?: boolean;
  data?: string | number | (string | number)[] | undefined;
  warehouseId?: string | number;
}

const prop = withDefaults(defineProps<PropType>(), {
  multiple: true,
  modelValue: undefined,
  data: undefined,
  warehouseId: undefined
});

const emit = defineEmits(['update:modelValue', 'confirmCallBack']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const inventoryDetailsList = ref<InventoryDetailsVO[]>([]);
const warehouseList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const selectInventoryList = ref<InventoryDetailsVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const tableRef = ref<VxeTableInstance<InventoryDetailsVO>>();

const inventoryDialog = useDialog({
  title: '库存选择'
});

const queryParams = ref<InventoryDetailsQuery>({
  pageNum: 1,
  pageSize: 10,
  productName: undefined,
  productCode: undefined,
  warehouseId: undefined,
  batchNumber: undefined,
  params: {}
});

const defaultSelectInventoryIds = computed(() => computedIds(prop.data));

const confirm = () => {
  emit('update:modelValue', selectInventoryList.value);
  emit('confirmCallBack', selectInventoryList.value);
  inventoryDialog.closeDialog();
};

const computedIds = (data) => {
  if (data === '' || data === null || data === undefined) {
    return [];
  }
  if (data instanceof Array) {
    return data.map((item) => String(item));
  } else if (typeof data === 'string') {
    return data.split(',');
  } else if (typeof data === 'number') {
    return [String(data)];
  } else {
    console.warn('<InventorySelect> 未支持的数据类型');
    return [];
  }
};

/** 查询库存明细列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listInventoryDetails(queryParams.value);
    inventoryDetailsList.value = res.rows;
    // 查询每个物料的锁定库存数量
    for (const item of inventoryDetailsList.value) {
      try {
        const lockRes = await countUnOutStockDetails({
          inventoryDetailsId: item.inventoryDetailsId
        });
        item.lockedAmount = lockRes.data?.outStockAmount || 0;
      } catch (error) {
        console.error('查询锁定库存失败:', error);
        item.lockedAmount = 0;
      }
    }
    total.value = res.total;
  } catch (error) {
    console.error('查询库存明细列表失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 查询仓库列表 */
const getWarehouseList = async () => {
  try {
    const res = await getWmsWarehouseInfoList();
    warehouseList.value = res.data;
  } catch (error) {
    console.error('查询仓库列表失败:', error);
  }
};

// 项目列表
const projectInfoList = ref([]);
/** 查询项目列表 */
const getProjectInfoList = async () => {
  try {
    const res = await getErpProjectInfoList(null);
    projectInfoList.value = res.data || [];
  } catch (error) {
    console.error('查询项目列表失败:', error);
  }
};
const pageList = async () => {
  await getList();
  const inventories = inventoryDetailsList.value.filter((item) => {
    return selectInventoryList.value.some((inventory) => inventory.inventoryDetailsId === item.inventoryDetailsId);
  });
  await tableRef.value?.setCheckboxRow(inventories, true);
};

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

const handleCheckboxAll = (checked) => {
  const rows = inventoryDetailsList.value;
  if (checked.checked) {
    rows.forEach((row) => {
      if (!selectInventoryList.value.some((item) => item.inventoryDetailsId === row.inventoryDetailsId)) {
        selectInventoryList.value.push(row);
      }
    });
  } else {
    selectInventoryList.value = selectInventoryList.value.filter((item) => {
      return !rows.some((row) => row.inventoryDetailsId === item.inventoryDetailsId);
    });
  }
};

const handleCloseTag = (inventory: InventoryDetailsVO) => {
  const inventoryDetailsId = inventory.inventoryDetailsId;
  const index = selectInventoryList.value.findIndex((item) => item.inventoryDetailsId === inventoryDetailsId);
  if (index > -1) {
    const row = selectInventoryList.value[index];
    tableRef.value?.setCheckboxRow(row, false);
    selectInventoryList.value.splice(index, 1);
  }
};

const initSelectInventory = async () => {
  if (defaultSelectInventoryIds.value.length > 0) {
    const inventories = inventoryDetailsList.value.filter((item) => {
      return defaultSelectInventoryIds.value.includes(String(item.inventoryDetailsId));
    });
    selectInventoryList.value = inventories;
    await nextTick(() => {
      tableRef.value?.setCheckboxRow(inventories, true);
    });
  }
};

const close = () => {
  inventoryDialog.closeDialog();
};
// ... existing code ...
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.productName = undefined;
  queryParams.value.productCode = undefined;
  // 不重置仓库ID，保留传入的筛选条件
  if (!prop.warehouseId) {
    queryParams.value.warehouseId = undefined;
  }
  queryParams.value.batchNumber = undefined;
  handleQuery();
};

const handleCheckboxChange = (checked) => {
  if (!prop.multiple && checked.checked) {
    tableRef.value?.setCheckboxRow(selectInventoryList.value, false);
    selectInventoryList.value = [];
  }
  const row = checked.row;
  if (checked.checked) {
    selectInventoryList.value.push(row);
  } else {
    selectInventoryList.value = selectInventoryList.value.filter((item) => {
      return item.inventoryDetailsId !== row.inventoryDetailsId;
    });
  }
};
// ... existing code ...

watch(
  () => inventoryDialog.visible.value,
  async (newValue: boolean) => {
    if (newValue) {
      // 重新设置仓库ID筛选条件
      if (prop.warehouseId) {
        queryParams.value.warehouseId = prop.warehouseId;
      }
      await getList();
      await getWarehouseList();
      await initSelectInventory();
      await getProjectInfoList();
    } else {
      tableRef.value?.clearCheckboxReserve();
      tableRef.value?.clearCheckboxRow();
      // 修改重置逻辑，保留传入的仓库ID
      resetQuery();
      selectInventoryList.value = [];
    }
  }
);
// ... existing code ...

defineExpose({
  open: inventoryDialog.openDialog,
  close: inventoryDialog.closeDialog
});
</script>
