<template>
    <el-config-provider :locale="zhCn">
        <el-container class="content">
            <fieldset class="input-area">
                <legend style="font-size: 25px;">入库界面</legend>
                <el-form ref="taskInRequestRef" :model="taskInRequestEntity" :label-position="labelPosition"
                    label-width="100px" style="max-width: 100%" :rules="rules" status-icon>
                    <el-row>
                        <el-col :span="22" :offset="1">
                            <el-form-item label="是否入空托" prop="isEmpty">
                                <el-select-v2 v-model="taskInRequestEntity.isEmpty" placeholder="请选择入库类型"
                                    :options="stockTypeOptions"
                                    @change="autoCompleteEmptyInfo(taskInRequestEntity)"></el-select-v2>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="22" :offset="1">
                            <el-form-item label="箱号" prop="vehicleNo">
                                <el-input v-model="taskInRequestEntity.vehicleNo" ref="vehicleNo" clearable
                                    v-on:keyup.tab="detectEndInputVehicleNo(taskInRequestEntity)" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="22" :offset="1">
                            <el-form-item label="零件号" prop="goodsId">
                                <el-input v-model="taskInRequestEntity.goodsId" ref="goodsId" clearable
                                    :disabled="disabledEmpty" @blur="queryAndAutoComplete(taskInRequestEntity)" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="22" :offset="1">
                            <el-form-item label="零件名称" prop="goodsName">
                                <el-input v-model="taskInRequestEntity.goodsName" clearable :disabled="disabledEmpty" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="22" :offset="1">
                            <el-form-item label="零件数量" prop="goodsNum">
                                <el-input-number v-model.number="taskInRequestEntity.goodsNum" ref="goodsNum" clearable
                                    :disabled="disabledEmpty" controls-position="right" :min="1"
                                    @blur="detectEndInputNum(taskInRequestEntity)"></el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="22" :offset="1">
                            <el-form-item label="零件重量（千克）" prop="weight">
                                <el-input v-model="taskInRequestEntity.weight" clearable :disabled="disabledEmpty" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="22" :offset="1" v-show="disPlayDateFlag">
                            <el-form-item label="有效期（年）" prop="shelfLife">
                                <!-- // TODO 日期 -->
                                <el-input v-model="taskInRequestEntity.shelfLife" clearable :disabled="disabledEmpty" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="22" :offset="1" v-show="disPlayDateFlag">
                            <el-form-item label="生产日期" prop="productionDate">
                                <el-date-picker v-model="taskInRequestEntity.productionDate" ref="productionDate"
                                    :disabled="disabledEmpty" style="width: 100%;height: 75px;" type="date"
                                    placeholder="请选择生产日期" :editable="false" size="large" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="11" :offset="1">
                            <el-form-item>
                                <el-button type="primary" round
                                    @click="addTempTasks(taskInRequestRef, taskInRequestEntity)">绑定信息</el-button>
                            </el-form-item>
                        </el-col>
                        <el-col :span="11">
                            <el-form-item>
                                <el-button type="warning" round
                                    @click="callEmptyVehicles(taskInRequestEntity)">请求空箱</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </fieldset>
            <div ref="btnArea"></div>
            <fieldset class="display-area">
                <legend style="font-size: 25px;">
                    入库暂存信息
                </legend>
                <el-table :data="tempTasks" stripe border class="table-class" max-height="684px"
                    :header-cell-style="{ 'text-align': 'center', 'height': '100px' }"
                    :cell-style="{ 'text-align': 'center' }">
                    <el-table-column prop="vehicleNo" label="箱号" fixed="left" min-width="1rem" />
                    <el-table-column prop="goodsId" label="零件号" fixed="left" min-width="1rem" />
                    <el-table-column prop="goodsNum" label="数量" min-width="1rem" />
                    <el-table-column prop="goodsName" label="零件名称" min-width="1rem" />
                    <el-table-column prop="weight" label="重量" min-width="1rem" />
                    <el-table-column fixed="right" label="操作" min-width="1rem">
                        <template #default>
                            <el-button style="width: 1rem;" plain type="primary"
                                @click="deleteRowTask(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <br />
                <el-row :gutter="4">
                    <el-col :span="24">
                        <el-form-item>
                            <el-button type="success" round
                                @click="submitGoodsInTask(taskInRequestEntity)">下发任务</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </fieldset>
        </el-container>
    </el-config-provider>
</template>

<script setup>
import store from '@/store'
import { sendGoodsInTask, callEmptyVehicle } from '@/api/task'
import { queryPartInfoByPartNo } from '@/api/goods'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { errorBox } from '@/utils/myMessageBox.js'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import UploadExcelPart from '@/excel/UploadExcelPart.vue'
const taskInRequestRef = ref()
const taskInRequestEntity = reactive({
    vehicleNo: '',// 载具号
    goodsId: '',// 零件号
    goodsName: '',// 零件名称
    goodsNum: 1,// 零件数量
    weight: 0,// 零件重量
    shelfLife: 0,// 有效期
    productionDate: '',// 生产日期
    isEmpty: '1',
    userName: store.getters.getUserName// 用户名
})
const rules = reactive({
    vehicleNo: [
        { required: true, message: '请输入载具编号' }
    ],
    goodsId: [
        { required: true, message: '请输入物料编号' }
    ],
    goodsNum: [
        { required: true, message: '请输入数量' },
        { type: 'number', message: '请输入数字' }
    ]
})
const labelPosition = "top"
const displayWidth = window.screen.width
</script>

