<template>
  <el-drawer :visible.async="show" title="选择库存" @close="handleCancelClick" :size="size" :close-on-click-modal="false" append-to-body>
    <div style="width: 90%;margin: 0 auto;">
      <el-form label-width="68px">
        <el-row gutter="20">
          <el-col :span="8">
            <el-form-item label="产品名称">
              <el-input v-model="query.itemName" clearable placeholder="产品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格名称">
              <el-input class="w200" v-model="query.skuName" clearable placeholder="规格名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="loadAll">查询</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="width: 100%;height: 65vh;overflow-y: auto;">
        <el-table :data="list" @selection-change="handleSelectionChange" border :row-key="row=>row.id" empty-text="暂无库存"
                  v-loading="loading" ref="inventorySelectFormRef" cell-class-name="my-cell" class="mt20">
          <el-table-column type="selection" width="55" :reserve-selection="true" :selectable="judgeSelectable"/>
          <el-table-column label="产品信息" prop="itemId">
            <template #default="{ row }">
              <div>{{ row.item.itemName }}</div>
              <div v-if="row.item.itemCode">编号：{{ row.item.itemCode }}</div>
              <div v-if="row.item.itemBrand">品牌：{{ useWmsStore().itemBrandMap.get(row.item.itemBrand).brandName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="规格信息">
            <template #default="{ row }">
              <div>{{ row.itemSku.skuName }}</div>
              <div v-if="row.itemSku.skuCode">编号：{{ row.itemSku.skuCode }}</div>
              <div v-if="row.itemSku.barcode">条码：{{ row.itemSku.barcode }}</div>
            </template>
          </el-table-column>
          <el-table-column label="规格单位">
            <template #default="{ row }">
              <div>{{ row.itemSku.unit }}</div>
            </template>
          </el-table-column>
            <el-table-column label="价格(元)">
              <template #default="{ row }">
                <div v-if="row.itemSku.costPrice" class="flex-space-between">
                  <span>成本价：</span>
                  <div>{{ (row.itemSku.costPrice || row.itemSku.costPrice === 0) ? row.itemSku.costPrice : '' }}</div>
                </div>
                <div v-if="row.itemSku.sellingPrice" class="flex-space-between">
                  <span>销售价：</span>
                  <div>{{ (row.itemSku.sellingPrice || row.itemSku.sellingPrice === 0) ? row.itemSku.sellingPrice : '' }}</div>
                </div>
              </template>
            </el-table-column>
          <el-table-column label="剩余库存" prop="quantity">
            <template #default="{ row }">
              <el-statistic :value="Number(row.quantity)" :precision="0"/>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-row>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-show="total > 0">
        </el-pagination>
      </el-row>
      <div style="width: 100%;display: flex;justify-content: space-between">
          <span>
          </span>
          <span>
            <el-button @click="handleCancelClick">取消</el-button>
            <el-button type="primary" @click="handleOkClick">确认</el-button>
        </span>
      </div>
    </div>
  </el-drawer>
</template>
<script setup name="InventorySelect">
import {computed, onMounted, reactive, ref} from 'vue';
import {useWmsStore} from '@/store_v3/modules/wms'
import {listInventory} from "@/api/wms/inventory";
import {getWarehouseAndSkuKey} from "@/utils/wmsUtil";
useWmsStore().getItemBrandList();

const loading = ref(false)
const query = reactive({
  itemName: '',
  itemCode: '',
  skuName: '',
  skuCode: '',
  minQuantity: 1,
  areaId: null,
  warehouseId: null,
  projectId: null
});
const selectInventoryVoCheck = ref([])
const inventorySelectFormRef = ref()
const total = ref(0);
const pageReq = reactive({
  page: 1,
  size: 10,
});
const list = ref([]);
const rightList = ref([]);
const rightListKeySet = computed(() => {
  const set = new Set();
  rightList.value.forEach((it) => set.add(it.id));
  return set
});

const currentPage = ref(1)
const handleSizeChange = (e)=>{
  pageReq.size = e;
  getList();
}
const handleCurrentChange = (e)=>{
  pageReq.page = e;
  getList();
}

const loadAll = () => {
  pageReq.page = 1
  getList()
};

const getList = () => {
  const data = {
    ...query,
    page: pageReq.page,
    limit: pageReq.size
  }
  loading.value = true
  listInventory(data).then((res) => {
    const content = [...res.data.list];
    list.value = content.map((item) => (
      {
        ...item,
        warehouseName: useWmsStore().warehouseMap.get(item.warehouseId)?.warehouseName
      }
    ));
    total.value = res.data.total;
  }).then(() => toggleSelection()).finally(() => loading.value = false);
}

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  size: {
    type: String,
    default: '30%'
  },
  selectedInventory: {
    type: Array,
    default: []
  }
})

const show = computed(() => {
  return props.modelValue;
})

const emit = defineEmits(["handleCancelClick", 'handleOkClick']);

function handleCancelClick() {
  emit('handleCancelClick');
  clearSelected()
}

function handleOkClick() {
  emit('handleOkClick', selectInventoryVoCheck.value);
  clearSelected()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  selectInventoryVoCheck.value = selection
}

const toggleSelection = () => {
  props.selectedInventory.forEach(selected => {
    const index = list.value.findIndex(it => getWarehouseAndSkuKey(selected) === getWarehouseAndSkuKey(it))
    if (index !== -1) {
      if(inventorySelectFormRef.value?.toggleRowSelection)
        inventorySelectFormRef.value.toggleRowSelection(list.value[index], true)
    }
  })
}

function clearSelected() {
  inventorySelectFormRef.value.clearSelection()
}

const judgeSelectable = (row) => {
  if (props.selectedInventory.find(selected => getWarehouseAndSkuKey(selected) === getWarehouseAndSkuKey(row))) {
    return false;
  }
  return true
}

const setWarehouseId = (warehouseId = null) => {
  query.warehouseId = warehouseId
}
const setProjectId = (projectId = null) => {
  query.projectId = projectId
}

defineExpose({
  setWarehouseId,
  setProjectId,
  getList
})
onMounted(() => {
  loadAll();
})
</script>
<style lang="scss">
.el-table .my-cell {
  vertical-align: top
}

.el-statistic__content {
  font-size: 14px;
}
</style>
<style scoped lang="scss">
::v-deep .el-drawer__wrapper .el-drawer__body{
  overflow-y: auto !important;
}
</style>

