<template>
    <div class="head_top">
        <div @click="ccc" :class="aaa ? 'buts check' : 'buts'">自主配送</div>
        <div @click="ddd" :class="bbb ? 'buts check' : 'buts'">外协</div>
    </div>
    <div
            style="margin: 2%; background-color: #ffffff; padding: 20px; box-sizing: border-box"
            v-if="aaa"
    >
        <el-form ref="form" :model="driverForm" label-width="100px" style="margin: 3px">
            <el-row>
                              <el-col :span="6">
                    <el-form-item label="配送司机:" prop="goodsShelfId">
                        <!--                        @change="changeSlaveDriver"-->
                        <el-select
                                v-model="deliveryDriver"
                                multiple
                                filterable
                                @change="changeDriver"
                                placeholder="请选择司机"
                        >
                            <el-option
                                    v-for="item in driverData"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="配送车辆:" prop="vehicleIds">
                        <el-select
                                filterable
                                multiple
                                v-model="vehicleIds"
                                placeholder="请选择车辆"
                                @change="changeVehicle"
                        >
                        <!-- vehicleData 车辆信息 -->
                            <el-option
                                    v-for="item in vehicleData" 
                                    :key="item.id"
                                    :label="item.vehicleNub"
                                    :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
    <el-col :span="6">
          <span>
            <el-form-item label="主司机:" prop="forklift">
              <el-input v-model="driverForm.masterDriverName" :disabled="true"> </el-input>
            </el-form-item>
            <el-form-item label="主车辆:" prop="forklift">
              <el-input v-model="driverForm.masterVehicleNub" :disabled="true"> </el-input>
            </el-form-item>
          </span>
                </el-col>
                <el-col :span="6">
                    <el-button round @click="viewDriverInfo" style="margin-left: 10%">查看司机配置</el-button>
                </el-col>
            </el-row>
        </el-form>
    </div>

    <div
            style="margin: 2%; background-color: #ffffff; padding: 20px; box-sizing: border-box"
            v-if="bbb"
    >
        <el-form ref="form" :model="waixieForm" label-width="100px" style="margin: 3px">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="外协来源:" prop="goodsShelfId">
                        <el-select filterable v-model="waixieForm.tripartiteSource" placeholder="请选择来源">
                            <el-option
                                    v-for="item in tripartiteSourceData"
                                    :key="item.dictKey"
                                    :label="item.dictValue"
                                    :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="司机名称:" prop="goodsShelfId">
                        <el-input v-model="waixieForm.driverName" placeholder="请输入司机名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="司机电话:" prop="goodsShelfId">
                        <el-input v-model="waixieForm.driverPhone" placeholder="请输入司机电话"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="车辆车牌:" prop="goodsShelfId">
                        <el-input v-model="waixieForm.vehicleNum" placeholder="请输入本次费用"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="配送费用:" prop="goodsShelfId">
                        <el-input v-model="waixieForm.deliveryFee" placeholder="请输入本次费用"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>

    <div style="margin: 2%; background-color: #ffffff; padding: 20px; box-sizing: border-box">
        <el-form ref="form" :model="stockUpForm" label-width="100px" style="margin: 3px">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="备货人员:" prop="forklift">
                        <el-select filterable v-model="stockUpForm.forklift" placeholder="请选择备货人员">
                            <el-option
                                    v-for="item in this.forkliftData"
                                    :key="item.dictKey"
                                    :label="item.dictValue"
                                    :value="item.dictKey"
                            >
                            </el-option>
                            <!--                            {{this.forkliftData}}-->
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="装车班组:" prop="loader">
                        <el-select filterable v-model="stockUpForm.loader" placeholder="请选择装卸班组">
                            <el-option
                                    v-for="item in loaderData"
                                    :key="item.dictKey"
                                    :label="item.dictValue"
                                    :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="卸车班组:" prop="loader">
                        <el-select filterable v-model="stockUpForm.unloader" placeholder="请选择装卸班组">
                            <el-option
                                    v-for="item in loaderData"
                                    :key="item.dictKey"
                                    :label="item.dictValue"
                                    :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <!--                <el-col :span="6">-->
                <!--                    <el-form-item label="班组职能:" prop="goodsAreaId">-->
                <!--                        <el-checkbox-group v-model="loadAndUnload">-->
                <!--                            <el-checkbox-->
                <!--                                    v-for="item in loadAndUnloadData"-->
                <!--                                    :label="item.dictKey"-->
                <!--                                    :value="item.dictKey"-->
                <!--                            >-->
                <!--                                <span>{{ item.dictValue }}</span>-->
                <!--                            </el-checkbox>-->
                <!--                        </el-checkbox-group>-->
                <!--                    </el-form-item>-->
                <!--                </el-col>-->
                <el-col :span="6">
                    <el-form-item label="配送类型:" prop="goodsAreaId">
                        <el-radio-group v-model="stockUpForm.deliveryType">
                            <el-radio :label="'1'" :value="'1'">商配&emsp;</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="备货区域:" prop="goodsAreaId">
                        <el-select filterable v-model="stockUpForm.goodsAreaId" placeholder="请选择备货区域">
                            <el-option
                                    v-for="item in goodsAreaData"
                                    :key="item.dictKey"
                                    :label="item.dictValue"
                                    :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="备货时间:" prop="goodsShelfId" class="zytim">
                        <el-date-picker
                                v-model="stockUpForm.stockupDate"
                                type="datetime"
                                placeholder="请选择备货时间"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="出库时间:" prop="outboundDate" label-width="100px">
                        <el-date-picker
                                v-model="stockUpForm.outboundDate"
                                type="datetime"
                                placeholder="请选择配车时间"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <div class="pstime">
                        <el-form-item label="配送日期:" prop="taskTime" label-width="100px">
                            <el-date-picker
                                    v-model="stockUpForm.taskTime"
                                    type="date"
                                    placeholder="请选择配送时间"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </div>
                </el-col>
                <el-row></el-row>
                <!--                <el-col :span="6">-->
                <!--                    <el-form-item label="配送方式:" prop="serveType" label-width="100px">-->
                <!--                        &lt;!&ndash;              <el-input v-model="form.serveType" clearable placeholder="请选择服务类型"/>&ndash;&gt;-->
                <!--                        <el-radio-group v-model="stockUpForm.deliveryWay" v-for="item in this.deliveryWayData">-->
                <!--                            <el-radio :label="item.dictKey" :value="item.dictKey"-->
                <!--                            >{{ item.dictValue }}&emsp;-->
                <!--                            </el-radio>-->
                <!--                        </el-radio-group>-->
                <!--                    </el-form-item>-->
                <!--                </el-col>-->

                <!--                <el-col :span="6">-->
                <!--                    <el-form-item label="服务类型:" prop="serveType" label-width="100px">-->
                <!--                        &lt;!&ndash;              <el-input v-model="form.serveType" clearable placeholder="请选择服务类型"/>&ndash;&gt;-->
                <!--                        <el-checkbox-group v-model="serveType" v-for="item in this.addvalueServeTypeData">-->
                <!--                            <el-checkbox :label="item.dictKey" :value="item.dictKey"-->
                <!--                            >{{ item.dictValue }}&emsp;-->
                <!--                            </el-checkbox>-->
                <!--                        </el-checkbox-group>-->
                <!--                    </el-form-item>-->
                <!--                </el-col>-->
            </el-row>

            <el-row>
                <el-col :span="24">
                    <el-form-item label="备注:" prop="remarks">
                        <el-input
                                type="textarea"
                                :rows="2"
                                placeholder="请输入内容"
                                v-model="stockUpForm.remarks"
                        >
                        </el-input>
                    </el-form-item>
                </el-col>
                <!--                <el-col :span="8">-->
                <!--                    <el-form-item label="其他费用:" prop="collectFee" label-width="100px">-->
                <!--                        <el-input v-model="stockUpForm.otherFee" placeholder="请输入其他费用"/>-->
                <!--                    </el-form-item>-->
                <!--                </el-col>-->
            </el-row>
        </el-form>
    </div>
    <div>
        <el-tabs type="border-card">
            <el-tab-pane label="订单">
                <el-button type="primary" link @click="handleAddOrder" class="addbtn">新增</el-button>
                <el-table
                        ref="table"
                        v-loading="loading"
                        :data="orderData"
                        :height="height"
                        style="width: 100%; height: 50%"
                        :border="option.border"
                        @select="handleSelectionChange"
                >
                    <el-table-column type="selection" width="55"/>
                    <el-table-column
                            v-if="option.index"
                            label="序号"
                            type="index"
                            width="80px"
                            align="center"
                    ></el-table-column>
                    <template v-for="(item, index) in option.columnStockArticles">
                        <el-table-column
                                v-if="item.hide !== true"
                                :prop="item.prop"
                                :label="item.label"
                                :width="item.width"
                                :key="index"
                        >
                        </el-table-column>
                    </template>

                    <el-table-column prop="menu" label="操作" :width="220" align="center">
                        <template #="{ row }">
                            <el-button v-if="row.resource !=='零担' || row.isZero === '0'"
                                       type="primary"
                                       link
                                       icon="el-icon-view"
                                       @click="viewStockArticlePackage(row)"
                            >查看包件
                            </el-button>
                            <el-button
                                    v-if="row.resource ==='零担' || row.isZero === '1'"
                                    type="primary"
                                    link
                                    icon="el-icon-view"
                                    @click="entryNum(row)"
                            >在库录入
                            </el-button>
                            <el-button
                                    v-if="row.resource ==='零担' || row.isZero === '1'"
                                    type="primary"
                                    link
                                    icon="el-icon-view"
                                    @click="entryReservationNum(row)"
                            >数量录入
                            </el-button>
                            <el-button type="primary" link icon="el-icon-edit" @click="removeStockArticle(row)"
                            >移除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>

        <el-dialog
                v-model="zeroOrderShow"
                title="零担品类信息"
                width="50%"
                :model="zeroOrderData">
            <el-row :gutter="24" class="rows">
                <el-col :xl="4" :lg="7" :md="8" :sm="24">
                    <h3><span>在库总数：{{this.obj.handQuantity}}</span></h3>
                </el-col>
            </el-row>

            <template v-if="zeroOrderData != null">
                <div v-for="(item,index) in zeroOrderData" :key="index">
                    <el-row :gutter="24" class="rows">
                        <el-col :xl="4" :lg="7" :md="8" :sm="24">
                            <span>名称：{{item.firsts }}</span>
                        </el-col>
                        <el-col :xl="4" :lg="7" :md="8" :sm="24">
                            <span>总数量：{{item.quantity }} </span>
                        </el-col>
                        <el-col :xl="4" :lg="7" :md="8" :sm="24">
                            <span>在库数量：{{item.handQuantity }} </span>
                        </el-col>
                        <el-col :xl="4" :lg="7" :md="8" :sm="24">
                            <span>冻结数量：{{item.deliveryQuantity }} </span>
                        </el-col>
                        <el-col :xl="4" :lg="7" :md="8" :sm="24">
                            <span>出库数量：{{item.outboundQuantity }} </span>
                        </el-col>
                        <el-col :xl="4" :lg="7" :md="8" :sm="24">
                            <span>可用数量：{{(item.handQuantity - item.deliveryQuantity - item.outboundQuantity)}}</span>
                            <!--                                <span>可用数量：{{(item.quantity)}}</span>-->
                        </el-col>
                    </el-row>
                    <el-input-number v-if="this.isrReservationEntry" v-model="item.reservationNum" min="0"
                                     :max="item.zeroOrderMax"
                                     placeholder="请输入预约数量"></el-input-number>
                    <el-input-number v-else v-model="item.number" min="0"
                                     :max="item.quantity"
                                     placeholder="请输入预约数量"></el-input-number>
                    <!--                    <el-input-number v-model="item.reservationNum" min="0" :max="item.quantity - item.deliveryQuantity -item.outboundQuantity "  placeholder="请输入预约数量"></el-input-number>-->
                </div>
            </template>
            <el-form-item style="margin-left: 37%; margin-top: 5px">
                <el-button v-if="!isrReservationEntry" type="primary" icon="el-icon-circle-close" @click="onSubmitUpdateZeroOrder"
                >修改(零担订单)
                </el-button
                >
                <el-button type="primary" icon="el-icon-circle-close" @click="onSubmitZeroOrder"
                >提交(零担订单)
                </el-button
                >
                <el-button icon="el-icon-circle-close" @click="zeroOrderShow = false">返 回</el-button>
            </el-form-item>
        </el-dialog>


        <el-form-item style="margin-left: 45%; margin-top: 10px">
            <el-button  :disabled='BtnDisabled' type="primary" icon="el-icon-circle-close" @click="onSubmitBusiness"
            >提交(商配订单)
            </el-button>
            <el-button icon="el-icon-circle-close" @click="this.$router.go(-1)">返 回</el-button>
        </el-form-item>
    </div>

    <el-dialog v-model="orderShow" title="在库订单信息" width="100%">
        <span v-for="item in this.deliveryTypeData">{{ item }}</span>
        <el-form :inline="true" :model="query">
            <el-form-item label="商场名称:">
                <el-input v-model="query.mallName" placeholder="请输入商场名称"></el-input>
            </el-form-item>
            <el-form-item label="货物名称:">
                <el-input v-model="query.descriptionGoods" placeholder="请输入货物名称"></el-input>
            </el-form-item>
            <el-form-item label="运单号:">
                <el-input v-model="query.waybillNumber" placeholder="请输入运单号"></el-input>
            </el-form-item>
            <el-form-item label="订单自编号:">
                <el-input v-model="query.orderCode" placeholder="请输入订单自编号"></el-input>
            </el-form-item>
            <el-form-item label="服务号:">
                <el-input v-model="query.serviceNumber" placeholder="请输入服务号"></el-input>
            </el-form-item>

            <el-form-item label="顾客姓名:">
                <el-input v-model="query.customerName" placeholder="请输入客户姓名"></el-input>
            </el-form-item>
            <el-form-item label="顾客电话:">
                <el-input v-model="query.customerTelephone" placeholder="请输入顾客电话"></el-input>
            </el-form-item>
            <el-form-item label="顾客地址:">
                <el-input v-model="query.customerAddress" placeholder="请输入顾客地址"></el-input>
            </el-form-item>
            <!-- 查询按钮 -->
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchChange">搜 索</el-button>
                <el-button icon="el-icon-delete" @click="searchReset()">清 空</el-button>
            </el-form-item>
        </el-form>

        <!--        @selection-change="selectionChange"-->

        <el-table
                ref="stockArticleTable"
                v-loading="loading"
                @selection-change="selectionStockArticleChange"
                :data="stockArticleInfo"
                :height="height"
                style="width: 100%; height: 80%"
                :border="option.border"
        >
            <el-table-column
                    type="selection"
                    v-if="option.selection"
                    width="55"
                    align="center"
                    :selectable="checkOrder"
            ></el-table-column>
            <el-table-column
                    v-if="option.index"
                    label="序号"
                    type="index"
                    width="80px"
                    align="center"
            ></el-table-column>
            <template v-for="(item, index) in option.columnStockArticles">
                <el-table-column
                        v-if="item.hide !== true"
                        :prop="item.prop"
                        :label="item.label"
                        :width="item.width"
                        :key="index"
                >
                </el-table-column>
            </template>
        </el-table>
        <el-form-item style="margin-left: 45%; margin-top: 5px">
            <el-button type="primary" icon="el-icon-circle-close" @click="onSubmitOrder"
            >提交(订单)
            </el-button>
            <el-button icon="el-icon-circle-close" @click="orderShow = false">返 回</el-button>
        </el-form-item>
        <el-row>
            <div class="avue-crud__pagination" style="width: 100%">
                <!-- 分页模块 -->
                <el-pagination
                        align="right"
                        background
                        @size-change="sizeOrderChange"
                        @current-change="currentOrderChange"
                        :current-page="page.currentPage"
                        :page-sizes="[30, 50, 80, 120]"
                        :page-size="page.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="page.total"
                >
                </el-pagination>
            </div>
        </el-row>
    </el-dialog>

    <el-dialog v-model="stockListShow" title="库存品信息" width="100%" :before-close="handleClose">
        <el-form :inline="true" :model="query">
            <el-form-item label="顾客电话:">
                <el-input v-model="query.customerTelephone" placeholder="请输入顾客电话"></el-input>
            </el-form-item>
            <el-form-item label="顾客地址:">
                <el-input v-model="query.customerAddress" placeholder="请输入顾客地址"></el-input>
            </el-form-item>
            <!-- 查询按钮 -->
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchChange">搜 索</el-button>
                <el-button icon="el-icon-delete" @click="searchReset()">清 空</el-button>
            </el-form-item>
        </el-form>
        <el-table
                ref="table"
                v-loading="loading"
                @selection-change="selectionChange"
                :data="inventoryInfo"
                :height="height"
                style="width: 90%; height: 80%"
                :border="option.border"
        >
            <el-table-column
                    type="selection"
                    v-if="option.selection"
                    width="55"
                    align="center"
            ></el-table-column>
            <el-table-column
                    v-if="option.index"
                    label="序号"
                    type="index"
                    width="80px"
                    align="center"
            ></el-table-column>
            <template v-for="(item, index) in option.columnStockLists">
                <el-table-column
                        v-if="item.hide !== true"
                        :prop="item.prop"
                        :label="item.label"
                        :width="item.width"
                        :key="index"
                >
                </el-table-column>
            </template>
            <el-table-column label="预约数量" type="index" width="100px">
                <template #="{ row }">
                    <el-input v-model="row.reservationNum" type="number" :min="0"></el-input>
                </template>
            </el-table-column>
        </el-table>
        <el-form-item style="margin-left: 45%; margin-top: 5px">
            <el-button type="primary" icon="el-icon-circle-close" @click="onSubmitInventory"
            >提交(库存品)
            </el-button>
            <el-button icon="el-icon-circle-close" @click="stockListShow = false">返 回</el-button>
        </el-form-item>
    </el-dialog>

    <el-dialog v-model="isShowPackage" title="包件信息" width="100%">
        <!-- 列表模块 -->
        <el-table
                ref='tableRef'
                v-loading="loading"
                @selection-change="selectionChange"
                :data="packageData"
                :height="height"
                style="width: 100%; height: 100%"
                :border="option.border"
                
        >
            <el-table-column type="selection" v-if="option.selection" width="55" align="center">
                <!--        :selectable="checkPackage"-->

                <!--        <el-checkbox v-model="checked"></el-checkbox>-->
            </el-table-column>
            <el-table-column type="expand" v-if="option.expand" align="center"></el-table-column>
            <el-table-column v-if="option.index" label="序号" type="index" width="60" align="center">
            </el-table-column>
            <template v-for="(item, index) in option.columnPackage">
                <!-- table字段 -->
                <el-table-column
                        v-if="item.hide !== true"
                        :prop="item.prop"
                        :label="item.label"
                        :width="item.width"
                        :key="index"
                >
                </el-table-column>
            </template>
            <!-- 操作栏模块 -->
            <el-table-column prop="menu" label="操作" :width="220" align="center">
                <template #="{ row }">
                    <!--              <el-button type="primary" text icon="el-icon-view" @click="handleView(row)">查看</el-button>-->
                    <!--                        <el-button type="primary" text icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>-->
                    <!--              <el-button type="primary" text icon="el-icon-delete" @click="rowDel(row)">删除</el-button>-->
                </template>
            </el-table-column>
        </el-table>
        <el-form-item style="margin-left: 45%; margin-top: 5px">
            <el-button type="primary" icon="el-icon-circle-close" @click="onSubmitPackage"
            >提交(包件)
            </el-button>
            <el-button icon="el-icon-circle-close" @click="isShowPackage = false">返 回</el-button>
        </el-form-item>
    </el-dialog>

    <el-dialog title="司机配置" v-model="isDriverShow" width="50%">
        <div style="display: flex">
            <div style="flex: 1">
                <el-table
                        ref="multipleTable"
                        v-loading="loading"
                        :data="driverInfo"
                        style="width: 100%"
                        :border="option.border"
                        @select-all="handleSelect"
                        @select="handleSelect"
                >
                    <el-table-column
                            type="selection"
                            v-if="option.selection"
                            width="55"
                            align="center"
                    ></el-table-column>
                    <template v-for="(item, index) in option.columnDriverInfo">
                        <!-- table字段 -->
                        <el-table-column
                                v-if="item.hide !== true"
                                :prop="item.prop"
                                :label="item.label"
                                :width="item.width"
                                :key="index"
                                style="height: 50px"
                        >
                        </el-table-column>
                    </template>
                    <!-- 操作栏模块 -->
                </el-table>
            </div>
            <div style="flex: 1">
                <el-table
                        ref="table"
                        v-loading="loading"
                        :data="vehticleInfo"
                        style="width: 100%"
                        :border="option.border"
                >
                    <el-table-column type="expand" v-if="option.expand" align="center"></el-table-column>
                    <template v-for="(item, index) in option.columnVehicleInfo">
                        <!-- table字段 -->
                        <el-table-column
                                v-if="item.hide !== true"
                                :prop="item.prop"
                                :label="item.label"
                                :width="item.width"
                                :key="index"
                                style="height: 50px"
                        >
                        </el-table-column>
                    </template>
                    <!-- 操作栏模块 -->
                    <el-table-column label="预约数量" type="index" width="200px">
                        <template #="{ row }">
              <span>
                <el-button type="primary" text size="small" @click="moveUpVehictle(row)"
                >上移
                </el-button>
              </span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <el-form-item style="margin-left: 45%; margin-top: 10px">
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmDriver">确 定</el-button>
        <el-button @click="isDriverShow = false">取 消</el-button>
      </span>
        </el-form-item>
    </el-dialog>
