<template>
    <el-config-provider :locale="zhCn">
        <el-container class="content">
            <div class="work-area">
                <fieldset class="main-area">
                    <el-form ref="inTaskRef" :model="inTaskEntity" :label-position="labelPosition" label-width="158px"
                        style="max-width: 100%" :rules="rules" status-icon>
                        <div style="display: flex;justify-content: space-between;">
                            <el-row>
                                <el-form-item label="入库类型" prop="emptyTask">
                                    <el-select-v2 v-model="inTaskEntity.emptyTask" placeholder="请选择入库类型"
                                        :options="inTypeOptions"
                                        :disabled="taskRequestEntity.vehicleId != ''"></el-select-v2>
                                </el-form-item>
                                <el-form-item label="箱号" prop="vehicleId">
                                    <el-input v-model="inTaskEntity.vehicleId" ref="vehicleId"
                                        :disabled="taskRequestEntity.vehicleId != ''" clearable
                                        @keyup.enter="handleEnter()" />
                                </el-form-item>
                                <el-form-item label="料号">
                                    <el-input v-model="inTaskEntity.goodsId" ref="goodsId"
                                        :disabled="inTaskEntity.emptyTask" clearable @keyup.enter="handleEnter()" />
                                </el-form-item>
                                <el-form-item label="数量">
                                    <el-input-number v-model.number="inTaskEntity.opNum" ref="opNum"
                                        :disabled="inTaskEntity.emptyTask" controls-position="right" :min="1" clearable
                                        @keyup.enter="handleEnter()" />
                                </el-form-item>
                            </el-row>
                            <el-row>
                                <el-button type="success"
                                    style="height: 50px; width: 100px; margin: auto 5px auto 5px; font-size: large; color: black;"
                                    @click="addBinding()">绑定物料</el-button>
                                <el-button type="warning"
                                    style="height: 50px; width: 100px; margin: auto 5px auto 5px; font-size: large; color: black;"
                                    @click="clearInput()">清除输入</el-button>
                                <el-button type="primary"
                                    style="height: 50px; width: 100px; margin: auto 5px auto 5px; font-size: large; color: black;"
                                    @click="openOutForInDialog()">入库料扫码</el-button>
                            </el-row>
                        </div>
                    </el-form>
                </fieldset>
                <fieldset class="confirm-area" v-if="taskRequestEntity.vehicleId != ''">
                    <el-form ref="taskRequestRef" :model="taskRequestEntity" :label-position="labelPosition"
                        label-width="158px" style="max-width: 100%" :rules="rules" status-icon>
                        <div style="display: flex;justify-content: space-between;">
                            <el-row>
                                <el-form-item label="入库类型">
                                    <el-select-v2 v-model="taskRequestEntity.emptyTask" placeholder="请选择入库类型"
                                        :options="inTypeOptions" disabled></el-select-v2>
                                </el-form-item>
                                <el-form-item label="箱号">
                                    <el-input v-model="taskRequestEntity.vehicleId" disabled />
                                </el-form-item>
                            </el-row>
                            <el-row>
                                <el-button type="success" ref="sendTaskRef"
                                    style="height: 50px; width: 100px; margin: auto 5px auto 5px; font-size: large; color: black;"
                                    @click="confirmTasks()">下发任务</el-button>
                                <el-button type="danger"
                                    style="height: 50px; width: 100px; margin: auto 5px auto 5px; font-size: large; color: black;"
                                    @click="cancelBinding()">取消绑定</el-button>
                            </el-row>
                        </div>
                    </el-form>
                    <el-table :data="taskRequestEntity.goodsInfo" stripe border class="table-class" max-height="450px"
                        :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
                        v-if="taskRequestEntity.goodsInfo.length != 0">
                        <el-table-column prop="goodsId" label="零件号" fixed="left" />
                        <el-table-column prop="opNum" label="数量" />
                        <el-table-column fixed="right" label="操作">
                            <template #default>
                                <el-button plain type="warning" @click="removeThisRow(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </fieldset>
                <el-dialog v-model="showInOutDialog" title="入库清单扫码" width="70%" draggable>
                    <fieldset class="main-area">
                        <el-form ref="outForInRef" :model="outForInEntity" :label-position="labelPosition"
                            label-width="158px" style="max-width: 100%" :rules="outForInRules" status-icon>
                            <div style="display: flex; justify-content: space-between;">
                                <el-row>
                                    <el-form-item label="料号">
                                        <el-input v-model="outForInEntity.goodsId" ref="forInGoodsId" clearable
                                            @keyup.enter="addForInGoods()" />
                                    </el-form-item>
                                </el-row>
                                <el-row>
                                    <el-button type="success"
                                        style="height: 50px; width: 100px; margin: auto 5px auto 5px; font-size: large; color: black;"
                                        @click="addForInGoods()">添加物料</el-button>
                                    <el-button type="primary"
                                        style="height: 50px; width: 100px; margin: auto 5px auto 5px; font-size: large; color: black;"
                                        @click="refreshOuts()">刷新</el-button>
                                </el-row>
                            </div>
                        </el-form>
                    </fieldset>
                    <fieldset class="confirm-area" v-if="outForInRequestEntity.goodsIds.length != 0">
                        <div style="display: flex; justify-content: space-between;">
                            <el-button type="success"
                                style="height: 50px; width: 100px; margin: auto 5px auto auto; font-size: large; color: black;"
                                @click="confirmTasks()">确认需求</el-button>
                        </div>
                        <el-table ref="outForInTableRef" :data="outForInRequestEntity.goodsIds" stripe border
                            class="table-class" max-height="200px" :header-cell-style="{ 'text-align': 'center' }"
                            :cell-style="{ 'text-align': 'center' }">
                            <el-table-column prop="goodsId" label="料号" fixed="left" />
                            <el-table-column fixed="right" label="操作">
                                <template #default>
                                    <el-button plain type="warning" @click="popThisGoodsId(row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </fieldset>
                    <!-- <fieldset class="confirm-area">
                        <el-table :data="outForInRequestEntity.goodsIds" stripe border class="table-class"
                            max-height="350px" :header-cell-style="{ 'text-align': 'center' }"
                            :cell-style="{ 'text-align': 'center' }">
                            <el-table-column prop="goodsId" label="料号" fixed="left" />
                            <el-table-column prop="goodsId" label="状态" fixed="left" />
                            <el-table-column fixed="right" label="操作">
                                <template #default>
                                    <el-button plain type="warning" @click="removeThisRow(row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </fieldset> -->
                </el-dialog>
            </div>
        </el-container>
    </el-config-provider>
