<template>
    <q-dialog v-model="openDialog" persistent :maximized="maximizedToggle" 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>收货确认</div>
                    <q-space />
                    <q-btn dense flat round icon="close" @click="openDialog = false" />
                </q-bar>
                <q-card-section>
                    <div class="row q-col-gutter-md items-center">
                        <!-- <div class="col-xl-5 col-lg-5 col-xs-5">
                            <q-btn-toggle size="16px" v-model="switchFlag" toggle-color="primary" rounded glossy push
                                color="white" text-color="primary" :options="[
                                    { label: '待拣', value: false },
                                    { label: '全部', value: true },
                                ]
                                    " />
                        </div> -->
                        <!-- <div class="col-xl-7 col-lg-7 col-xs-7">
                            <q-input outlined v-model="asnRowSearch.keyword" label="关键字搜索" class="text-h6" clearable>
                                <template v-slot:after>
                                    <q-btn glossy push rounded size="lg" color="primary" icon="search"
                                        @click="getListByKeyword" />
                                </template>
                            </q-input>
                        </div> -->
                        <div class="col-xl-4 col-lg-4 col-xs-12">
                            <q-select class="text-h6" v-show="!displayFlag" :readonly="overReceivingFlag"
                                :disable="overReceivingFlag" outlined clearable v-model="asnRowSearch.storagePartitionId"
                                :options="storageList" option-label="storageName" option-value="id" emit-value map-options
                                label="库存地点" bottom-slots @update:model-value="storagePartitionUpdate">
                                <template v-slot:hint>
                                    <span style="color:red;">[ 可选项 ]：待收货列表批量设置为相同的库存地点</span>
                                </template>
                            </q-select>
                        </div>
                    </div>
                </q-card-section>
            </q-card-section>

            <q-separator />

            <q-card-section :style="{ height: Screen.height - 195 + 'px' }" class="scroll">
                <q-form ref="myForm">
                    <div v-for="(item, index) in formData.asnRowReceivingVOList" :key="index">
                        <q-card-section v-show="switchFlag || Number(item.checkCount) > 0"
                            class="q-mb-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-card-actions>
                                <div class="row q-col-gutter-md">
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-xs-12">
                                        <q-input class="text-h6" disable readonly standout label="订单号"
                                            v-model="item.orderCode" />
                                    </div>
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-xs-12">
                                        <q-input class="text-h6" disable readonly standout label="项目号"
                                            v-model="item.projectCode" />
                                    </div>
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-xs-12">
                                        <q-input class="text-h6" disable readonly standout label="物料名称"
                                            v-model="item.materialName" />
                                    </div>
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-xs-12">
                                        <q-input class="text-h6" disable readonly standout label="物料编码"
                                            v-model="item.materialCode" />
                                    </div>
                                    <!-- <div class="col-xl-6 col-lg-6 col-md-6 col-xs-12">
                                        <q-input class="text-h6" disable readonly standout label="规格型号"
                                            v-model="item.specsName" />
                                    </div> -->
                                    <!-- <div class="col-xl-6 col-lg-6 col-md-6 col-xs-12">
                                        <q-input class="text-h6" disable readonly standout label="总数量"
                                            v-model="item.totalCount" />
                                    </div> -->
                                    <div class="col-6">
                                        <q-input class="text-h6" disable readonly standout v-model="item.receivingCount"
                                            label="待收货数量"></q-input>
                                    </div>
                                    <div class="col-6">
                                        <q-input class="text-h6" disable readonly standout v-model="item.receivedCount"
                                            label="已收货数量"></q-input>
                                    </div>
                                    <div class="col-xl-12 col-lg-12 col-xs-12">
                                        <q-select class="text-h6" :outlined="item.receivedCount <= '0'"
                                            :standout="item.receivedCount > '0'" clearable v-model="item.storagePartitionId"
                                            :options="storageList" option-label="storageName" option-value="id"
                                            :disable="item.receivedCount > '0'"
                                            :readonly="item.receivedCount > '0' || displayFlag" emit-value map-options
                                            label="所属库存地点" :rules="item.receivingCount === '0' || item.receivedCount > '0' ? [] : [
                                                (val) => (val && val.length > 0) || '请选择所属库存地点',
                                            ]">
                                        </q-select>
                                    </div>
                                    <!-- standout="bg-white text-white" -->
                                    <!-- <div class="col-12" v-show="Number(item.checkCount) !== 0">
                                        <q-input class="text-h6" type="number" outlined
                                            :bg-color="Number(item.checkCount) > 0 ? 'white' : ''"
                                            :disable="Number(item.checkCount) == 0" v-model="item.receivingCount"
                                            :rules="[(val: number) => val >= 0 || '收货数量不能小于0', (val: number) => val <= Number(item.checkCount) || '收货数量不能大于待拣数量']"
                                            label="当前收货数量" @update:model-value="checkCountUpdate">
                                            <template v-slot:append>
                                                <h6 class=" text-primary">
                                                    {{ '待拣数量：' + item.checkCount }}
                                                </h6>
                                            </template>
                                        </q-input>
                                    </div> -->
                                </div>
                            </q-card-actions>
                        </q-card-section>
                    </div>
                </q-form>
            </q-card-section>

            <q-separator />

            <q-card-actions align="right">
                <q-btn glossy push rounded color="white" text-color="black" class="q-mr-xs" @click="openDialog = false">{{
                    $t('cancel')
                }}</q-btn>
                <q-btn glossy push rounded color="primary" v-if="!overReceivingFlag" @click="submitForm()">{{ $t('submit')
                }}</q-btn>
                <q-btn glossy push rounded color="positive" v-if="overReceivingFlag"
                    @click="overReceivingForm()">完成收货</q-btn>
            </q-card-actions>
        </q-card>
    </q-dialog>