</template>
<script>
  import { getDictionaryBiz } from '@/api/system/dict';
  import option from '@/option/distribution/distributionReservation';
  import { getListTeamInfo } from '@/api/basicdata/basicdataTeamGroup';
  import { deliveryBusinessTask, getDeliveryZeroOrderDetail } from '@/api/distribution/distributionReservation';
  import { getListUser } from '@/api/distribution/distributionStockup';
  import { getPostList } from '@/api/system/post';
  import { getListOwn } from '@/api/system/user';
  import { stockUpInfo } from '@/api/basicdata/basicdataGoodsArea';
  import { getVehicleList } from '@/api/basicdata/basicdataVehicle';
  import { getDriverList } from '@/api/basicdata/basicdataDriverArtery';//司机信息
  import {
    selectStockArticleInfoList,
    selectDiscussStockArticleInfoList, getZeroOrderDetail, getPackageListByStockArticleId
  } from '@/api/distribution/distributionStockArticle';
  import { getInventoryList } from '@/api/distribution/distributionStockList';
  import { getDeliveryList, updateDeliveryList,getPackageListByDeliveryIdAndOrderId} from '@/api/distribution/distributionDeliveryList';
  import { mapGetters } from 'vuex';
  import dayjs from 'dayjs';
  import { entryNum, updateEntryNum } from '@/api/distribution/distributionParcelNumber';
