<!--
  功能：调拨入库
  作者：陶庆峰
-->
<template>
    <div class="page-horizontal-wrap">
        <div class="page-left-container">
            <div class="left-form-container" style="min-height:150px">
                <el-form ref="formDataRef" label-position="left" label-width="120px" :model="formData">
                    <el-form-item label="调拨入库单号" prop="SENDORDERNO">
                        <el-input v-model="formData.SHIPREQUESTNAME" placeholder="请输入出库单号"
                            @keydown.enter.prevent="getBoxList" />
                    </el-form-item>
<!--                    <el-form-item label="单据状态">-->
<!--                        <el-input disabled v-model="formData.SHIPREQUESTSTATE" placeholder="请输入单号" />-->
<!--                    </el-form-item>-->
                    <!-- <el-form-item label="退货商">
                        <el-input disabled v-model="formData.CUSTOMERNAME" placeholder="请输入发货单号" />
                    </el-form-item> -->
                    <!-- <el-form-item label="请求数量">
                        <el-input disabled v-model="formData.SENDORDERNO" placeholder="请输入发货单号" />
                    </el-form-item>
                    <el-form-item label="物料编号">
                        <el-input disabled v-model="formData.SENDORDERNO" placeholder="请输入发货单号" />
                    </el-form-item> -->
                    <el-form-item label="组织">
                        <el-input disabled v-model="formData.ERPRECEIVEFACTORY" placeholder="接收组织" />
                    </el-form-item>
                    <el-form-item label="仓库">
                        <el-input v-model="formData.ERPRECEIVELOCATION" placeholder="接收库位" />
                    </el-form-item>
                    <el-form-item label="目的货位" prop="portFormRefData.SEARCHTYPE">
                        <el-cascader @visible-change="handleOuterClick" v-model="state.StorageSelect"
                            :options="state.StorageSelectList"
                            :props="{ checkStrictly: true, label: 'ERPLOCATION', value: 'ERPLOCATION', children: 'children' }" />
                    </el-form-item>
                </el-form>

                <el-form ref="queryParamRef" label-position="left" label-width="120px" :model="queryParam"
                    :rules="rules_assigned">
                    <el-form-item label="条码" prop="MATERIALPACKINGNAME">
                        <el-input v-model="queryParam.MATERIALPACKINGNAME" placeholder="请输入条码"
                            @keydown.enter.prevent="getBatch" />
                    </el-form-item>
                </el-form>

            </div>
        </div>
        <div class="vue-element-page-wrap" ref="tableContainer">
            <div class="vue-element-page-table">
                <div class="page-table-operate">
                    <span>发货单明细</span>
                </div>
                <el-table border v-loading="undistributed_loading" :data="undistributed_list" height="300"
                    highlight-current-row row-key="id" @row-click="getBoxList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <template v-for="(col, index) in undistributed_column" :key="index">
                        <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
                            <template #default="scope">
                                <span>{{ scope.row[col.field] }}</span>
                            </template>
                        </el-table-column>
                    </template>
                    <template v-slot:empty>
                        <svg-icon icon-class="noData" width="160px" height="160px" />
                    </template>
                </el-table>
            </div>
            <div class="vue-element-page-table">
                <div class="page-table-operate">
                    <span>发货单标签明细</span>
                </div>
                <el-table border v-loading="assigned_loading" :data="assigned_list" height="300" highlight-current-row
                    row-key="id" @row-click="slectItem">
                    <template v-for="(col, index) in assigned_column" :key="index">
                        <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
                            <template #default="scope">
                                <span>{{ scope.row[col.field] }}</span>
                            </template>
                        </el-table-column>
                    </template>
                    <template v-slot:empty>
                        <svg-icon icon-class="noData" width="160px" height="160px" />
                    </template>
                </el-table>
            </div>
            <el-row class="page-search" justify="end" align="middle">

                <div class="page-search-btns">
                    <el-button type="primary" v-loading="state.loading" @click="handleReserve"
                        :disabled="state.Button_state">确定</el-button>
                </div>
            </el-row>
            <!-- assigned_list -->
        </div>
    </div>

</template>
<script lang="ts">
export default {
  name: 'AllocateStockIn'
};
</script>
<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance } from "vue";
import { ElForm, ElMessageBox } from "element-plus";
import { BpelEvent, getQueryList } from "@/api/common";
// import { getPageList } from "@/api/menu";
// import { Header } from "element-plus/es/components/table-v2/src/components";

const { proxy }: any = getCurrentInstance();