</template>

<script setup>
import store from '@/store'
import { requireStockIn } from '@/api/task.js'
import { errorBox } from '@/utils/myMessageBox.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { nextTick, onMounted, reactive, ref } from 'vue'
import { loading } from '@/utils/loading.js'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { labelPosition } from '@/constant/form'
const inTypeOptions = [
    {
        label: '空箱入库',
        value: true
    },
    {
        label: '非空箱入库',
        value: false
    }
]
const rules = reactive({
    emptyTask: [
        { required: true, message: '请选择入库类型。' }
    ],
    vehicleId: [
        { required: true, message: '请输入箱号。' }
    ]
})
const vehicleId = ref()
const goodsId = ref()
const opNum = ref()
const sendTaskRef = ref()
let inTaskRef = ref()
let inTaskEntity = reactive({
    emptyTask: false,
    vehicleId: '',
    goodsId: '',
    opNum: null
})
let taskRequestRef = ref()
let taskRequestEntity = reactive({
    emptyTask: false,
    vehicleId: '',
    origin: store.getters.getStandId,
    goodsInfo: [],
    standId: store.getters.getStandId,
    userName: store.getters.getUserName
})
let showInOutDialog = ref(false)
let outForInRef = ref()
let outForInEntity = reactive({
    goodsId: '',
})
const outForInRules = reactive({
    goodsId: [
        { required: true, message: '请输入料号。' }
    ]
})
const forInGoodsId = ref()
let outForInRequestEntity = reactive({
    goodsIds: [],
    origin: store.getters.getStandId,
    standId: store.getters.getStandId,
    userName: store.getters.getUserName
})
const outForInTableRef = ref()
onMounted(() => {
    nextTick(() => {
        vehicleId.value.focus()
    })
})
// 处理回车事件
const handleEnter = () => {
    changeFocus()
}
// 改变输入焦点
const changeFocus = () => {
    // 进行大写格式化
    inTaskEntity.vehicleId = inTaskEntity.vehicleId.toUpperCase()
    inTaskEntity.goodsId = inTaskEntity.goodsId.toUpperCase()
    if (inTaskEntity.vehicleId == '') {
        vehicleId.value.focus()
        return
    }
    // 进行格式判断
    if (inTaskEntity.vehicleId != '') {
        const vehicleArray = inTaskEntity.vehicleId.split('-')
        if (vehicleArray.length != 2) {
            errorBox('箱号格式不正确，正确格式为“ASRS-XXXX”。')
            vehicleId.value.focus()
            return
        } else {
            if (vehicleArray[0] != 'ASRS' || !numberCheck(vehicleArray[1]) || vehicleArray[1].length != 4) {
                errorBox('箱号格式不正确，正确格式为“ASRS-XXXX”。')
                vehicleId.value.focus()
                return
            } else if (parseInt(vehicleArray[1]) < 1 || parseInt(vehicleArray[1]) > 2200) {
                errorBox('箱号范围是0001～2200。')
                vehicleId.value.focus()
                return
            }
        }
    }
    if (inTaskEntity.opNum != null) {
        if (inTaskEntity.opNum < 0 || inTaskEntity.opNum > 99999) {
            errorBox('数量不正确，应该为1-99999之间的整数值。')
            opNum.value.focus()
            return
        }
    }
    // 非空箱入库
    if (!inTaskEntity.emptyTask) {
        if (inTaskEntity.goodsId == '') {
            goodsId.value.focus()
            return
        }
        if (inTaskEntity.opNum == null || inTaskEntity.opNum == '') {
            opNum.value.focus()
            return
        }
    }
    if (inTaskEntity.goodsId == inTaskEntity.vehicleId || inTaskEntity.goodsId == inTaskEntity.opNum || inTaskEntity.vehicleId == inTaskEntity.opNum) {
        errorBox('箱号、料号、数量必须为互不相同。')
        goodsId.value.focus()
        return
    }
    addBinding()
}
// 判断一个字符串是否是数字
const numberCheck = (numberStr) => {
    if (numberStr == null || numberStr == '') {
        return false
    }
    try {
        return !isNaN(parseInt(numberStr))
    } catch (e) {
        return false
    }
}
// 清除输入
const clearInput = () => {
    if (taskRequestEntity.vehicleId != '') {
        if (!taskRequestEntity.emptyTask) {
            inTaskEntity.goodsId = ''
            inTaskEntity.opNum = null
        }
    } else {
        inTaskEntity.vehicleId = ''
        if (!inTaskEntity.emptyTask) {
            inTaskEntity.goodsId = ''
            inTaskEntity.opNum = null
        }
    }
}
// 添加绑定关系
const addBinding = () => {
    if (taskRequestEntity.vehicleId != '' && taskRequestEntity.vehicleId != inTaskEntity.vehicleId) {
        errorBox('请下发已绑定的任务或取消绑定后重试。')
        return
    }
    if (taskRequestEntity.vehicleId == '') {
        if (inTaskEntity.vehicleId == '') {
            errorBox('请输入箱号。')
            vehicleId.value.focus()
            return
        }
        if (!inTaskEntity.emptyTask) {
            if (inTaskEntity.goodsId != '' && inTaskEntity.opNum != null && inTaskEntity.opNum > 0) {
                // 非空入库
                taskRequestEntity.goodsInfo.push({
                    goodsId: inTaskEntity.goodsId,
                    opNum: inTaskEntity.opNum
                })
                inTaskEntity.goodsId = ''
                inTaskEntity.opNum = null
            }
        }
        // 添加任务
        taskRequestEntity.emptyTask = inTaskEntity.emptyTask
        taskRequestEntity.vehicleId = inTaskEntity.vehicleId
    } else {
        if (!taskRequestEntity.emptyTask) {
            if (inTaskEntity.goodsId == '') {
                errorBox('请输入料号。')
                goodsId.value.focus()
                return
            }
            if (inTaskEntity.opNum == null || inTaskEntity.opNum == 0) {
                errorBox('请输入正确的数量。')
                opNum.value.focus()
                return
            }
            // 非空入库
            taskRequestEntity.goodsInfo.push({
                goodsId: inTaskEntity.goodsId,
                opNum: inTaskEntity.opNum
            })
            inTaskEntity.goodsId = ''
            inTaskEntity.opNum = null
        } else {
            // 空入库不允许多次下发
            errorBox('空入库不允许多次下发。')
            return
        }
    }
    goodsId.value.focus()
}
// 确认下发任务
const confirmTasks = () => {
    // 判断是否是非空箱入库时，未输入料号和数量
    if (!taskRequestEntity.emptyTask && taskRequestEntity.goodsInfo.length == 0) {
        ElMessageBox.confirm(
            '非空箱入库未绑定物料，默认生成回库任务。\n是否继续',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            confirmSend()
        }).catch(() => {
            ElMessage.info('操作取消')
        })
    } else {
        confirmSend()
    }
}
const confirmSend = () => {
    let request = taskRequestEntity
    loading.open()
    requireStockIn(request).then(res => {
        const response = res.data
        if (response.code == 0) {
            ElMessage.success(response.message)
            cancelBinding()
        } else {
            errorBox(response.message)
        }
    }).catch(err => {
        console.log(err)
        errorBox('请求错误。')
    }).finally(() => {
        loading.close()
    })
}
// 取消绑定
const cancelBinding = () => {
    resetTaskEntity()
    inTaskEntity.vehicleId = ''
    vehicleId.value.focus()
}
// 移除当前行
const removeThisRow = (row) => {
    taskRequestEntity.goodsInfo.splice(taskRequestEntity.goodsInfo.indexOf(row), 1)
    if (taskRequestEntity.goodsInfo.length == 0 && taskRequestEntity.vehicleId != '' && !taskRequestEntity.emptyTask) {
        // 非空箱且没有料号列表的情况下，解绑当前任务
        resetTaskEntity()
    }
    goodsId.value.focus()
}
// 重置任务
const resetTaskEntity = () => {
    taskRequestEntity.emptyTask = false
    taskRequestEntity.vehicleId = ''
    taskRequestEntity.goodsInfo = []
}
// 打开入库料扫码
const openOutForInDialog = () => {
    // 打开出库任务弹窗
    showInOutDialog.value = true
    nextTick(() => {
        // 聚焦
        forInGoodsId.value.focus()
    })
}
// 添加入库料
const addForInGoods = () => {
    if (outForInEntity.goodsId == '') {
        errorBox('请输入料号。')
    } else {
        outForInEntity.goodsId = outForInEntity.goodsId.toUpperCase()
        outForInRequestEntity.goodsIds.push({
            goodsId: outForInEntity.goodsId
        })
        outForInEntity.goodsId = ''
    }
    // 表格自动滚动到最后
    // nextTick(() => {
    //     outForInTableRef.value.scrollTo({
    //         top: outForInTableRef.value.getScrollHeight(),
    //         behavior: 'smooth'
    //     })
    // })
    // 聚焦
    forInGoodsId.value.focus()
}
const popThisGoodsId = (row) => {
    outForInRequestEntity.goodsIds.splice(outForInRequestEntity.goodsIds.indexOf(row), 1)
    forInGoodsId.value.focus()
}
// 刷新入库料清单
const refreshOuts = () => {

}
</script>