import { ElMessageBox } from 'element-plus'
import { ElMessage } from 'element-plus'
  export default {
    data() {
      return {
        cell:true,//车辆信息
        loading: true,
        height: 0,
        loading: false,
        error: null,
        form: {},
        driverForm: {},
        stockUpForm: {},
        waixieForm: {},
        data: [],
        datainfo: [], //添加的信息
        // 分页信息
        page: {
          currentPage: 1,
          pageSize: 30,
          total: 40
        },
        tableRef:null,//Ref表格实例
        query: {},
        aaa: true,
        bbb: false,
        option: option,
        deliveryTypeData: [],
        //配送类型字典列表
        resvervationStatusData: [],
        //备货状态
        stockupStatusData: [],
        //订单来源
        orderSourceData: [],
        //预约时段
        periodOfTimeData: [],
        //配送方式
        deliveryWayData: [],
        //服务内容
        addvalueServeTypeData: [],
        //基础车辆信息
        vehicleData: [],
        vehicleDatas: [],
        //叉车信息
        forkliftData: [],
        //班组信息
        loaderData: [],
        //备货区信息
        goodsAreaData: [],
        //部门信息
        deptId: '',
        //司机信息
        driverData: [],
        //装卸班组
        loadAndUnloadData: [],
        //装卸
        tripartiteSourceData: [],
        //装卸只能
        loadAndUnload: [],
        //车辆信息1
        vehicleIds: [],
        vehicleIdss: [],
        //配送司机信息
        deliveryDriver: [],
        //司机配置
        isDriverShow: false,
        //车辆表格信息
        driverInfo: [],
        //司机表格信息
        vehticleInfo: [],
        //主司机
        masterDriverName: '',
        //主车辆
        masterVehictleName: '',
        //司机配置选中行信息
        multipleSelection: [],
        //
        multipleTable: {},
        stockArticleTable: [],
        stockArticleList: [],
        driverList: [],
        vehticleList: [],
        packageList: [],
        //订单数据
        orderData: [],
        //库存品数据
        inventoryData: [],
        //
        selectionList: [],
        addvalue: {},
        //订单弹窗
        orderShow: false,
        //库存品弹窗
        stockListShow: false,
        //在库订单数据
        stockArticleInfo: [],
        //库存品信息列表
        inventoryInfo: [],
        //包件弹窗控制
        isShowPackage: false,
        //包件数据
        packageData: [],
        //班组职能
        loadAndUnload: [],
        zeroOrderShow:false,
        zeroOrderData:[],
        isrReservationEntry:false,
        //服务类型
        serveType: [],
        page: {
          currentPage: 1,
          pageSize: 30,
          total: 40
        },
        //外协数据来源
        tripartiteSourceData: [],
        deliveryListId: '',
        isDisable: false,
        checked: true,
        obj: {
          type: Object,
          default: () => ({})
        },
        isInitialized: false,
        isUpdate: false,
        BtnDisabled:false,//按钮禁止
      };
    },
    watch: {
      '$route.query.id': {
        handler(newVal, oldVal) {
          console.log(newVal, oldVal);
          if (!!this.$route.query.id) {
            this.fetchData();
            this.onLoad(this.page);
          }
          this.driverForm = {};
          this.vehicleIds = [];
          this.deliveryDriver = [];
        },
        deep: true,
        immediate: true
      }
    },
    created() {
      this.$watch(
        () => this.$route.params,
        () => {
          this.fetchData();
        },
        // 组件创建完后获取数据，
        // 此时 data 已经被 observed 了
        { immediate: true }
      );
      this.getDictionary();
      this.getFork();
      this.getTeam();
      this.getvehicleData();
      this.getDriverData();
    },
    computed: {
      ...mapGetters(['permission']),
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(',');
      }
    },

    mounted() {
      this.onLoad(this.page);
    },

    methods: {
      //查询叉车人员
      async getFork() {
        await getListUser().then(res => {
          //查询当前人信息
          console.log('查询当前人信息>>>', res.data.data);
          let fo = [];
          res.data.data.forEach(i => {
            let a = {
              dictKey: i.id,
              dictValue: i.realName
            };
            fo.push(a);
            if (!this.deptId) {
              this.deptId = i.deptId;
            }
          });
          this.forkliftData = fo;
        });
        // let ides = '';
        // let ide = {};
        // await getListUser().then(res => {
        //   console.log('res>>>', res.data.data);
        //   ides = res.data.data.tenantId;
        //   this.deptId = res.data.data.deptId;
        // });
        // await getPostList(ides).then(res => {
        //   console.log('>>>>', res.data.data);
        //   // this.forkliftData = res.data.data;
        //   res.data.data.forEach(i => {
        //     if (i.postName == '叉车') {
        //       ide = i;
        //     }
        //   });
        // });
        // // console.log("ied>>>>>",ide);
        // let params = {
        //   postId: ide.id, //岗位
        //   deptId: this.deptId //部门
        //   // roleId: '', //角色
        // };
        // getListOwn(Object.assign(params, this.query)).then(res => {
        //   // console.log(".............",res.data.data);
        //   let fo = [];
        //   res.data.data.forEach(i => {
        //     let a = {
        //       dictKey: i.id,
        //       dictValue: i.name
        //     };
        //     fo.push(a);
        //   });
        //   this.forkliftData = fo;
        // });
        await this.getStorageArea();
        await this.getTeam();
      },
      //查询班组
      async getTeam() {
        const info = JSON.parse(localStorage.getItem('TWMS-userInfo'))
        console.log('info >>>>>>>>', info);
        // let params = this.deptId;
        let params = info.content.dept_id;
        console.log('%%%%%%%%%', params);
        getListTeamInfo(params).then(res => {
          console.log('aaaaaaaaa', res.data.data);
          let fo = [];
          res.data.data.forEach(i => {
            let a = {
              dictKey: i.id,
              dictValue: i.groupName
            };
            fo.push(a);
          });
          this.loaderData = fo;
        });
      },
      //备货区
      async getStorageArea() {
        let params = this.deptId;
        console.log('^^^^^^^^^^^^^', params);
        stockUpInfo(params).then(res => {
          console.log('=========================》', res);
          let fo = [];
          res.data.data.forEach(i => {
            let v = {
              dictKey: i.id,
              dictValue: i.headline
            };
            fo.push(v);
          });
          this.goodsAreaData = fo;
        });
      },

      //查询司机信息
      getDriverData() {
        return new Promise((rv, rev) => {
          getDriverList(1, 10, '').then(res => {
            this.driverData = res.data.data;
            console.log('=============== 司机信息>', res.data.data);
            rv(res.data.data);
          });
        });
      },
      selectionChange(list) {
        //只要这个触发就认定为该包件进行了重新勾选，不论数据是否发生变化
        this.selectionList = list;
        this.packageListInfo=this.selectionList
        console.log(' this.selectionList = list', this.selectionList);

        this.orderData.forEach(item => {
          if (item.id === this.obj.id) {
            item.isUpdate = true;
          }
        });
        console.log('?????????????????', this.orderData);
        //这里就为当前选择的订单进行包件信息的添加
        // this.obj.
      },
      // 复选框事件
      selectionStockArticleChange(list) {
        console.log('selectionStockArticleChange', list);
        this.stockArticleList = list;
        // 新增选中信息
        this.datainfo = list;
        console.log(this.datainfo, 'datainfo');
        console.log(this.stockArticleList, '选中数据');
      },

      //查询车辆信息
      getvehicleData() {
        return new Promise((rv, rev) => {
          getVehicleList(1, 10, '').then(res => {
            this.vehicleData = res.data.data;
            console.log('^^^^^^^^^^^^^^^^车辆信息', res.data.data);
            rv(res.data.data);
          });
        });
      },
      fetchData() {
        this.error = this.post = null;
        this.loading = true;
        if (this.$route.query.id) {
          this.deliveryListId = this.$route.query.id;
        }
        this.loading = false;
      },
      sizeOrderChange(pageSize) {
        this.page.pageSize = pageSize;
        if (this.deliveryListId) {
          //这里的编辑需要进行特殊处理
          this.onLoadEditOrder(this.page, this.deliveryListId);
        } else {
          this.onLoadOrder(this.page);
        }
      },
      currentOrderChange(currentPage) {
        this.page.currentPage = currentPage;
        if (this.deliveryListId) {
          this.onLoadEditOrder(this.page, this.deliveryListId);
        } else {
          this.onLoadOrder(this.page);
        }
      },
      checkPackage(row, index) {
        console.log('>>>>>>>>>>>>', row, index);
        // return false;
      },
      viewDriverInfo() {
        console.log(this.driverInfo.length);
        console.log(this.vehticleInfo.length);
        if (this.driverList.length !== this.vehticleList.length) {
          this.$message({
            message: '司机车辆数量有误!!!',
            type: 'warning'
          });
          return;
        }
        this.isDriverShow = true;
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      /**
       * 在库录入
       * */
      entryNum(row){
        console.log("row------------->",row);
        this.obj = row;
        getZeroOrderDetail(row.id).then(res => {
          if (res.data.data != null) {
            this.zeroOrderData = res.data.data;
          }
        });
        this.zeroOrderShow = true;
        this.isrReservationEntry = false;
      },
      /**
       * 数量录入
       * */
      entryReservationNum(row){
        console.log("row------------->",row);
        this.obj = row;
        if (this.deliveryListId) {
          //查询零担计划数量详情
          console.log('order------------>', row.id);
          // getReservationZeroOrderDetail(this.deliveryListId, row.id).then(res => {
          getDeliveryZeroOrderDetail(this.deliveryListId, row.id).then(res => {
            let a = res.data.data;
            a.forEach(item=>{
              item.zeroOrderMax = (item.handQuantity - item.deliveryQuantity - item.outboundQuantity + item.reservationNum)
            })
            this.zeroOrderData = res.data.data;
            // console.log(res.data.data);
          });
        } else {
          getZeroOrderDetail(row.id).then(res => {
            if (res.data.data != null) {
              let a = res.data.data;
              a.forEach(item=>{
                item.zeroOrderMax = (item.handQuantity - item.deliveryQuantity - item.outboundQuantity)
              })
              this.zeroOrderData = res.data.data;
            }
          });
        }
        this.zeroOrderShow = true;
        this.isrReservationEntry = true;
      },
      /**
       * 修改零担在库数量
       * */
      onSubmitUpdateZeroOrder() {
        console.log('this.obj--------------------->', this.obj);
        console.log('this.zeroOrderData--------------------->', this.zeroOrderData);
        console.log('this.zeroOrderData--------------------->', this.zeroOrderData);
        this.isrReservationEntry = false;
        let a = this.zeroOrderData;
        if (a.length > 1) {
          let b = 0;
          //计算该品类已使用数量

          a.forEach(item => {
            b += item.number;
          });
          let f = a.every(item=>{
            console.log('this.number--------------------->', item.number);
            console.log('number--------------------->', (item.deliveryQuantity + item.outboundQuantity));
            if (item.number < (item.deliveryQuantity + item.outboundQuantity) || item.number > item.quantity){
              return false;
            }
            return true;
          })

          if (b > this.obj.handQuantity) {
            this.$message({
              type: 'error',
              message: '录入数量超过订单在库数量!'
            });
            return;
          }
          if (!f) {
            this.$message({
              type: 'error',
              message: '请检查修改数量!'
            });
            return;
          }
        }
        updateEntryNum(this.zeroOrderData).then(res=>{
          if (res) {
            this.$message({
              type: 'success',
              message: '操作成功'
            });
          }
        })
        this.zeroOrderShow = false;
        console.log('-------------->', this.zeroOrderData);
      },
      onSubmitZeroOrder() {
        if (this.isrReservationEntry) {
          //零担预约数量录入
          this.orderData.forEach(item => {
            if (this.obj.id === item.id) {
              item.parcelNumberVOS = this.zeroOrderData;
            }
          });
          console.log('this.zeroOrderData------------->', this.zeroOrderData);
          console.log('this.orderData------------->', this.orderData);
        } else {
          //在库数量录入
          let a = this.zeroOrderData;
          if (a.length > 0) {
            let n = 0;
            a.forEach(item => {
              n += item.number;
            });
            if (n > this.obj.handQuantity) {
              this.$message({
                type: 'error',
                message: '录入数量超过订单在库数量!'
              });
              return;
            }
            let b = a.every(item => {
              console.log('最大数量-------------->', (item.handQuantity + item.outboundQuantity + item.deliveryQuantity + item.number));
              if ((item.handQuantity + item.outboundQuantity + item.deliveryQuantity + item.number) > item.quantity) {
                return false;
              }
              return true;
            });
            console.log('----------------->', b);
            if (!b) {
              this.$message({
                type: 'error',
                message: '请输入正确数量!'
              });
              return;
            }
          }

          entryNum(this.zeroOrderData).then(res => {
            if (res) {
              this.$message({
                type: 'success',
                message: '操作成功'
              });
            }
          });
          console.log('this.zeroOrderData------------->', this.zeroOrderData);
        }

        this.zeroOrderShow = false;
      },
  // 表格选中项
  toggleSelection (val=true,data) {
  console.log('执行了此函数');
  //对表单进行循环把所有表格进行全部选中,或者通过IF对条件满足进行选中
    const setIn = setTimeout(() => {
      if(val){
       this.packageData.forEach((row, i) => {
        this.$refs.tableRef.toggleRowSelection(this.packageData[i], true)
      })
      }
      else{
      this.packageData.forEach((row, i) => {
        if(row.id==data[i]){
            this.$refs.tableRef.toggleRowSelection(this.packageData[i], true)
        }
      })
      }

      clearTimeout(setIn); //清除定时器
    }, 0);
},
      /**
       * 查看包件
       */
      viewStockArticlePackage(row) {

        //这里应该先对订单下的所有包件信息进行获取，然后结合查询出预约单下以选择的包件信息进行勾选状态的回显
        //查询该订单下所有的包件信息
        this.loading = true;
        this.obj = row;
        let page = this.page;
        console.log('++++++++++++', row);
        if (this.deliveryListId) {
          getPackageListByDeliveryIdAndOrderId(page.currentPage,page.pageSize,this.deliveryListId,row.id).then(res=>{
          console.log("getPackageListByDeliveryIdAndOrderId1--------------------->",res);
          this.packageData =  res.data.data.data.packageList
          console.log(this.packageData,'this.packageListInfo');
          console.log( res.data.data.data.reservationPackageList,' res.data.data.data.reservationPackageList');
          let reservationPackageList=[]
          res.data.data.data.reservationPackageList.forEach(val=>{
           reservationPackageList.push(val.id )  
          })
          this.toggleSelection(false,reservationPackageList)
          console.log(reservationPackageList,'reservationPackageList');
        })
          // //编辑
          // let params = {};
          // console.log('^^^^^^^^', row);
          // //这里订单的对象中应该存在三个数组，一个数组是该订单下的所有包件细信息
          // //一个数组是该订单被选择使用的包件信息
          // //还有一个就是正在操作的包件信息
          // let packageInfo = row.parcelListVOS;
          // if (row.packageList) {
          //   let packageListInfo = row.packageList;
          //   packageInfo.forEach((item, index) => {
          //     packageListInfo.forEach(p => {
          //       if (item.id === p.id) {
          //         this.$nextTick(() => {
          //           this.$refs.packageList.toggleRowSelection(this.packageData[index], true);
          //         });
          //       }
          //     });
          //   });
          // }
          // this.packageData = row.parcelListVOS;
        } else {
          getPackageListByStockArticleId(page.currentPage,page.pageSize,row.id).then(res=>{
            console.log("________--------------------->",res.data.data.records);
            this.packageData=res.data.data.records;
            this.packageListInfo=res.data.data.records
                      // 自动全选
           this.toggleSelection()
          console.log(this.selectionList,'勾选值');
          })
          // //新增
          // //默认打开包件信息，包件列表处于全选状态
          // let params = {};
          // this.packageData = row.parcelListVOS;
          // this.packageData.forEach((item, index) => {
          //   this.$nextTick(() => {
          //     this.$refs.packageList.toggleRowSelection(this.packageData[index], true);
          //   });
          // });
          // console.log('^^^^^^^^', row);

        }
        this.loading = false;
        this.isShowPackage = true;
      },
      checkOrder(row, index) {
        if (row.freezeStatus === '30' || row.freezeStatusName === '已冻结') {
          return false;
        } else {
          return true;
        }
        return false;
      },
      /**
       * 提交包件信息
       */
      onSubmitPackage() {
        //包件处于默认全选的状态这里不需要要求进行包件选择
        //如果这里用户进行全部包件的取消，那么这里会对订单下的所有包件进行添加，由后台完成

        //这里就需要对原来包件是否发生变化进行处理
        //如果发生变化该订单下的某一字段就会发生改变，后台根据该字段进行判断是否发生包件选择的变化
        console.log(this.obj.parcelListVOS);
        console.log('___________', this.obj);
        console.log(this.orderData,'orderdata=====');
        this.orderData.forEach(item => {
          if (item.id === this.obj.id) {
            item.packageListInfo = this.selectionList;
          }
        });
        console.log('**********', this.orderData);
        // if (this.selectionList.length ===this.obj.parcelListVOS.length){
        //   //这里就需要考虑，如果选中包件的数组长度和原来不同，那么包件信息必定发生变化
        //   //当包件长度一致需要判断包件数组的内容是否一致，然后进行字段的改变和赋值
        //
        //   console.log(this.obj);

        // }
        //这里就需要将具体的包件信息和订单进行关系绑定
        console.log('this.selectionList', this.selectionList);
        this.isShowPackage = false;
      },
      removeStockArticle(row) {
        this.orderData.forEach((item, index) => {
          if (item.id === row.id) {
            this.orderData.splice(index, 1);
          }
          console.log(item);
        });
        console.log('>>>>>>>>>>>>>>>row', row);
      },
      onSubmitInventory() {
        if (this.selectionList.length === 0) {
          this.$message.warning('请选择至少一条数据');
          return;
        }
        if (this.orderData.length) {
          this.selectionList.some(i => {
            let a = this.inventoryData.filter(ele => ele.id == i.id).length >= 1;
            if (!a) {
              this.inventoryData.push(i);
            }
          });
        } else {
          this.inventoryData = this.selectionList;
        }
        this.stockListShow = false;
      },
      // 添加按钮
      onSubmitOrder() {
        console.log('>>>>>>>>>>>>', this.stockArticleList);
        this.info = this.stockArticleList;
        console.log('>>>>>>>>orderData', this.orderData);
        const data = this.stockArticleList;
        const info = [];
        this.stockArticleInfo.forEach((item, index) => {
          this.stockArticleList.forEach(order => {
            // const newDate1 = this.orderData.map(item => { // map遍历本地数据
            //   if (this.orderList.find(o => o.id !== item.id)) { // 如果在接口数据中包含本地数据，则返回这条本地数据
            //     return item;
            // });
            //   }              info.push(order);
            //清理原来订单列表的订单数据
            info.push(order);
            this.stockArticleInfo.splice(index, 1);
          });
        });

        if (this.orderData.length >= 1) {
          let newDate1 = this.stockArticleList.map(item => {
            // map遍历本地数据
            if (this.orderData.find(o => o.id !== item.id)) {
              // 如果在接口数据中包含本地数据，则返回这条本地数据
              return item;
            }
          });
          console.log('newDate1-------------->', newDate1.length);
          if (newDate1.length >= 1) {
            console.log('newDate1-------------->', newDate1);
            newDate1.forEach(a => {
              this.orderData.push(a);
            });
          }
          console.log('this.orderData------------->', this.orderData);
        } else {
          this.orderData = this.stockArticleList;
        }
        // data.map(item=>{
        //   console.log(item);
        //     this.orderData.forEach(order=>{
        //       if (item.id !== order.id){
        //         this.orderData.push(item);
        //       }
        //     })
        // })
        // // this.orderData = info;
        console.log('+++++++++++++++', this.orderData);
        this.orderShow = false;
      },
      /**
       * 订单提交
       */
      onSubmitBusiness() {

        this.BtnDisabled=true
        setTimeout(() => {
          // 启用按钮
          this.BtnDisabled = false;
        }, 2000);
        if(!this.BtnDisabled){
          return
        }
        if (this.orderData.length === 0) {
          this.$message.warning('请选择订单');
          return;
        }
        if (this.deliveryListId) {
          let data = {};
          let tripartite = {};
          let stockup = {};
          let allocationInfo = [];
          //备货区数据构建
          if (this.stockUpForm.loader) {
            this.loaderData.forEach(a => {
              if (this.stockUpForm.loader === a.dictKey) {
                stockup.loaderName = a.dictValue;
                stockup.loaderId = a.dictKey;
              }
            });
          }
          if (this.stockUpForm.unloader) {
            this.loaderData.forEach(a => {
              if (this.stockUpForm.loader === a.dictKey) {
                stockup.unloaderName = a.dictValue;
                stockup.unloaderId = a.dictKey;
              }
            });
          }
          console.log('this.stockUpForm.forklift-------->', this.stockUpForm.forklift);
          this.forkliftData.forEach(b => {
            if (this.stockUpForm.forklift === b.dictKey) {
              stockup.forkliftName = b.dictValue;
              stockup.forkliftId = b.dictKey;
            }
          });

          this.goodsAreaData.forEach(c => {
            if (this.stockUpForm.goodsAreaId === c.dictKey) {
              stockup.goodsAreaId = c.dictKey;
              stockup.goodsAreaName = c.dictValue;
            }
          });

          if (this.stockUpForm.stockupDate) {
            stockup.stockupDate = this.stockUpForm.stockupDate;
          }
          if (this.stockUpForm.remarks) {
            data.remarks = this.stockUpForm.remarks;
          }
          if (this.stockUpForm.outboundDate) {
            stockup.outboundDate = this.stockUpForm.outboundDate;
          }
          // stockup.loadAndUnload = this.loadAndUnload.join(',');
          data.stockupInfo = stockup;
          //将服务类型转为数组
          if (this.serveType) {
            console.log('this.serveType---------->', this.serveType);
            let serve = Object.values(this.serveType);
            serve = serve.sort((a, b) => {
              return a - b;
            });
            this.stockUpForm.serveType = serve.join(',');
            console.log('this.stockUpForm.serveType----------->', this.stockUpForm.serveType);
          }
          //判断是否是三方配送
          if (this.waixieForm.tripartiteSource) {
            //三方配送数据构建
            if (this.waixieForm.driverName) {
              tripartite.driverName = this.waixieForm.driverName;
            }
            if (this.waixieForm.driverPhone) {
              tripartite.driverPhone = this.waixieForm.driverPhone;
            }
            if (this.waixieForm.vehicleNum) {
              tripartite.vehicleNum = this.waixieForm.vehicleNum;
            }
            if (this.waixieForm.deliveryFee) {
              tripartite.deliveryFee = this.waixieForm.deliveryFee;
            }
            if (this.waixieForm.tripartiteSource) {
              this.tripartiteSourceData.forEach(item => {
                if (this.waixieForm.tripartiteSource === item.dictKey) {
                  tripartite.distributionCompanyId = item.dictKey;
                  tripartite.distributionCompany = item.dictValue;
                }
              });
              data.tripartite = tripartite;
            }
          } else {
            //自主配送数据构建
            console.log('this.driverList', this.driverList);
            console.log('this.vehticleList', this.vehticleList);
            if (this.driverList.length !== this.vehticleList.length) {
              this.$message({
                message: '司机车辆数量有误!!!',
                type: 'warning'
              });
              return;
            } else {
              let info = [];
              for (let i = 0; i < this.driverInfo.length; i++) {
                let obj = {};
                obj.driverName = this.driverInfo[i].name;
                obj.driverPhone = this.driverInfo[i].phone;
                obj.driverId = this.driverInfo[i].id;
                obj.vehicleNub = this.vehticleInfo[i].vehicleNub;
                obj.vehicleId = this.vehticleInfo[i].id;
                info.push(obj);
                this.driverInfo[i].name;
              }
              allocationInfo = info;
            }
            console.log(allocationInfo);
            data.allocationInfo = allocationInfo;
          }
          data.masterDriverName = this.driverForm.masterDriverName;
          data.masterVehicleNub = this.driverForm.masterVehicleNub;
          data.stockArticle = this.orderData;
          let reservation = {};
          reservation.deliveryType = this.stockUpForm.deliveryType;
          reservation.deliveryWay = this.stockUpForm.deliveryWay;
          reservation.serveType = this.stockUpForm.serveType;
          reservation.otherFee = this.stockUpForm.otherFee;
          data.taskTime = this.stockUpForm.taskTime;
          data.reservation = reservation;
          data.id = this.deliveryListId;
          this.orderData.map((item, index) => {
            console.log('item=>', item);
            if (!item.packageListInfo) {
              item.packageListInfo = item.parcelListVOS;
            }
          });
          console.log('data>>>>>>>>>>>TTTTTT', data);
          updateDeliveryList(data).then(res => {
            this.$router.push({
              path: '/distribution/deliverylist/distributionDeliveryListdis'
            });
          });
        } else {
          let data = {};
          let stockup = {};
          let tripartite = {};
          let allocationInfo = [];
          //备货区数据构建
          if (this.stockUpForm.loader) {
            this.loaderData.forEach(a => {
              if (this.stockUpForm.loader === a.dictKey) {
                stockup.loaderName = a.dictValue;
                stockup.loaderId = a.dictKey;
              }
            });
          }
          if (this.stockUpForm.unloader) {
            this.loaderData.forEach(a => {
              if (this.stockUpForm.loader === a.dictKey) {
                stockup.unloaderName = a.dictValue;
                stockup.unloaderId = a.dictKey;
              }
            });
          }
          this.forkliftData.forEach(b => {
            if (this.stockUpForm.forklift === b.dictKey) {
              stockup.forkliftName = b.dictValue;
              stockup.forkliftId = b.dictKey;
            }
          });
          this.goodsAreaData.forEach(c => {
            if (this.stockUpForm.goodsAreaId === c.dictKey) {
              stockup.goodsAreaId = c.dictKey;
              stockup.goodsAreaName = c.dictValue;
            }
          });
          if (this.stockUpForm.stockupDate) {
            stockup.stockupDate = this.stockUpForm.stockupDate;
          }
          if (this.stockUpForm.remarks) {
            data.remarks = this.stockUpForm.remarks;
          }
          if (this.stockUpForm.outboundDate) {
            stockup.outboundDate = this.stockUpForm.outboundDate;
          }
          //将服务类型转为数组
          let serve = Object.values(this.serveType);
          serve = serve.sort((a, b) => {
            return a - b;
          });
          this.stockUpForm.serveType = serve.join(',');
          // stockup.loadAndUnload = this.loadAndUnload.join(',');
          //判断是否是三方配送
          if (this.waixieForm.tripartiteSource) {
            //三方配送数据构建
            if (this.waixieForm.driverName) {
              tripartite.driverName = this.waixieForm.driverName;
            }
            console.log('-------------->', this.waixieForm);
            if (this.waixieForm.driverPhone) {
              tripartite.driverPhone = this.waixieForm.driverPhone;
            }
            if (this.waixieForm.vehicleNum) {
              tripartite.vehicleNum = this.waixieForm.vehicleNum;
            }
            if (this.waixieForm.deliveryFee) {
              tripartite.deliveryFee = this.waixieForm.deliveryFee;
            }
            if (this.waixieForm.tripartiteSource) {
              this.tripartiteSourceData.forEach(item => {
                if (this.waixieForm.tripartiteSource === item.dictValue) {
                  tripartite.distributionCompanyId = item.dictKey;
                  tripartite.distributionCompany = item.dictValue;
                }
              });
              data.tripartite = tripartite;
            }
          } else {
            if( !this.driverForm.masterDriverName ){
          ElMessage({
          message: '没有选择配送司信息',
          type: 'warning',
          })
             return
            }
            if(!this.driverForm.masterVehicleNub){
          ElMessage({
           message: '没有选择配车辆信息',
          type: 'warning',
          })
             return
              }
            //自主配送数据构建
            if (this.driverList.length !== this.vehticleList.length) {
              this.$message({
                message: '司机车辆数量有误!!!',
                type: 'warning'
              });
              return;
            } else {
              let info = [];
              for (let i = 0; i < this.driverInfo.length; i++) {
                let obj = {};
                obj.driverName = this.driverInfo[i].name;
                obj.driverPhone = this.driverInfo[i].phone;
                obj.driverId = this.driverInfo[i].id;
                obj.vehicleNub = this.vehticleInfo[i].vehicleNub;
                obj.vehicleId = this.vehticleInfo[i].id;
                info.push(obj);
                this.driverInfo[i].name;
              }
              allocationInfo = info;
            }
          }
          data.stockup = stockup;
          data.masterDriverName = this.driverForm.masterDriverName;
          data.masterVehicleNub = this.driverForm.masterVehicleNub;
          data.allocationInfo = allocationInfo;
          data.stockArticle = this.orderData;
          let reservation = {};
          reservation.deliveryType = this.stockUpForm.deliveryType;
          reservation.deliveryWay = this.stockUpForm.deliveryWay;
          reservation.serveType = this.stockUpForm.serveType;
          reservation.otherFee = this.stockUpForm.otherFee;
          data.taskTime = this.stockUpForm.taskTime;
          data.reservation = reservation;
          //编辑
          //如果用户没有进行包件选择，这里对可选择的包件进行全选操作
          this.orderData.map((item, index) => {
            console.log('item=>', item);
            if (!item.packageListInfo) {
              item.packageListInfo = item.parcelListVOS;
            }
          });

          console.log('data>>>>>>>>>>>ssssssss', data);
          // 新增
          deliveryBusinessTask(data).then(res => {
            this.$router.push({
              path: '/distribution/deliverylist/distributionDeliveryListdis'
            });
          });
        }
      },
      changeVehicle(params) {
        console.log(params);
        this.vehticleList = params;
        let b = [];
        if (params) {
          this.vehicleData.forEach(item => {
            this.vehticleList.forEach(p => {
              if (p == item.id) {
                b.push(item);
                console.log(this.driverInfo);
              }
            });
            if (params[0] === item.id) {
              this.driverForm.masterVehicleNub = item.vehicleNub;
            }
          });
          this.vehticleInfo = b;
        }
      },

      changeDriver(params) {
        console.log(params.length,'lengs');
        if(params.length==0){
          this.cell=true
          return
        }
        this.cell=false
        console.log('params 司机触发事件---------->', params);
        this.driverList = params;
        console.log(this.driverData,'this.driverList');
        let a = [];
        if (params) {
          this.driverData.forEach(item => {
            if(params==item.id){
               console.log(item,'item');
               this.vehicleDatas=item.vehicleVOList
               console.log( this.vehicleDatas,'最新信息');
            }
            this.driverList.forEach(p => {
              if (p == item.id) {
                a.push(item);
                console.log(this.driverInfo,'driveringo');
                //TODO 这里发送车辆的请求，如果有车辆信息则进行车牌号的填充

                // console.log("------------>item",item);
                // console.log("---------------->",this.vehicleData);
              }
            });
            if (params[0] === item.id) {
              this.driverForm.masterDriverName = item.name;
            }
          });
          this.driverInfo = a;
        }
      },
      //上移
      moveUpVehictle(row) {
        let i = 0;
        this.vehticleInfo.forEach((item, index) => {
          if (item.id === row.id) {
            i = index;
          }
        });
        //获取当当前选中的下标，如果下标为第一个则不能上移
        if (i > 0) {
          let a = this.vehticleInfo[i - 1];
          this.vehticleInfo.splice(i - 1, 1);
          this.vehticleInfo.splice(i, 0, a);
        } else {
          this.$message({
            message: '已经是第一条，上移失败',
            type: 'warning'
          });
        }
        console.log(this.vehticleInfo);
      },
      handleSelect(selection, row) {
        // 阻止全选框原有逻辑
        this.$refs.multipleTable.clearSelection();
        if (row) {
          if (selection.length === 1) {
            this.multipleSelection = row;
            this.$refs.multipleTable.toggleRowSelection(row, true);
          } else if (selection.length > 1) {
            let a = {};
            selection.forEach((s, index) => {
              if (s.id === row.id) {
                selection.splice(index, 1);
                a = s;
              }
            });
            this.multipleSelection = selection;
            this.$refs.multipleTable.toggleRowSelection(a, true);
          }
        }
      },
      confirmDriver() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请选择至少一条数据');
          return;
        }
        console.log('this.adada', this.multipleSelection);
        this.isDriverShow = false;
        //获取到表格的行坐标
        let a = 0;
        this.driverInfo.forEach((item, index) => {
          if (item.id === this.multipleSelection.id) {
            a = index;
          }
        });
        this.driverForm.masterDriverName = this.driverInfo[a].name;
        this.driverForm.masterVehicleNub = this.vehticleInfo[a].vehicleNub;
      },
      // //数据字典数据获取
      getDictionary() {
        getDictionaryBiz('addvalue_serve_type').then(res => {
          this.addvalueServeTypeData = res.data.data;
        });
        // getDictionaryBiz('load_and_unload').then(res => {
        //   this.loadAndUnloadData = res.data.data;
        // });
        getDictionaryBiz('delivery_way').then(res => {
          this.deliveryWayData = res.data.data;
        });
        //三方外协来源
        getDictionaryBiz('tripartite_source').then(res => {
          this.tripartiteSourceData = res.data.data;
        });
      },
      ccc() {
        if (this.deliveryListId) {
          //清空司机、车辆信息
          this.waixieForm.tripartiteSource = '';
          this.waixieForm.driverName = '';
          this.waixieForm.driverPhone = '';
          this.waixieForm.vehicleNum = '';
          this.waixieForm.deliveryFee = '';
        } else {
          // this.loadAndUnload = [];
          this.serveType = [];
          this.waixieForm = {};
        }
        this.aaa = true;
        this.bbb = false;
        this.stockUpForm.deliveryType = '1';
        this.stockUpForm.deliveryWay = '10';
        // this.loadAndUnload = ['1', '2'];
        this.stockUpForm.otherFee = 0;
        this.stockUpForm.taskTime = dayjs().format('YYYY-MM-DD');
        this.stockUpForm.stockupDate = dayjs().format('YYYY-MM-DD HH:mm:ss');
        this.stockUpForm.taskTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
      },
      ddd() {
        if (this.deliveryListId) {
          this.vehicleIds = [];
          this.deliveryDriver = [];
          this.driverForm.masterDriverName = '';
          this.driverForm.masterVehicleNub = '';
        } else {
          // this.loadAndUnload = [];
          this.serveType = [];
          this.waixieForm = {};
        }
        this.aaa = false;
        this.bbb = true;
        this.stockUpForm.deliveryType = '1';
        this.stockUpForm.deliveryWay = '10';
        // this.loadAndUnload = ['1', '2'];
        this.stockUpForm.otherFee = 0;
        this.stockUpForm.taskTime = dayjs().format('YYYY-MM-DD');
        this.stockUpForm.stockupDate = dayjs().format('YYYY-MM-DD HH:mm:ss');
        this.stockUpForm.taskTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
      },
      handleAddOrder() {
        //TODO 这里还缺少对于订单状态的筛选条件
        this.query.typeService = 1;
        this.query.genre = '1';
        const page = this.page;
        this.query = {};
        //初始化新增订单数据
        this.onLoadOrder(page);
        this.query = {};
        this.loading = false;
        this.orderShow = true;
      },
      searchReset() {
        this.query = {
          typeService: 1,
          genre: '1'
        };
        this.searchChange();
      },
      // selectDiscussStockArticle(arg,params={}){
      //   this.query.typeService = 1;
      //   this.query.genre = '1';
      //   const page = arg;
      //   selectDiscussStockArticleInfoList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
      //     console.log("----------------------------->",res.data.data);
      //     const data = res.data.data;
      //     // this.page.total = data.total;
      //     this.stockArticleInfo = data.records;
      //     this.stockArticleInfo.forEach((item, index) => {
      //       if (this.orderData) {
      //         this.orderData.forEach(a => {
      //           if (item.id === a.id) {
      //             this.$nextTick(() => {
      //               this.$refs.stockArticleTable.toggleRowSelection(this.stockArticleInfo[index], true);
      //             });
      //             console.log("item---------------->",item);
      //             this.checkOrder(item,index)
      //           }
      //         });
      //       }
      //     });
      //     this.page.total = data.total;
      //   });
      // },
      searchChange() {
        let params = {};
        this.query.typeService = 1;
        this.query.genre = '1';
        console.log('query------------->', this.query);
        const page = this.page;
        this.onLoadOrder(page);
        // selectStockArticleInfoList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        //   console.log('------------------->', res);
        //   const data = res.data.data;
        //   this.stockArticleInfo = data.records;
        //   if (this.orderData) {
        //     this.stockArticleInfo.forEach((item, index) => {
        //       this.orderData.forEach(order => {
        //         if (item.id === order.id) {
        //           console.log('----------->');
        //           this.$nextTick(() => {
        //             this.$refs.stockArticleTable.toggleRowSelection(this.stockArticleInfo[index], true);
        //           });
        //         }
        //       });
        //     });
        //   }
        // });
        // selectStockArticleAndParcel(Object.assign(params,this.query)).then(res=>{
        //   console.log("res------------>",res.data.data);
        //   const data = res.data.data
        //   this.stockArticleInfo = data;
        //   if (this.deliveryListId){
        //     this.stockArticleInfo.forEach((item,index)=>{
        //       this.orderData.forEach(order=>{
        //         if (item.id === order.id){
        //           console.log("----------->");
        //           this.$nextTick(() => {
        //             this.$refs.stockArticleTable.toggleRowSelection(this.stockArticleInfo[index], true);
        //           })
        //         }
        //       })
        //     })
        //   }
        // })
      },
      handleAddInventory() {
        this.form.deliveryType = '1';
        let params = {};
        let page = this.page;
        getInventoryList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(
          res => {
            const inventoryList = res.data.data;
            console.log('>>>>>>>>>>', inventoryList);
            inventoryList.records.forEach(item => {
              item.reservationNum = '0';
            });
            this.page.total = inventoryList.total;
            this.inventoryInfo = inventoryList.records;
            this.loading = false;
            this.selectionClear();
          }
        );
        this.selectionList = [];
        this.stockListShow = true;
      },
      selectionClear() {
        this.selectionList = [];
        this.query = {};
      },
      onLoadEditOrder(arg, deliveryListId, params = {}) {
        this.query.typeService = 1;
        this.query.genre = '1';
        const page = arg;
        const id = deliveryListId;
        selectDiscussStockArticleInfoList(
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.query),
          id
        ).then(res => {
          console.log('----------------------------->', res.data.data);
          const data = res.data.data;
          this.page.total = data.total;
          this.stockArticleInfo = data.records;
          this.stockArticleInfo.forEach((item, index) => {
            if (this.orderData) {
              this.orderData.forEach(a => {
                if (item.id === a.id) {
                  this.$nextTick(() => {
                    this.$refs.stockArticleTable.toggleRowSelection(
                      this.stockArticleInfo[index],
                      true
                    );
                  });
                  console.log('item---------------->', item);
                  this.checkOrder(item, index);
                }
              });
            }
          });
          // this.page.total = data.total;
        });
      },
      onLoadOrder(arg, params = {}) {
        this.query.typeService = 1;
        this.query.genre = '1';
        const page = arg;
        let a = [];
        if (this.orderData) {
          this.orderData.forEach(item => {
            a.push(item.id);
          });
        }
        this.query.orderIds = a.join(',');
        selectStockArticleInfoList(
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.query)
        ).then(res => {
          console.log(res.data.data);
          const data = res.data.data;
          // this.page.total = data.total;
          this.stockArticleInfo = data.records;
          this.stockArticleInfo.forEach((item, index) => {
            //检查订单是否冻结
            this.checkOrder(item, index);
          });
          this.page.total = data.total;
        });
      },
      async onLoad(page, params = {}) {
        this.stockUpForm.deliveryType = '1';
        console.log('》》》》》》》》》》》》》》》', this.deliveryListId);
        if (this.deliveryListId) {
          getDeliveryList(this.deliveryListId).then(async res => {
            let data = res.data.data;
            Object.assign(this.stockUpForm, data.reservationInfo);
            Object.assign(this.stockUpForm, data.stockupInfo);
            this.stockUpForm.deliveryType = '1';
            // this.stockUpForm.deliveryWay = data.reservationInfo.deliveryWay;
            // this.serveType = data.reservationInfo.serveType.split(',');
            // if (data.stockupInfo) {
            //   this.loadAndUnload = data.stockupInfo.teamResponsibility.split(',');
            // }
            // data.deliverySelfVO
            this.stockUpForm.loader = data.loadingTeamId;
            this.stockUpForm.unloader = data.unloadingTeamId;
            this.stockUpForm.forklift = data.stockupInfo.forkliftId;
            this.stockUpForm.outboundDate = data.stockupInfo.outboundDate;
            this.stockUpForm.remarks = data.remarks;
            this.stockUpForm.taskTime = data.taskTime;
            data.stockArticleList.forEach(item => {
              if (item.packageList) {
                item.packageList = item.packageList;
                item.packageListInfo = item.packageList;
              }
            });
            this.orderData = data.stockArticleList;
            // if (data.teamResponsibility) {
            //   this.loadAndUnload = data.teamResponsibility.split(',');
            // }
            console.log('data.kind', data.kind);
            if (data.kind === '1') {
              //自主配送
              let self = data.deliverySelfVO;
              let vehicle = await this.getvehicleData();
              console.log('___________________-->', vehicle);
              let driver = await this.getDriverData();
              let a = [];
              let b = [];
              let vehicleInfo = [];
              vehicle.forEach(item => {
                self.forEach(s => {
                  if (item.id === s.vehicleId) {
                    a.push(s.vehicleId);
                    vehicleInfo.push(item);
                  }
                  if (s.isMaster === 2) {
                    this.driverForm.masterVehicleNub = s.vehicleNub;
                  }
                });
              });
              this.vehticleList = a;
              this.vehicleIds = a;
              console.log(' this.vehicleIds', this.vehicleIds);
              this.vehticleInfo = vehicleInfo;
              let driverInfo = [];
              driver.forEach(item => {
                self.forEach(s => {
                  if (item.id === s.driverId) {
                    b.push(s.driverId);
                    driverInfo.push(item);
                  }
                  if (s.isMaster === 2) {
                    this.driverForm.masterDriverName = s.driverName;
                  }
                });
              });
              this.deliveryDriver = b;
              this.driverList = b;
              this.driverInfo = driverInfo;
            } else {
              let deliveryTripartiteVO = data.deliveryTripartiteVO;
              this.aaa = false;
              this.bbb = true;
              this.waixieForm.tripartiteSource = data.distributionCompanyId;
              console.log(
                'distributionCompanyId---------------->',
                deliveryTripartiteVO.distributionCompanyId
              );
              console.log('deliveryTripartiteVO---------------->', deliveryTripartiteVO);
              this.waixieForm.driverName = deliveryTripartiteVO.driverName;
              this.waixieForm.vehicleNum = deliveryTripartiteVO.vehicleNum;
              this.waixieForm.driverPhone = deliveryTripartiteVO.driverPhone;
              this.waixieForm.deliveryFee = deliveryTripartiteVO.deliveryFee;
              //外协配送
            }
            console.log('-------------->', res.data.data);
          });
          this.isDisable = true;
        } else {
          this.stockUpForm.deliveryType = '1';
          this.stockUpForm.deliveryWay = '10';
          // this.loadAndUnload = ['1', '2'];
          this.stockUpForm.otherFee = 0;
          this.stockUpForm.taskTime = dayjs().format('YYYY-MM-DD');
          this.stockUpForm.stockupDate = dayjs().format('YYYY-MM-DD HH:mm:ss');
          this.stockUpForm.outboundDate = dayjs().format('YYYY-MM-DD HH:mm:ss');
        }
        this.loading = false;
      }
    }
  };
