<template>
    <q-dialog v-model="visble" persistent :maximized="true" transition-show="slide-up" transition-hide="slide-down">
        <q-card>
            <q-card-section class="no-padding">
                <q-bar class="bg-primary text-white glossy">
                    <div>【{{ materialName }}】库存</div>
                    <q-space />
                    <q-btn dense flat round icon="close" @click="visble = false" />
                </q-bar>
                <q-card-section>
                    <div class="row q-col-gutter-md">
                        <!-- <div class="col-xl-3 col-lg-3 col-xs-12">
                        <q-select class="text-h6" outlined use-input clearable v-model="pagination.data.areaId"
                            :options="filterOption['areaList']" @filter="filterFunction['areaListJoin']"
                            @update:model-value="filterUpdate['binListJoin']" :option-label="filterLabel['areaList']"
                            :option-value="filterValue['areaList']" emit-value map-options label="所属库区" />
                    </div> -->
                        <div class="col-sm-12">
                            <q-input outlined label="扫描库位" v-model="pagination.data.binId" class="text-h6" autofocus
                                clearable @input="getPage" @clear="getPage" ref="inputFoucs">
                                <template v-slot:after>
                                    <q-btn glossy push rounded size="lg" color="primary" icon="search" @click="getPage()" />
                                </template>
                            </q-input>
                            <!-- <q-select class="text-h6" outlined use-input clearable v-model="pagination.data.binId"
                            :options="filterOption['binList']" @filter="filterFunction['binListJoin']"
                            :option-label="filterLabel['binList']" :option-value="filterValue['binList']" emit-value
                            map-options label="所属库位">
                            <template v-slot:after>
                                <q-btn push rounded glossy size="lg" color="primary" icon="search" @click="query" />
                            </template>
                        </q-select> -->
                        </div>

                        <!-- <div class="col-xl-3 col-lg-3 col-sm-12">
                        <q-btn push label="查询" color="primary" icon="search" size="20px" @click="query">
                            <q-tooltip content-class="bg-amber text-black shadow-4">查询物料</q-tooltip>
                        </q-btn>
                        <q-btn push label="重置" color="primary" class="q-ml-md" icon="youtube_searched_for" size="20px"
                            @click="reset">
                            <q-tooltip content-class="bg-amber text-black shadow-4">重置</q-tooltip>
                        </q-btn>
                    </div> -->
                    </div>
                </q-card-section>
            </q-card-section>
            <q-separator />
            <q-card-section :style="{ height: Screen.height - 175 + 'px', padding: '0px' }">
                <!-- 内容 滚动部分 -->
                <q-scroll-area ref="scrollRef" :thumb-style="thumbStyle" :bar-style="barStyle" @scroll="onScroll"
                    :style="{ height: Screen.height - 175 + 'px' }">
                    <div v-for="(item, index) in tableData" :key="index" style="padding:16px 16px 0 16px;">
                        <q-item tag="label" v-ripple class="q-mb-md q-pa-md shadow-6 shadow-box">
                            <div class="absolute-top-right">
                                <q-badge color="grey-5" rounded floating style="
                                        font-size: 1.2rem;
                                        font-weight: 500;
                                        line-height: 1.2rem;
                                        letter-spacing: 0.0125em;
                                        z-index:99;
                                    ">
                                    {{ index + 1 }}
                                </q-badge>
                            </div>
                            <q-item-section avatar>
                                <q-checkbox v-model="checked" :val="item.id" color="primary"
                                    @update:model-value="(value) => { onUpdate(value, item) }" />
                            </q-item-section>
                            <div class="row q-col-gutter-xs items-center">
                                <q-item-actions style="border-bottom:1px solid #b4b4b4;"
                                    class="col-xl-6 col-lg-6 col-md-6 col-xs-12 text-h6 text-weight-bold q-pb-sm q-pt-sm">
                                    <q-item-label>可用库存</q-item-label>
                                    <q-item-label class="text-h5">
                                        {{ item.count }} {{ item.unit }}
                                    </q-item-label>
                                </q-item-actions>
                                <!-- <q-item-actions style="border-bottom:1px solid #b4b4b4;"
                                    class="col-xl-6 col-lg-6 col-md-6 col-xs-12 text-h6 text-weight-bold q-pb-sm q-pt-sm">
                                    <q-item-label>库区</q-item-label>
                                    <q-item-label class="text-h5">
                                        {{ item.areaName == null ? 'N/A' : item.areaName }}
                                    </q-item-label>
                                </q-item-actions> -->
                                <q-item-actions style="border-bottom:1px solid #b4b4b4;"
                                    class="col-xl-6 col-lg-6 col-md-6 col-xs-12 text-h6 text-weight-bold q-pb-sm q-pt-sm">
                                    <q-item-label>库位</q-item-label>
                                    <q-item-label class="text-h5">
                                        {{ item.binName == null ? 'N/A' : item.binName }}
                                    </q-item-label>
                                </q-item-actions>
                                <q-item-actions style="border-bottom:1px solid #b4b4b4;"
                                    class="col-xl-6 col-lg-6 col-md-6 col-xs-12 text-h6 text-weight-bold q-pb-sm q-pt-sm">
                                    <q-item-label>物料名称</q-item-label>
                                    <q-item-label class="text-h5">
                                        {{ item.materialName }}
                                    </q-item-label>
                                </q-item-actions>
                                <q-item-actions style="border-bottom:1px solid #b4b4b4;"
                                    class="col-xl-6 col-lg-6 col-md-6 col-xs-12 text-h6 text-weight-bold q-pb-sm q-pt-sm">
                                    <q-item-label>规格型号</q-item-label>
                                    <q-item-label class="text-h5">
                                        {{ item.specsName }}
                                    </q-item-label>
                                </q-item-actions>
                                <q-item-actions
                                    class="col-xl-6 col-lg-6 col-md-6 col-xs-12 text-h6 text-weight-bold q-pt-sm">
                                    <q-item-label>物料编码</q-item-label>
                                    <q-item-label class="text-h5">
                                        {{ item.materialCode }}
                                    </q-item-label>
                                </q-item-actions>
                            </div>
                        </q-item>
                    </div>
                    <div class="row justify-center q-my-md" v-show="loadingFlag">
                        <q-spinner-dots color="primary" size="40px" />
                    </div>
                </q-scroll-area>
            </q-card-section>
            <q-separator />
            <q-card-actions>
                已选总数：<span :style="{ color: totalCount > 0 ? 'green' : 'red', fontWeight: 'bold' }">{{ totalCount }}</span>
                <q-space />
                <q-btn glossy push rounded color="white" text-color="black" @click="visble = false" class="q-mr-xs">{{
                    $t('cancel')
                }}</q-btn>
                <q-btn glossy push rounded color="primary" @click="stockMaterialSelected()">确认选择</q-btn>
            </q-card-actions>
        </q-card>
    </q-dialog>