</template>

<script setup lang="ts">
import { Loading, Dialog, Notify, QSpinnerRadio, QSpinnerHourglass } from 'quasar';
import { asnApi } from 'src/api/inbound/asnApi';
import { storageApi } from 'src/api/storage/storageApi'
import { AsnReceiptEntity } from 'src/api/inbound/model/asn';
import { Screen } from 'quasar'
import { ref } from 'vue';

const formData = ref(new AsnReceiptEntity());

const emit = defineEmits(['refresh'])

// 库存地点集合
const displayFlag = ref(false);
const storageList = ref([]);
const maximizedToggle = ref(true)
const openDialog = ref(false);
const switchFlag = ref(false);
const overReceivingFlag = ref(false);
const asnRowSearch = ref({
    asnId: '',
    keyword: '',
    storagePartitionId: ''
})

const clearFormData = () => {
    formData;
    asnRowSearch.value.keyword = ''
};

// 库存地点设置
const storagePartitionUpdate = (val: any) => {
    if (val) {
        formData.value.asnRowReceivingVOList.forEach((item: any) => {
            item.storagePartitionId = val
        })
    }
}

const getListByKeyword = () => {
    asnApi.getListByKeyword(asnRowSearch.value).then((res: any) => {
        res.forEach((item: any) => {
            item.asnRowId = item.id;
            item.checkCount = item.totalCount - item.receivedCount;
            item.receivingCount = item.totalCount - item.receivedCount; // 当此收货数量
        });
        formData.value.asnRowReceivingVOList = res;
        const result = res.filter((item: any) => { return item.checkCount == 0 }).length >= res.length
        switchFlag.value = result
        overReceivingFlag.value = result
        formData.value.asnId = asnRowSearch.value.asnId; // 入库单ID
        // formData.value.orderCode = e.orderCode;
        // formData.value.projectCode = e.projectCode;
        formData.value.warehouseId = res.warehouseId;
        formData.value.warehouseName = res.warehouseName;
    });
}

const clickForm = (e?: any) => {
    asnRowSearch.value.asnId = e.id
    if (e.asnType == 2) {
        // 判断是否为 生产订单 不可选择库存地点
        displayFlag.value = true;
    }
    clearFormData();
    if (e.state !== 1 && e.state !== 2) {
        Notify.create({
            message: '非待收货入库单不可执行收货操作',
            icon: 'close',
            color: 'negative',
        });
        return
    }
    storageApi.getStorageList({ 'warehouseId': e.warehouseId }).then((res: any) => {
        storageList.value = res;
        getListByKeyword()
    });
    openDialog.value = true;
};

// 提交收货
const myForm = ref();
const submitForm = () => {
    myForm.value.resetValidation();
    myForm.value.validate().then((success: any) => {
        if (success) {
            Loading.show({
                spinner: QSpinnerHourglass,
                message: '收货中，请稍等...',
                boxClass: 'bg-grey-2 text-grey-9',
                spinnerColor: 'primary'
            });
            asnApi.receiving(formData.value).then(() => {
                openDialog.value = false;
                emit('refresh');
            }).finally(() => {
                Loading.hide();
            });
        }
    })
};

const checkCountUpdate = (val: any) => {
    if (val <= 0) {
        myForm.value.resetValidation();
    }
}

const overReceivingForm = (e?: any) => {
    Dialog.create({
        title: '系统提示',
        message: '是否通知SAP完成收货？',
        class: 'text-h7 text-weight-bold',
        cancel: true,
        persistent: true
    }).onOk(() => {
        Loading.show({
            spinner: QSpinnerRadio,
            message: '正在通知SAP完成收货，请稍等...',
            boxClass: 'bg-grey-2 text-grey-9',
            spinnerColor: 'primary'
        });
        asnApi.overReceiving(Number(formData.value.asnId)).then(() => {
            openDialog.value = false
            emit('refresh');
        }).finally(() => {
            Loading.hide();
        });
    }).onCancel(() => { })
}

defineExpose({
    clickForm
})
</script>