</script>

<style lang="scss" scoped>
    .head_top {
        width: 100%;
        display: flex;
        align-items: center;
        background-color: #ffffff;
        // border-bottom: 1px solid rgb(228, 228, 228);
        padding-left: 10px;

        > .buts {
            padding: 10px 20px;
            cursor: pointer;
            margin-right: 10px;
            font-size: 18px;
            border-bottom: 4px solid #ffffff;
            // background-color: #ffffff;
        }

        .check {
            color: #d3832a;
            border-bottom: 4px solid #d3832a;
        }
    }

    .minaxbox {
        display: flex;
        flex-direction: column;

        .tophed {
            display: flex;
            flex-wrap: wrap;
        }
    }

    .head_top {
        justify-content: flex-start;
    }

    :deep(.el-tag) {
        background-color: transparent !important;
        border-bottom: 1px solid #eeeeee;
        width: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    .has-prefix {
        width: 100%;
    }

    :deep(.el-select__input) {
        display: none;
    }

    :deep(.has-prefix) {
        width: 100% !important;
    }

    :deep(.el-date-picker) {
    }

    :deep(.el-date-picker) {
        width: 500px !important;
    }

    .el-date-picker {
        width: auto !important;
    }

    .el-date-table {
        margin-left: 16%;
    }

    .addbtn {
        margin-bottom: 20px;
        border: 1px solid #172e60;
        width: 54px;
        color: #172e60;
    }

    .addbtn:hover {
        border: 1px solid #172e60 !important;
        color: #172e60;
    }

    .addbtn:active {
        border: 1px solid #172e60 !important;
        color: #172e60;
    }

    :deep(.el-table-column--selection) {
        .cell {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
    .clsj{
      display: flex;
      align-items: flex-start;
      color: #606266;
      font-size: 14px;
       margin-left: 5px;
      cursor: pointer;
        .ck{
          height: 30px;
          display:flex;
          align-items: center;
          justify-content:center;
        }
      .el-form-item{
      margin-right:0;
      }
    }
</style>