</template>
<script setup lang="ts">
import { nextTick, ref } from 'vue';
// import {
//     filterFunction,
//     filterOption,
//     filterLabel,
//     filterValue,
//     filterUpdate,
// } from 'src/Utils/filterUtils';
import { Screen } from 'quasar'
import { Pagination, convert } from 'src/api/class';
import { stockApi } from 'src/api/stock/stockApi';
import { StockMaterialViewSearchEntity } from 'src/api/stock/model/stock';
const emit = defineEmits(['stockMaterialSelected']);

const checked = ref([]) // 选中的物料集合 ID
const stockMaterialList: any = ref([]) // 选中的物料集合 {id,count}
const thumbStyle = {
    right: '4px',
    borderRadius: '5px',
    width: '5px'
}
const barStyle = {
    right: '2px',
    borderRadius: '9px',
    width: '9px'
}
let tableData = ref([{}]);
const materialName = ref();
const rowIndx = ref();
const totalCount = ref(0); // 当前选择的下架总数

const visble = ref(false);
const loadingFlag = ref(false)
const pagination = ref(new Pagination(new StockMaterialViewSearchEntity()));
pagination.value.rowsPerPage = 10

const scrollRef = ref()
const getPage = (callback?: VoidCallback) => {
    // // 滚动栏置顶 防止连续请求接口
    // nextTick(() => {
    //     scrollRef.value.setScrollPercentage('vertical', 0, 0);
    // })
    pagination.value.page = 1
    loadingFlag.value = true;
    stockApi.getStockMaterialPage(pagination.value).then((res) => {
        convert(pagination.value, res);
        tableData.value = res.dataList;
        loadingFlag.value = false;
        callback ? callback() : ''
    });
};

// 上拉搜索 下一页
const onScroll = ({ verticalPercentage }) => {
    if (verticalPercentage === 1 && pagination.value.rowsNumber > tableData.value.length) {
        loadingFlag.value = true
        pagination.value.page = pagination.value.page + 1
        stockApi
            .getStockMaterialPage(pagination.value)
            .then((res) => {
                loadingFlag.value = false
                convert(pagination.value, res);
                tableData.value = tableData.value.concat(res.dataList);
            });
    }
}

// 确认选择 返回库存选择
const stockMaterialSelected = () => {
    emit('stockMaterialSelected', checked.value, totalCount.value, rowIndx.value, stockMaterialList.value);
    visble.value = false;
};

// 触发查询当前物料的库存
const queryMaterial = (row: any, rowIndex: any) => {
    clearSelected();
    stockMaterialList.value = row?.stockMaterialList ?? []; // 当前选中的集合包含 { id, count }
    totalCount.value = row.count ?? 0 // 已选数量
    materialName.value = row.materialName;
    pagination.value.data.warehouseId = row.warehouseId;
    pagination.value.data.materialId = row.materialId;
    pagination.value.data.dnId = row.dnId;
    rowIndx.value = rowIndex; // 当前asnRow被点击的索引
    getPage(() => {
        checked.value = row?.checkedList ?? []; // 已选的ID集合
    });
    visble.value = true; // 打开模态窗
};

let checkList: any = []
// 计算已选数量
const onUpdate = (checkeds: any, row: any) => {
    checkList.push({ id: row.id, count: row.count })
    checkList = filter(checkList)
    stockMaterialList.value = []
    // 汇总选中的物料总数
    let collect = 0
    for (let i = 0; i < checkeds.length; i++) {
        for (let j = 0; j < checkList.length; j++) {
            if (checkList[j].id !== checkeds[i]) {
                continue
            }
            stockMaterialList.value.push(checkList[j])
            collect += checkList[j].count
        }
    }
    totalCount.value = collect
};

// 数组去重
const filter = (arr: any) => {
    let list: any = []
    return arr.filter((item: any) => !list.includes(item.id) && list.push(item.id))
}

const clearSelected = () => {
    totalCount.value = 0;
    checked.value = [];
};

// const reset = () => {
//     pagination.value.data.areaId = '';
//     pagination.value.data.binId = '';
//     getPage();
// };
defineExpose({
    queryMaterial
});
</script>