const formDataRef = ref(ElForm);
const queryParamRef = ref(ElForm);
const state = reactive({
    Button_state: false,
    firstLocation: '',
    loading: false,
    StorageSelect: [] as any,
    StorageSelectList: [] as any,
    formData: {
        SHIPREQUESTNAME: '',
        SHIPREQUESTSTATE: '',
        ERPRECEIVELOCATION: '',
        ERPRECEIVEFACTORY: '',
        CUSTOMERNAME: '',
        ToSHIPREQUEST: '',
        ToSHIPREQUESTDetail: '',
        MaterialPackingList: []
    },
    ERPRECEIVEFACTORY : '',
    queryParams: {
        queryId: "",
        version: "",
        params: {
            SITENAME: 'SDK',
            AREANAME: '',
            SHIPREQUESTNAME: "",
            RECEIVEACTNO: "",
            DELIVERYTYPE: "", //移动类型
            SUPPLIERNAME: "",
            //下面是handle查询参数
            MATERIALSPECNAME: "",
            ERPLOCATION: '',
            ERPFACTORY: '',
            SHIPREQUESTDETAILNAME: '',
        }, pageNum: 1,
        pageSize: 12
    },
    rules: {
        SENDORDERNO: [{ required: true, message: "请输入发货单号", trigger: "change" }]
    },
    queryParam: {
        MATERIALPACKINGNAME: ''
    },
    rules_assigned: {
        MATERIALPACKINGNAME: [{ required: true, message: "请输入条码", trigger: "change" }]
    },
    // 未分配
    undistributed_list: [] as any,
    undistributed_loading: false,
    undistributed_column: [] as any,

    assigned_list: [] as any,
    assigned_loading: false as any,
    assigned_column: [] as any,
    // 当前选中项
    rowItem: null as any,
    ThisFlag: false,//用于判断是否相同
    ThatFlag: false,
    TransportTaskChoose: [] as any
});
const { TransportTaskChoose, formData, queryParam, undistributed_column, undistributed_list, undistributed_loading, rules, assigned_list, assigned_loading, assigned_column, rules_assigned } = toRefs(state);

onMounted(() => {
    state.undistributed_column = [
        {
            header: "发货单号",
            field: "SHIPREQUESTNAME",
            width: "100px",
            hide: false,
        },
        {
            header: "行号",
            field: "SHIPREQUESTDETAILNAME",
            width: "100px",
            hide: false,
        },
        {
            header: "请求数量",
            field: "REQUESTQUANTITY",
            width: "100px",
            hide: false,
        },
        {
            header: "绑定数量",
            field: "ASSIGNEDQUANTITY",
            width: "100px",
            hide: false,
        }
        ,

    ]
    state.assigned_column = [
        {
            header: "标签批次",
            field: "MATERIALPACKINGNAME",
            width: "100px",
            hide: false,
        },
        {
            header: "阶段",
            field: "PHASE",
            width: "100px",
            hide: false,
        },
        {
            header: "数量",
            field: "MATERIALQUANTITY",
            width: "100px",
            hide: false,
        },
        {
            header: "库位",
            field: "ERPLOCATION",
            width: "100px",
            hide: false,
        },
        {
            header: "货位",
            field: "LOCATIONNAME",
            width: "100px",
            hide: false,
        },
        {
            header: "SDK规格",
            field: "SPECNAME",
            width: "100px",
            hide: false,
        }
    ]
});

/*****************************************************下面方法******************************************/
async function handleReserve() {
    if (state.assigned_list.length > 0) {
        state.Button_state = true
        let objectFull = []
        state.loading = true
        // state.TransportTaskChoose
        // 原代码
        for (let i = 0; i < state.assigned_list.length; i++) {
            objectFull.push({ "MATERIALPACKINGNAME": state.assigned_list[i].MATERIALPACKINGNAME, "LOCATIONNAME": state.assigned_list[i].LOCATIONNAME || '' })
        }
        // for (let i = 0; i < state.TransportTaskChoose.length; i++) {
        //     objectFull.push({ "MATERIALPACKINGNAME": state.assigned_list[0].MATERIALPACKINGNAME, "LOCATIONNAME": state.assigned_list[0].LOCATIONNAME || '', })
        // }
        await BpelEvent({
            header: {
                MESSAGENAME: "AllocationStockIn",
                LANGUAGE: "Chinese",
                userId: localStorage.getItem('userId') ,
            },
            body: {
                SITENAME: localStorage.getItem('SITENAME') || "SDK",
                SHIPREQUESTDETAILNAME: '',
                SHIPREQUESTNAME: state.formData.SHIPREQUESTNAME,
                ERPLOCATION: state.formData.ERPRECEIVELOCATION,
                ERPFACTORY: state.formData.ERPRECEIVEFACTORY,
                BOXLIST: objectFull

            }
        }).then((res: any) => {
            if (res.code == '500') {
                ElMessageBox.alert(res.data.msg, '提示框', {
                    confirmButtonText: 'OK',
                })
                state.loading = false
                state.Button_state = false
            }
            else if (res.code == 'UndefinedCode') {
                ElMessageBox.alert(res.data.msg, '提示框', {
                    confirmButtonText: 'OK',
                })
                state.loading = false
                state.Button_state = false
            } else if (res.code == '0') {
                ElMessageBox.alert("入库成功", '提示框', {
                    confirmButtonText: 'OK',
                })
                state.loading = false
                state.Button_state = false
            }
        }).catch((error: any) => {
            ElMessageBox.alert(error, '提示框', {
                confirmButtonText: 'OK',
            })
            state.Button_state = false
        })
    } else {
        ElMessageBox.alert("入库标签列表为空", '提示框', {
            confirmButtonText: 'OK',
        })
        state.Button_state = false
    }

}