<script>
export default {
    name: 'goodsInPda',
    components: {
        UploadExcelPart
    },
    data() {
        return {
            tempTasks: [],
            tempVehicleNo: '',
            disPlayDateFlag: false,
            currentPartInfo: {},
            stockTypeOptions: [
                {
                    value: '0',
                    label: '空箱入库'
                },
                {
                    value: '1',
                    label: '带料入库'
                }
            ],
            disabledEmpty: false,
            totalWeight: 0,
            isOverWeight: false
        }
    },
    mounted() {
        this.$refs.vehicleNo.focus()
    },
    methods: {
        // 查询
        queryAndAutoComplete(taskInRequestEntity) {
            this.loading = true
            const param = { material: taskInRequestEntity.goodsId }
            queryPartInfoByPartNo(param).then(res => {
                console.log(res)
                if (res.data.code == 0) {
                    this.currentPartInfo = res.data.returnData
                    taskInRequestEntity.goodsName = this.currentPartInfo.itemDesc
                    this.calWeight(taskInRequestEntity)
                    if (this.currentPartInfo.SLED > 0) {// 判断生产日期区域显示与否
                        this.disPlayDateFlag = true
                        taskInRequestEntity.shelfLife = this.currentPartInfo.SLED
                    } else {
                        this.disPlayDateFlag = false
                        taskInRequestEntity.shelfLife = 0
                        taskInRequestEntity.productionDate = ''
                    }
                    taskInRequestEntity.goodsNum = ''
                    this.$refs.goodsNum.focus()
                } else {
                    taskInRequestEntity.goodsName = ''
                    taskInRequestEntity.goodsNum = ''
                    taskInRequestEntity.weight = 0
                    this.disPlayDateFlag = false
                    taskInRequestEntity.shelfLife = 0
                    taskInRequestEntity.productionDate = ''
                    ElMessage.error(res.data.message)
                }
            }).catch(err => {
                taskInRequestEntity.goodsName = ''
                taskInRequestEntity.goodsNum = ''
                taskInRequestEntity.weight = 0
                this.disPlayDateFlag = false
                taskInRequestEntity.shelfLife = 0
                taskInRequestEntity.productionDate = ''
                ElMessage.error('查询物料信息错误' + err.message)
            })
            this.loading = false
        },
        calWeight(taskInRequestEntity) {
            taskInRequestEntity.weight = this.currentPartInfo.partWeight * taskInRequestEntity.goodsNum
            this.totalWeight = this.totalWeight + taskInRequestEntity.weight
            if (this.totalWeight > 30) {
                this.isOverWeight = true
                ElMessage({
                    message: '箱子重量超过30kg',
                    type: 'warning',
                })
            }
        },
        autoCompleteEmptyInfo(taskInRequestEntity) {// 自动补全空托入库信息
            if (taskInRequestEntity.isEmpty == '0') {// 空托入库
                taskInRequestEntity.goodsId = '000000000'
                taskInRequestEntity.batchNo = '000000000'
                taskInRequestEntity.goodsNum = 1
                taskInRequestEntity.weight = 0
                taskInRequestEntity.shelfLife = 0
                taskInRequestEntity.productionDate = ''
                taskInRequestEntity.goodsName = '空箱'
                this.currentPartInfo = {}
                this.disabledEmpty = true
                this.disPlayDateFlag = false
            } else {
                taskInRequestEntity.goodsId = ''
                taskInRequestEntity.batchNo = ''
                taskInRequestEntity.goodsNum = 1
                this.disabledEmpty = false
            }
            this.$refs.vehicleNo.focus()

        },
        addTempTasks(formEl, formData) {// 生成入库任务
            if (!formEl) return
            formEl.validate((valid) => {
                if (!valid) {
                    ElMessage({
                        message: '请输入必须的入库信息！',
                        type: 'warning',
                    })
                    return
                }
                if (this.tempVehicleNo !== '' && this.tempVehicleNo !== formData.vehicleNo) {
                    ElMessage({
                        message: '载具编号不一致，请确认后重新输入！',
                        type: 'warning',
                    })
                    return
                }
                if (this.tempVehicleNo != '' && formData.isEmpty == '0') {
                    ElMessage({
                        message: '此箱子已经绑定过，请下发。',
                        type: 'warning',
                    })
                    return
                }
                if (this.isOverWeight) {
                    ElMessage({
                        message: '已超重，不可继续绑定，请移除此物料，并下发任务',
                        type: 'error',
                        showClose: true
                    })
                    return
                }
                this.tempVehicleNo = formData.vehicleNo
                formData.userName = store.getters.getUserName
                const sameIndex = this.tempTasks.findIndex(task => task.goodsId == formData.goodsId)
                if (sameIndex != -1) {// 绑定过相同物料
                    var sameGoods = this.tempTasks[sameIndex]
                    sameGoods.goodsNum = sameGoods.goodsNum + formData.goodsNum
                    sameGoods.weight = sameGoods.weight + formData.weight
                } else {
                    this.tempTasks.push(Object.assign({}, formData))
                }
                this.resetFields(formData)
                formData.vehicleNo = this.tempVehicleNo
                ElMessage({
                    message: '绑定成功！',
                    type: 'success',
                })
            })
        },
        submitGoodsInTask(taskInRequestEntity) {// 下发入库任务
            if (this.tempTasks.length == 0) {
                ElMessage.error("未绑定任何信息")
            }
            sendGoodsInTask(this.tempTasks).then(res => {
                if (res.data.code == 0) {
                    this.tempTasks = []
                    this.tempVehicleNo = ''
                    this.resetFields(taskInRequestEntity)
                    this.totalWeight = 0
                    this.isOverWeight = false
                    ElMessage({
                        message: '下发任务成功，剩余库位可用数量: ' + res.data.returnData,
                        type: 'success'
                    })
                    this.$refs.vehicleNo.focus()
                } else {
                    ElMessage.error(res.data.message)
                }
            }).catch(err => {
                console.log(err)
                ElMessage.error('创建入库任务错误！' + err.message)
            })
        },
        resetFields(taskInRequestEntity) {
            taskInRequestEntity.vehicleNo = ''
            if (taskInRequestEntity.isEmpty != '0') {// 不是空托入库
                taskInRequestEntity.goodsId = ''
                taskInRequestEntity.goodsName = ''
                taskInRequestEntity.goodsNum = 1
                taskInRequestEntity.weight = 0
                taskInRequestEntity.shelfLife = 0
                taskInRequestEntity.productionDate = ''
            }
            this.disPlayDateFlag = false
            this.currentPartInfo = {}
        },
        callEmptyVehicles(taskInRequestEntity) {
            callEmptyVehicle(taskInRequestEntity).then(res => {
                if (res.data.code == 0) {
                    ElMessage({
                        message: res.data.message,
                        type: 'success'
                    })
                } else {
                    ElMessage.error(res.data.message)
                }
            }).catch(err => {
                console.log(err)
                ElMessage.error('呼叫空箱错误' + err.message)
            })
        },
        deleteRowTask(row) {// 删除当前行的入库任务
            this.tempTasks.splice(this.tempTasks.indexOf(row), 1)
            if (this.tempTasks.length == 0) {
                this.tempVehicleNo = ''
            }
        },
        detectEndInputVehicleNo(taskInRequestEntity) {
            if (taskInRequestEntity.isEmpty == '0') {// 空托入库
                this.$refs.btnArea.scrollIntoView();
                // this.$refs.vehicleNo.blur()
            } else {
                this.$refs.goodsId.focus()
            }
        },
        detectEndInputNum(taskInRequestEntity) {
            this.calWeight(taskInRequestEntity)
        }
    }
}
</script>