<style scoped>
.content {
    display: flex;
    width: 100%;
}

.work-area {
    width: 100%;
    /* padding: 5px; */
}

.main-area {
    margin: auto;
    min-height: fit-content;
    max-height: 90%;
    margin-bottom: 10px;
    min-width: inherit;
    border: solid 1px;
    border-radius: 10px;
    box-shadow: 0px 15px 10px -15px #000;
    overflow: auto;
    padding: 10px;
}

.confirm-area {
    margin: auto;
    min-height: fit-content;
    max-height: 90%;
    margin-bottom: 10px;
    min-width: inherit;
    border: solid 1px;
    border-radius: 10px;
    box-shadow: 0px 15px 10px -15px #000;
    overflow: auto;
    padding: 10px;
}

.title-area {
    display: flex;
    /* min-height: 10%; */
    max-height: max-content;
    margin-bottom: 10px;
    min-width: inherit;
    border: solid 1px;
    border-radius: 10px;
    box-shadow: 0px 15px 10px -15px #000;
    overflow: auto;
}

.el-form-item {
    margin: 10px 5px 10px 5px;
}

.el-form-item .el-input {
    width: 196px;
}

.el-form-item .el-input-number {
    width: 185px;
}

.table-class {
    margin: 5px 5px 5px 5px;
    width: inherit;
}
</style>