<template>
    <Navbar title="领料车" :is-go-back="false">
        <a-space>
            <div @click="goToHome()" style="cursor: pointer;">
                <HomeOutlined style="font-size: 26px;" />
            </div>
        </a-space>
    </Navbar>

    <a-form :colon="false">
        <a-row :gutter="[8, 0]" justify="space-start">

            <a-col>
                <a-form-item label="选择仓库" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
                    <a-select v-model:value="warehouseId" placeholder="选择仓库" class="w-full" allow-clear
                        @change="getDatas">
                        <a-select-option v-for="item in warehouseList" :key="item.id" :value="item.id">
                            {{ item.name }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
            </a-col>
            <a-col>
                <a-form-item label="设备名称" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
                    <a-input v-model:value="inventoryName" placeholder="设备名称" class="w-full" @keyup.enter="getDatas" />
                </a-form-item>
            </a-col>
            <a-col>
                <a-form-item label="设备编码" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
                    <a-input v-model:value="inventoryNo" placeholder="设备编码" class="w-full" @keyup.enter="getDatas" />
                </a-form-item>
            </a-col>
            <a-col>
                <a-form-item label="设备型号" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
                    <a-select v-model:value="inventoryType" placeholder="设备型号" class="w-full" allow-clear
                        :options="inventoryTypeList" @change="getDatas">
                    </a-select>
                </a-form-item>
            </a-col>
            <a-col>
                <a-form-item>
                    <a-space>
                        <a-button style="margin-left: 12px;" type="primary" @click="getDatas">查询</a-button>
                        <a-button style="background: #269745;color: #fff;" @click="submitStock">领料</a-button>
                        <a-button danger @click="deleteStock">删除</a-button>
                    </a-space>
                </a-form-item>
            </a-col>
        </a-row>
    </a-form>
    <CommonTable ref="carTableRef" :extra-height="70" :columns="inventoryList" :data-source="carList"
        :total="pagination.total" :is-select="true"  @get-pager="getPageParams" @get-selected="getSelectParams">
    </CommonTable>
    <Loading v-if="loading" />
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import Common from '../common/Common.js';
import CommonTable from '../common/CommonTable.vue';
import { HomeOutlined } from '@ant-design/icons-vue';
import { carColumns, typeList } from './columns.js';
import { useRouter } from 'vue-router';

const router = useRouter();
const carTableRef = ref(null);
const userId = ref(undefined);
const warehouseId = ref(undefined);
const inventoryName = ref('');
const inventoryNo = ref('');
const inventoryType = ref(undefined);
const warehouseList = ref([]);
const carList = ref([]);
const selectedIds = ref([]);
const loading = ref(false);
const inventoryList = ref(carColumns);
const inventoryTypeList = ref(typeList);
const pagination = ref({
    total: 0,
    start: 1,
    lang: 20,
});

// 返回领料
const goToHome = () => {
    router.push('/wms/stock-requisition');
}

// 获取分页参数
const getPageParams = (page, pageSize) => {
    pagination.value.start = page;
    pagination.value.lang = pageSize;
    getPickerCarList();
}

// 获取选中的物料ID
const getSelectParams = (selected) => {
    selectedIds.value = selected.selectedRowKeys;
}

// 从领料车里删除工装设备
const deleteStock = () => {
    if (selectedIds.value.length == 0) {
        message.warning('请至少选择一个工装设备');
        return;
    }
    Modal.confirm({
        title: '确认将工装设备从领料车中删除吗?',
        content: '确认的话请点击【确认】按钮，否则请点击【取消】按钮',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
            deleteStockCarApi();
        },
        onCancel() {
            console.log('Cancel');
        },
    });

}

// 查询物料数据
const getPickerCarList = () => {
    loading.value = true;
    const loginInfo = localStorage.getItem('#LoginInfo');
    if (loginInfo) {
        const loginInfoObj = JSON.parse(loginInfo);
        userId.value = loginInfoObj.userId;
    }
    const params = {
        inventoryName: inventoryName.value,
        inventoryNo: inventoryNo.value,
        inventoryType: inventoryType.value,
        warehouseId: warehouseId.value,
        userId: userId.value,
        start: (pagination.value.start - 1) * pagination.value.lang,
        length: pagination.value.lang,
    };
    $.ajax({
        url: Common.getApiURL('PickingCarResource/queryCFPickCar'),
        type: 'post',
        contentType: 'application/json',

        dataType: 'json',
        data: JSON.stringify(params),
        beforeSend: function (request) {
            Common.addTokenToRequest(request);
        },
        success: function (successData) {

            if (successData.errorCode == 0) {
                if (successData.datas && successData.datas.length > 0) {
                    carList.value = successData.datas;
                } else {
                    carList.value = [];
                }
                pagination.value.total = successData.total;
            }
            loading.value = false;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            Common.processException(XMLHttpRequest, textStatus, errorThrown);
            loading.value = false;
        },
    });
}

//  删除接口
const deleteStockCarApi = () => {
    loading.value = true;
    const params = {
        pickingCarIds: selectedIds.value,
    }
    $.ajax({
        url: Common.getApiURL('PickingCarResource/deleteCFPickCar'),
        type: 'post',
        contentType: 'application/json',

        dataType: 'json',
        data: JSON.stringify(params),
        beforeSend: function (request) {
            Common.addTokenToRequest(request);
        },
        success: function (successData) {
            if (successData.errorCode == 0) {
                message.success('工装设备从领料车中删除成功');
                carTableRef.value.clear();
                getDatas();
            } else {
                message.warning(successData.errorMessage);
            }
            loading.value = false;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            Common.processException(XMLHttpRequest, textStatus, errorThrown);
            loading.value = false;
        },
    });
}
// 获取仓库列表
const getWarehouseList = () => {
    $.ajax({
        type: 'get',
        dataType: 'json',
        url: Common.getApiURL('WarehouseResource/queryByCondition'),
        contentType: 'application/json',
        beforeSend: function (request) {
            Common.addTokenToRequest(request);
        },
        success: function ({ datas, errorCode, errorMessage }) {
            if (errorCode == 0) {
                if (datas && datas.length > 0) {
                    warehouseList.value = datas;
                } else {
                    warehouseList.value = [];
                }
            } else {
                message.warning(errorMessage);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
    });
}

// 查询回到第一页
const getDatas = () => {
    carTableRef.value.backFirstPage();
}

// 领料
const submitStock = () => {
    if (selectedIds.value.length == 0) {
        message.warning('请至少选择一个工装设备');
        return;
    }
    loading.value = true;
    const params = {
        pickingCarIds: selectedIds.value,
    }
    $.ajax({
        url: Common.getApiURL('StockOutPrepareResource/saveCFStockOutPrepare'),
        type: 'post',
        contentType: 'application/json',

        dataType: 'json',
        data: JSON.stringify(params),
        beforeSend: function (request) {
            Common.addTokenToRequest(request);
        },
        success: function (successData) {

            if (successData.errorCode == 0) {
                getDatas();
                message.success('领料单生成成功，请前往闸机进行领料登记等相关操作');
            }
            loading.value = false;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            Common.processException(XMLHttpRequest, textStatus, errorThrown);
            loading.value = false;
        },
    });
}
onMounted(() => {
    getDatas();
    getWarehouseList();
})
</script>

<style scoped>
.horizontal-form-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.w-full {
    width: 192px;
}

:deep(.ant-form-item) {
    margin-bottom: 10px !important;
}

:deep(.ant-form-item-label > label) {
    font-size: 14px !important;
    font-weight: 600 !important;
}
</style>