<template>
  <el-drawer :visible.sync="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="选择产品" style="width: 100%;">
                <el-select v-model="queryParams.itemId" placeholder="选择产品" filterable style="width: 100%;" @change="handleChangeProduct">
                  <el-option v-for="item in useWmsStore().productList" :key="item.item.id" :label="item.item.itemName" :value="item.item.id"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格型号">
                  <el-select v-model="queryParams.skuId" placeholder="规格型号" filterable clearable style="width: 100%;">
                      <el-option v-for="item in skuItemList" :key="item.id" :label="item.skuName" :value="item.id"/>
                  </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div style="margin-top: 5px;">
                <el-button type="primary" @click="loadAll">查询</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <div class="ed_title">
          <span>产品明细</span>
          <span style="margin-left: 10px;">已选：{{ selectItemSkuVoCheck.length }}</span>
        </div>
        <div style="width: 100%;max-height: 65vh;overflow-y: auto;margin-top: 20px;">
          <el-table :data="list" @selection-change="handleSelectionChange" border :row-key="row=>row.id" empty-text="暂无产品" v-loading="loading" ref="skuSelectFormRef" cell-class-name="my-cell">
            <el-table-column type="selection" width="55" :reserve-selection="true" v-if="!singleSelect" :selectable="judgeSelectable"/>
            <el-table-column label="产品名称" prop="itemName"></el-table-column>
            <el-table-column label="规格型号" prop="skuName"> </el-table-column>
            <el-table-column label="规格单位" prop="unit"></el-table-column>
            <el-table-column label="产品编号" prop="serialnumber"></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;margin-top: 20px;">
        <span></span>
        <span>
          <el-button @click="handleCancelClick">取消</el-button>
          <el-button type="primary" @click="handleOkClick" v-if="!singleSelect">确认</el-button>
      </span>
      </div>
    </div>
  </el-drawer>
</template>
<script setup name="SkuSelect">
import {computed, getCurrentInstance, onMounted, reactive, ref} from 'vue';
import { listFinished } from "@/api/wms/product";
import {listItemSku} from "@/api/wms/itemSku";
import {useWmsStore} from '@/store_v3/modules/wms'
useWmsStore().getItemBrandList();
useWmsStore().getProductList();

const { proxy } = getCurrentInstance()

const loading = ref(false)
const selectItemSkuVoCheck = ref([])
const skuSelectFormRef = ref()
const selectNos = ref([])
const total = ref(0);
const queryParams = ref({
  page:1,
  limt:10,
  status:0,
  itemId:'',
  skuId:'',
  warehouseId: null,
});
const list = ref([]);
const skuItemList = ref([]);

const currentPage = ref(1)
const handleSizeChange = (e)=>{
  queryParams.value.limit = e;
  getList();
}
const handleCurrentChange = (e)=>{
  queryParams.value.page = e;
  getList();
}

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

const handleChangeProduct = (val) => {
    skuItemList.value = [];
    queryParams.value.skuId = '';
    if(!val) return
    listItemSku(val).then(res => {
        if(res.code!==0) return proxy?.$message.error(res.msg);
        skuItemList.value = res.data;
    })
  }

const getList = () => {
  listFinished(queryParams.value).then((res) => {
    const content = [...res.data.list];
    list.value = content.map((it) => ({...it, id: it.id, checked: false}));
    total.value = res.data.total;
  }).then(()=>{toggleSelection()}).finally(() => loading.value = false);
}

// 定义props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  size: {
    type: String,
    default: '30%'
  },
  singleSelect:{
    type: Boolean,
    default: false
  },
  selectedSku: {
    type: Array,
    default: []
  }
})

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

// 定义事件
const emit= defineEmits(['handleCancelClick', 'handleOkClick','handleSingleOkClick'])

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

function handleChooseSku(row) {
  emit('handleSingleOkClick', row);
}

function handleOkClick() {
  emit('handleOkClick', selectItemSkuVoCheck.value);
  clearQuantity()
}
/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  selectItemSkuVoCheck.value = selection
}

const toggleSelection = () => {
  list.value.forEach((l,i)=>{
    if (selectNos.value.includes(l.serialnumber)) {
      skuSelectFormRef.value.toggleRowSelection(list.value[i], true)
    } 
  })
}

const judgeSelectable = (row) => {
  if (selectNos.value.find(selected => selected === row.serialnumber)) {
    return false;
  }
  return true
}

function clearQuantity() {
  skuSelectFormRef.value.clearSelection()
}

const setWarehouseId = (warehouseId = null) => {
  queryParams.value.warehouseId = warehouseId
}
defineExpose({
  getList,
  toggleSelection,
  setWarehouseId,
  selectNos
})
</script>
<style lang="scss">
.el-table .my-cell {
  vertical-align: top
}
</style>
<style scoped lang="scss">
::v-deep .el-drawer__wrapper .el-drawer__body{
  overflow-y: auto !important;
}

.ed_title{
  margin-top: 40px;
  display: flex;
  align-items: center;
  span{
    font-family: PingFang-SC, PingFang-SC;
    font-weight: bold;
    font-size: 14px;
    color: #1D2129;
    line-height: 20px;
  }
}
</style>