/**
 * 发货单号回车
 * */
function handleEnterKey() {
    getShipreDetailList()
    getTicketInfo()
}

//选择搬送任务
function handleSelectionChange(selection: any) {
    console.log('调用了', selection)
    state.TransportTaskChoose = selection
}

//获取所有的箱
function getAllPackingList() {
    let queryParam = {
        queryId: "getAllPackingList",
        version: "00001",
        params: {
            SITENAME: "SDK",
            SHIPREQUESTNAME: state.formData.SHIPREQUESTNAME,//预留单 
            SHIPREQUESTTYPE: '4E'
        }
    }
    getQueryList(queryParam).then((res: any) => {
        console.log(res.data)
        state.formData.CUSTOMERNAME = res.data[0]?.CUSTOMERNAME
        state.formData.ERPRECEIVEFACTORY = res.data[0]?.ERPFACTORY
        state.formData.ERPRECEIVELOCATION = res.data[0]?.ERPLOCATION
        state.formData.SHIPREQUESTSTATE = res.data[0]?.SHIPREQUESTSTATE
        
    }).catch((error: any) => {
        ElMessageBox.alert(error, '提示框', {
            confirmButtonText: 'OK',
        })
    })
}

function getBoxList() {
    let queryParam = {
        queryId: "GetSaleRetuenList",
        version: "00001",
        params: {
            SITENAME: "SDK",
            SHIPREQUESTNAME: state.formData.SHIPREQUESTNAME,//预留单 
            SHIPREQUESTTYPE: '4E'
        }
    }
    getQueryList(queryParam).then((res: any) => {
        console.log(res.data)
        state.formData.CUSTOMERNAME = res.data[0]?.CUSTOMERNAME
        state.formData.ERPRECEIVEFACTORY = res.data[0]?.ERPFACTORY
        state.formData.ERPRECEIVELOCATION = res.data[0]?.ERPLOCATION
        state.formData.SHIPREQUESTSTATE = res.data[0]?.SHIPREQUESTSTATE
        
    }).catch((error: any) => {
        ElMessageBox.alert(error, '提示框', {
            confirmButtonText: 'OK',
        })
    })
    getDetailList()
}

function handleOuterClick() {
    StorageList(state.formData.ERPRECEIVELOCATION)
}

async function StorageList(firstLocation: any) {
    try {
        try {
            state.queryParams.queryId = 'Get2stAreaName';
            state.queryParams.version = '00002';
            state.queryParams.params.ERPLOCATION = firstLocation;
            const res = await getQueryList(state.queryParams);
            state.StorageSelectList = res.data;
            if (state.StorageSelectList.length == 0) {
                proxy.$ElMessage.info('目的货位为空!');
                return;
            }
            for (let i = 0; i < state.StorageSelectList.length; i++) {
                state.queryParams.queryId = 'Get3stStorageName';
                state.queryParams.version = '00002';
                state.queryParams.params.AREANAME = state.StorageSelectList[i].ERPLOCATION;
                const childrenRes = await getQueryList(state.queryParams);
                state.StorageSelectList[i].children = childrenRes.data;
            }
        } catch (error) {
            console.error(`Error fetching children for item `, error);
            // 处理错误，可能设置一些默认值或标记该项为出错  
        }

        console.log("StorageSelectList", state.StorageSelectList);
    } catch (error) {
        console.error('Error fetching initial data', error);
        // 处理错误，可能重置 state 或进行其他恢复操作  
    }
}

function getDetailList() {
    let queryParam = {
        queryId: "GetSaleReturnDetail",
        version: "00001",
        params: {
            SITENAME: "SDK",
            SHIPREQUESTNAME: state.formData.SHIPREQUESTNAME,//预留单 
        }
    }
    getQueryList(queryParam).then((res: any) => {
        state.undistributed_list = res.data
    }).catch((error: any) => {
        ElMessageBox.alert(error, '提示框', {
            confirmButtonText: 'OK',
        })
    })
}
/**
 * 发货单明细列表查询
 * */