<style scoped>
.content {
    display: flex;
    flex-direction: column;
    width: v-bind(displayWidth);
}

.el-row {
    margin: 20px 0;
}

:deep(.el-form-item__label) {
    font-size: 25px;
    /* margin: 10px; */
    padding: 10px 0;
}

:deep(.el-select-v2__placeholder) {
    font-size: 25px;
}

:deep(.el-select-v2__wrapper) {
    height: 80px;
}

:deep(.el-form-item .el-input) {
    height: 80px;
    font-size: 25px;
}

:deep(.el-form-item .el-input-number) {
    height: 80px;
    font-size: 25px;
}

:deep(.el-table .cell) {
    line-height: 100%;
}

.el-row .el-form-item {
    justify-content: center;
}

.el-row .el-form-item .el-select {
    width: 100% !important;
}

.el-row .el-form-item .el-select-v2 {
    width: 100% !important;
}

.el-row .el-form-item .el-input-number {
    width: 100% !important;
}

.el-row .el-form-item .el-button {
    width: 180px;
    height: 60px;
    margin: auto;
    font-size: 25px;
}

.input-area {
    margin: 10px;
    width: v-bind(displayWidth) - 20px;
    /* height: 730px; */
    border: solid 1px;
    border-radius: 10px;
    box-shadow: 0px 15px 10px -15px #000;
}

.display-area {
    margin: 10px;
    width: v-bind(displayWidth) - 20px;
    /* height: auto; */
    border: solid 1px;
    border-radius: 10px;
    box-shadow: 0px 15px 10px -15px #000;
}

.table-class {
    width: 100%;
    font-size: 1rem;
}
</style>