function getShipreDetailList() {
    formDataRef.value.validate((isValid: boolean) => {
        if (isValid) {
            getQueryList({
                queryId: "GetBoxListBy_4",
                version: "00001",
                params: {
                    userId: localStorage.getItem('userId'),
                    ...state.formData
                },
            }).then((res: any) => {
                console.log(res.data, 'data')
                // state.list = res.data
            });
        }
    });
}
/**
 * 发货单信息查询
 * */
function getTicketInfo() {
    formDataRef.value.validate((isValid: boolean) => {
        if (isValid) {
            getQueryList({
                queryId: "GetBoxListBy_4",
                version: "00001",
                params: {
                    userId: localStorage.getItem('userId'),
                    ...state.formData
                },
            }).then((res: any) => {
                console.log(res.data, 'data')
                // 禁用表单在此赋值
                // state.list = res.data
            });
        }
    });

}

/**
 * 行点击
 * */
function slectItem(row: any) {
    state.rowItem = row
}


/**
 * 回车查询批次信息
 * */
async function getBatch() {
    let columnsd = [] as any
    await getQueryList({
        queryId: "GetPackingName",
        version: "00001",
        params: {
            SITENAME: localStorage.getItem("siteName") || 'SDK',//localStorage.getItem("siteName"),
            MATERIALPACKINGNAME: state.queryParam.MATERIALPACKINGNAME,
        },
    }).then(async (res: any) => {
        if (res.data.length > 0) {
            for (let i = 0; i < state.assigned_list.length; i++) {
                if (state.assigned_list[i].MATERIALPACKINGNAME == res.data[0].MATERIALPACKINGNAME) {
                    ElMessageBox.alert('此标签已经绑定！', '提醒框', {
                        confirmButtonText: 'OK',
                    })
                    return
                }
            }
            for (let i = 0; i < state.undistributed_list.length; i++) {
                if (state.undistributed_list[i].SHIPREQUESTNAME == res.data[0].SHIPREQUESTNAME && state.undistributed_list[i].SHIPREQUESTDETAILNAME == res.data[0].SHIPREQUESTDETAILNAME) {
                    state.formData.ToSHIPREQUEST = res.data[0].SHIPREQUESTNAME
                    state.formData.ToSHIPREQUESTDetail = res.data[0].SHIPREQUESTDETAILNAME
                    columnsd = res.data[0]
                    state.ThisFlag = true
                    break
                }
            }
            if (state.ThisFlag == true) {
                await BpelEvent({
                    header: {
                        MESSAGENAME: 'AssignReceiveRequestToBox',
                        LANGUAGE: "Chinese",
                        userId: localStorage.getItem('userId') || '10975133',
                    },
                    body: {
                        SITENAME: localStorage.getItem('SITENAME') || "SDK",
                        SHIPREQUESTDETAILNAME: state.formData.ToSHIPREQUESTDetail,
                        SHIPREQUESTNAME: state.formData.ToSHIPREQUEST,
                        MATERIALPACKINGNAME: state.queryParam.MATERIALPACKINGNAME,
                        MATERIALQUANTITY: res.data[0].MATERIALQUANTITY
                    }
                }).then((res: any) => {
                    if (res.code == '0') {
                        columnsd.LOCATIONNAME = state.StorageSelect[1]
                        state.assigned_list.push({ ...columnsd })
                        state.StorageSelect = []
                        ElMessageBox.alert('绑定成功', '提醒框', {
                            confirmButtonText: 'OK',
                        })
                    }
                });
            } else {
                ElMessageBox.alert('此标签不属于此单据', '提醒框', {
                    confirmButtonText: 'OK',
                })
            }
        } else {
            ElMessageBox.alert('此标签不在信息查询失败！', '提醒框', {
                confirmButtonText: 'OK',
            })
        }

    })



}

/**
 * 入库按钮
 * */
function stockIn() {
    let query = {
        header: {
            MESSAGENAME: "OICCreateCheckPlan",
            LANGUAGE: "Chinese"
        },
        body: {
            BOXLIST: [],
            SITENAME: "SDK",
        }
    }
    BpelEvent(query).then((res: any) => {
        console.log(res, 'res')
    });

}

</script>

<style scoped>
.page-horizontal-wrap {
    display: flex;
    width: 100%;
    height: 100%;

    .page-left-container {
        width: 360px;
        height: 100%;
        background: #FFFFFF;
        border: 1px solid #DBDEE3;
        box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.10);
        border-radius: 4px;
        margin-right: 6px;
        padding: 10px;
        display: flex;
        flex-direction: column;

        :deep(.el-form-item) {
            margin-bottom: 20px;
        }

        .page-left-container-head {
            display: flex;
            justify-content: space-between;

            .page-form-title {
                font-size: 14px;
                color: #000000;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-weight: bold;
                margin-bottom: 10px;

                .el-icon {
                    cursor: pointer;
                }
            }
        }

    }

    .vue-element-page-wrap {
        flex: 1;
    }
}
</style>