<!--
@name: 待调度
@author: 张泽贤
@time: 2022-04-13
@doc: PROLOG_UPCloudSolutionForTMS__v1.2.1_调度管理_1.2.2


shipbillMapBtn,运单地图
groupShipbillMapBtn,分组运单地图
lineMatchBtn,线路匹配
schedulingBtn,调度
packetSchedulingBtn,分组调度
policySplitBtn,策略拆分
policySchedulingBtn,策略调度
transitBtn,中转
smartTransitBtn,策略中转
mapPase,地址解析
export,导出
location,定位
print,打印

-->

<template>
  <div class="pages">
    <settingGroudModal :fieldOptions="options.GROUP_DISPATCH_NEW" @update="(data, name) => { options.GROUP_CONFIG = data; defaultGroupName = name }" :visible.sync="visibleSystemGroup"/>
    <p-spin :spinning="spinning" v-if="!editType" v-show="toggleType=='main'">
      <p-card style="margin-bottom: 10px">
        <p-form-model ref="formTarget"  @submit="handelSubmit" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" class="plg-grid-from">
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="货主">
                <p-search-modal v-bind="$data.$formItems.consignorAttr" :value="form.cargoOwnerName"  @change="(...args) => onFormChange('cargoOwner', form, ...args)"  />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="订单号">
                <p-input :value="form.orderNo"  @blur="event=> form.orderNo=event.target.value"/>
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="运单号">
                <p-input  :value="form.shipbillNo" @blur="event=> form.shipbillNo=event.target.value"/>
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="业务类型">
                <p-select v-model="form.orderBusinessType" :options="options.ORDER_BUSINESS_TYPE" allowClear />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="预计提货时间" >
                <p-range-picker v-model="estimatedPickupTime" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="预计送达时间" >
                <p-range-picker v-model="estimatedDeliveryTime" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="订单下单日期" >
                <p-range-picker v-model="orderDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="创建时间" >
                <p-range-picker v-model="createDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="始发地">
                <areaTree :areaId="form.shipperAdministrativeAreas" @getAreaChange="(value) => getAreaChange('shipperAdministrativeAreas', value)"></areaTree>
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="目的地">
                <areaTree :areaId="form.administrativeAreas" @getAreaChange="(value) => getAreaChange('administrativeAreas', value)"></areaTree>
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="线路">
                <p-search-modal v-bind="$data.$formItems.lineAttr"  :value="form.lineName" @change="(...args) => onFormChange('line', form, ...args)"  />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="收货方位置">
                <p-select v-model="form.consigneeLocation" :options="options.CONSIGNEE_LOCATION" allowClear />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="发货方位置">
                <p-select v-model="form.shipperLocation" :options="options.SHIPPER_LOCATION" allowClear />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="记录标记语">
                <p-input :value="form.recordTagWord"  @blur="event=>form.recordTagWord=event.target.value" />
              </p-form-model-item>
            </a-col>
            <!-- <a-col :span="6">
              <p-form-model-item label="收货方详细地址">
                <p-input :value="form.consigneeAddress "  @blur="event=>form.consigneeAddress =event.target.value" />
              </p-form-model-item>
            </a-col> -->
            <a-col :span="6">
              <p-form-model-item label="承运商">
                <p-search-modal v-bind="carrierAttr"  :value="form.carrierName" @ok="(...args) => onFormChange('carriers', form, ...args)"  />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: right">
                <a-space>
                  <p-button type="primary" html-type="submit"  icon="search">查询</p-button>
                  <p-button @click="onReset">重置</p-button>
                  <!-- <p-button type="primary" @click="onSeniorSearch">高级查询</p-button> -->
                </a-space>
              </p-form-model-item>
            </a-col>
          </a-row>
        </p-form-model>
      </p-card>
      <!-- :bodyStyle="{height:'480px'}" -->
      <p-card style="margin-bottom: 10px" >
        <a-space slot="title">
          <span>运单信息</span>
          <p-button v-action:directionBtns :type="!form.lineDirection?'primary':'default'"  @click="() =>{form.lineDirection = null,onSearch()} ">全部</p-button>
          <p-button v-action:directionBtns :type="form.lineDirection==10?'primary':'default'" @click="() =>{form.lineDirection = 10,onSearch()}" >正向</p-button>
          <p-button v-action:directionBtns :type="form.lineDirection==20?'primary':'default'" @click="() =>{form.lineDirection = 20,onSearch()} ">逆向</p-button>
        </a-space>
        <a-space slot="extra">
          <p-button type="primary" v-action:shipbillMapBtn @click="onWaybillMap">运单地图</p-button>
          <a-dropdown-button :disabled="!planGroupDimensionList.length" v-action:planSchedulingBtn type="primary" @click.stop="onPlan" >
              计划调度
              <a-radio-group slot="overlay">
                <ul class="dropdown-mini-menu ant-menu ant-menu-inline ant-menu-root ant-menu-light">
                  <li class="ant-menu-item" style="padding-left:10px"  v-for="(item,index) in options.GROUP_DISPATCH_PLAN" :key="index">
                    <a-checkbox
                    :name="item.value"
                    @change="(e)=>{item.checked=e.target.checked}"
                    :defaultChecked="item.checked">
                    {{ item.label }}</a-checkbox>
                  </li>
                </ul>
              <!-- <a-menu class="dropdown-mini-menu" mode="inline">
                <a-menu-item style="padding-left:10px"  v-for="(item,index) in options.GROUP_DISPATCH_PLAN" :key="index">
                  <a-checkbox
                    :name="item.value"
                    @change="(e)=>{item.checked=e.target.checked}"
                    :defaultChecked="item.checked">
                    {{ item.label }}</a-checkbox>
                </a-menu-item>


              </a-menu> -->
            </a-radio-group>

          </a-dropdown-button>
          <p-button type="primary" v-action:schedulingBtn :disabled="!selectedRowKeys.length" @click="onSchedule('schedule')">调度</p-button>
          <a-dropdown-button v-action:packetSchedulingBtn type="primary" @click="handleSystemGroupClick" >
            {{defaultGroupName?'"'+defaultGroupName+'"默认':'暂无默认分组'}}
            <a-radio-group slot="overlay">
              <a-menu class="dropdown-mini-menu" mode="inline">
                <a-sub-menu key="sub1" >
                  <span slot="title">分组配置</span>
                  <a-menu-item v-for="(item) in options.GROUP_CONFIG" :key="item.groupName">
                  <a-checkbox
                    :name="item.groupName"
                    @change="handleMenuClick($event,'sub1')"
                    :checked="groupName===item.groupName">
                    {{ item.groupName }}</a-checkbox>
                </a-menu-item>
              </a-sub-menu>
                <a-sub-menu key="sub2">
                  <span slot="title">类型条件</span>
                  <a-menu-item v-for="(item) in options.GROUP_DISPATCH_NEW" :key="item.value">
                  <a-checkbox
                  :checked="groupDimensionList.includes(item.value)"
                  @change="handleMenuClick($event,'sub2',item.value)" >{{ item.label }}</a-checkbox>
                </a-menu-item>
              </a-sub-menu>
                <a-menu-item style="margin-bottom:6px;padding-left:8px">
                  <a-space>
                    <a-button @click.stop="settingGroupClick" >设置</a-button>
                    <a-button type="primary"  @click.stop="onSystemGroup" :disabled="!groupDimensionList.length&&!groupName" >确定</a-button>
                  </a-space>
                 </a-menu-item>
              </a-menu>
          </a-radio-group>
          </a-dropdown-button>
          <p-button type="primary"  v-action:lineMatchBtn  @click="onLineMatch">线路匹配</p-button>
          <p-button type="primary"  v-action:policySplitBtn :disabled="!selectedRowKeys.length" @click="onPolicySplit">策略拆分</p-button>
          <p-button type="primary"  v-action:policySchedulingBtn :disabled="!selectedRowKeys.length" @click="onPolicyScheduling">策略调度</p-button>
          <p-button type="primary" v-action:transitBtn :disabled="!selectedRowKeys.length" @click="onTransit">中转</p-button>
          <p-button type="primary" v-action:smartTransitBtn :disabled="!selectedRowKeys.length" @click="onSmartTransit">策略中转</p-button>
          <a-dropdown>
              <a-menu slot="overlay">
                <a-menu-item type="link" key="1" v-action:mapParse :disabled="!selectedRowKeys.length">
                  <p-button type="link" @click="mapPase" :disabled="!selectedRowKeys.length">地址解析</p-button>
                </a-menu-item>
                <a-menu-item key="2" v-action:export>
                  <export-button
                    type="link"
                    :ids="selectedRowKeys"
                    :pages="mainPages"
                    :getSearchValue="() => listParams"
                    downloadFileName="待调度"
                    :allUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/pending_dispatch/export_all_detail'"
                    :currentUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/pending_dispatch/export_current_page_detail'"
                    :selectUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/pending_dispatch/export_select_line_detail'"
                    >导出</export-button
                  >
                </a-menu-item>
                <a-menu-item type="link" key="4"  v-action:location>
                  <p-button type="link" @click="onLocation" :disabled="selectedRowKeys.length === 0">定位</p-button>
                </a-menu-item>
                <a-menu-item type="link" key="3" v-action:print>
                  <p-button type="link" :disabled="!selectedRowKeys.length">打印</p-button>
                </a-menu-item>
              </a-menu>
            <a-button>更多</a-button>
          </a-dropdown>
        </a-space>


        <t-table
          ref="masterTable"
          dragle
          bordered
          rowSelectFixed
          :customCell="customRow"
          @selectChange="selectChange"
          :extendedObjectCode="'15'"
          row-key="shipbillId"
          :id="$route.meta.menuId + '_pendingScheduled'"
          :scroll="{ x: true}"
          :vScrollY="{ enabled:true}"
          :vScrollX="{ enabled:true}"
          :columns="mx_columns"
          :data-source="dataSource"
          :remote-url="listRemoteUrl"
          :remoteData="listParams"
          :rowSelectType="2"
          @clickRow="masterClickRow"
          :sign="true"
          :doneBefore="doneBefore"
          :attachFooter="[
            { key: 'totalPcs' },
            { key: 'totalVolume' },
            { key: 'totalWeight' },
          ]"
        >
          <template slot="operation" slot-scope="text, record">
            <a-space>
              <a :style="record.colorTagFontColor&&{color: record.colorTagFontColor}" @click.stop="toView(record)">查看</a>
              <a :style="record.colorTagFontColor&&{color: record.colorTagFontColor}" v-action:split @click.stop="toSplit(record)">拆分</a>
              <a :style="record.colorTagFontColor&&{color: record.colorTagFontColor}" @click.stop="toTransit(record)">中转</a>
              <a :style="!disRevoke(record)&&record.colorTagFontColor&&{color: record.colorTagFontColor}" @click.stop="toRevoke(record)" :disabled="disRevoke(record)">撤销</a>
              <a :style="record.colorTagFontColor&&{color: record.colorTagFontColor}" @click.stop="toPrint(record)" v-action:print>打印</a>
            </a-space>
          </template>
        </t-table>
      </p-card>
      <a-row :gutter="10">
        <a-col :span="12">
          <p-card title="商品信息" :bodyStyle="{minHeight:'300px'}">
            <t-table
              ref="goodsTable"
              dragle
              bordered
              customScrollbar
              :extendedObjectCode="'17'"
              row-key="id"
              :id="$route.meta.menuId + '_goodsTable'"
              :scroll="{ x: true}"
             :vScrollX="{enabled:false}"
             :vScrollY="{enabled:true,rows:4}"
              :columns="goods_columns"
              :data-source="goodsDataSource"
              :remote-url="goodsListRemoteUrl"
              :remoteData="goodsListParams"
              :rowSelectType="false"
              @selectChange="(selectKey, selectData)=>goodsSelectedRowKeys=selectKey"
              :autoLoad="false"
              @clickRow="goodsClickRow"
            >
            </t-table>
          </p-card>
        </a-col>
        <a-col :span="12">
          <p-card title="包裹信息"  :bodyStyle="{minHeight:'300px'}">
            <t-table
              ref="packTable"
              dragle
              customScrollbar
              bordered
              row-key="id"
              :id="$route.meta.menuId + '_packTable'"
              :scroll="{ x: true}"
              :vScrollX="{enabled:false}"
              :vScrollY="{enabled:true,rows:4}"
              :columns="pack_columns"
              :data-source="packDataSource"
              :remote-url="packListRemoteUrl"
              :remoteData="packListParams"
              :rowSelectType="false"
              @selectChange="(selectKey, selectData)=>packSelectedRowKeys=selectKey"
              :autoLoad="false"
              @clickRow="packClickRow"
            >
            </t-table>
          </p-card>
        </a-col>
      </a-row>
    </p-spin>

    <!-- 地址解析 -->
    <!-- <addressAnalysis v-if="editType === 'address'" :searchParams="addressSearchData" @back="editType = ''"></addressAnalysis> -->
    <addressAnalysis
      :showType="addressAnalysisShow"
      rowKey="shipbillId"
      :remoteUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/pending_dispatch/address_resolution/page'"
      :saveUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/pending_dispatch/parse_address'"
      :searchParams="addressSearchData"
      @back="addressBack"
    />

    <!-- 查看 -->
    <edit v-show="editType === 'view'"  parcelTable :options="options" :record="editId ? { shipbillId: editId } : null" :formExtendedField="formExtendedField" @back="editType = preverType"></edit>

    <!-- 运单地图 -->
    <waybillMap v-if="editType === 'map'" :isPacketScheduling="true" :searchData="waybillMap_serchData" @back="editType = ''" :options="options" :shipbillIdList="selectedRowKeys" :orderList="selectedRowData" :mextendedField_list="mextendedField_list"></waybillMap>

    <!-- 调度 -->
    <schedule
      :columns="mx_columns"
      :customRow="customRow"
      :lineDirection="form.lineDirection"
      :carrierStrategyForm="carrierStrategyForm"
      v-if="editType === 'schedule'"
      :orderList="selectedRowData"
      :mextendedField_list="tableExtendedField"
      :options="options"
      :shipbillIdList="selectedRowKeys"
      @back="handleBack"
      :groupDimensionList="groupDimensionList"
      :defaultGroupName="defaultGroupName"
      :groupName="groupName"
      @onPacketScheduling="onPacketScheduling"
      @visibleSettingGroup="(v)=>{visibleSystemGroup=true}"
      @menuClick="handleMenuClick"
    ></schedule>
    <!-- @计划调度 -->
    <planDispatch
    v-if="toggleType === 'planDispatch'"
    @back="(name,isReload)=>toggleType = name"
    :groupDimensionList="planGroupDimensionList"
    :options="options"

    />
    <!-- 分组调度 -->
    <packetScheduling
     :SELECT_GROUP_CONFIG="SELECT_GROUP_CONFIG"
     :sysList="sysList"
      v-if="editType === 'packetScheduling'"
      :orderList="selectedRowData"
      :groupItemNames="groupItemNames"
      :mextendedField_list="mextendedField_list"
      :options="options"
      :selectSystemGroup="groupDimensionList"
      :groupDimensionLabel="groupDimensionLabel"
      @back="editType = ''"
      @updateGroupList="updateGroupList"
    >
  </packetScheduling>

    <!-- 中转 -->
    <transit v-if="editType === 'transit'" :shipbillIdList="selectedRowKeys" @back="editType = ''"></transit>

    <!-- 拆分 -->
    <split v-if="editType === 'split'" :selectedRow="selectedRow" @back="editType = ''"></split>

    <!-- 策略拆分 -->
    <p-modal title="策略拆分" width="80%" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="visible = false">
      <div v-for="(item, index) in strategySplitMatchingDTOS" :key="index">
        <p-form-model :model="item" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" class="plg-grid-from" :rules="rules">
          <a-row>
            <a-col :span="24">
              <p-form-model-item :label="'运单号 ' + item.shipbillId" prop="strategy">
                <p-radio-group v-model="item.strategy" :options="item.strategyEnums" />
                <!-- <p-select v-model="form.strategy" :options="item.strategyEnums" /> -->
              </p-form-model-item>
            </a-col>
          </a-row>
        </p-form-model>
      </div>
    </p-modal>
  </div>
</template>

<script>
import { initDictionary, resultExtendedField } from '@/blocks/utils';
import edit from '@/blocks/components/orderView/index.orderView.vue';
import addressAnalysis from '@/views/TMS/order/orderManage/model/addressAnalysis/addressAnalysis.index.vue';
import schedule from '@/blocks/components/scheduling/schedule/index.vue';
import planDispatch from './modules/planDispatch';
import packetScheduling from '@/blocks/components/scheduling/packetScheduling/index.vue';
import { UPCLOUD_RDC_TMS_BUSINESS_SERVICE } from '@/config/serviceSettings.js';
import exportButton from '@/blocks/components/export-modal/modal.index.vue';
import { setMainColumns, setGoodsColums, setPackColums,customRow } from '@/blocks/components/scheduling/js/table/tableConfig.js';
import areaTree from '@/blocks/components/formConfig/index.areaTree.multiple.vue'

import {
  listRemoteUrl,
  page_detail_item,
  page_package_item,
  page_detail_package,
  page_item_package,
  Revoke,
  viewUrl,
  smart_split,
  smart_split_strategy,
  carrier_dispatch_strategy,
  sys_group_query,
  smart_transfer,
  query_dispatch_strategy,
  match_line,
  Location,
} from './js/api';
import waybillMap from './modules/waybillMap.vue';
import settingGroudModal from './modules/settingGroudModal';
import transit from './modules/transit.vue';
import split from './modules/split.vue';
import * as $formItems from '@/blocks/components/searchModalConfig/index.js'

export default {
  components: {planDispatch,settingGroudModal, addressAnalysis, edit, waybillMap, schedule, packetScheduling, transit, split, exportButton,areaTree },
  computed: {
    planGroupDimensionList() {
      const GROUP_DISPATCH_PLAN = this.options.GROUP_DISPATCH_PLAN
      let keys = [];
      GROUP_DISPATCH_PLAN?.forEach(item => {
        if (item.checked) {
          keys.push(item.value)
        }
      });
      return keys
    },
    estimatedPickupTime: {
      get() {
        return [this.form.estimatedPickupStartTime, this.form.estimatedPickupEndTime];
      },
      set(value) {
        this.$set(this.form, 'estimatedPickupStartTime', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'estimatedPickupEndTime', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
    estimatedDeliveryTime: {
      get() {
        return [this.form.estimatedDeliveryStartTime, this.form.estimatedDeliveryEndTime];
      },
      set(value) {
        this.$set(this.form, 'estimatedDeliveryStartTime', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'estimatedDeliveryEndTime', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
    orderDate: {
      get() {
        return [this.form.orderDateStart, this.form.orderDateEnd];
      },
      set(value) {
        this.$set(this.form, 'orderDateStart', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'orderDateEnd', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
    createDate: {
      get() {
        return [this.form.createDateStart, this.form.createDateEnd];
      },
      set(value) {
        this.$set(this.form, 'createDateStart', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'createDateEnd', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
    carrierAttr() {
      let carrierAttr = $formItems.carrierAttr;
      carrierAttr.targetValueKey = 'name';
      return carrierAttr;
    },
  },
  data() {

    $formItems.lineAttr.tableConfig.rowSelectType=2
    $formItems.consignorAttr.tableConfig.rowSelectType=2
    return {
      planVisible:false,
      visibleSystemGroup:false,
      $formItems,
       //承运商策略数据
      carrierStrategyForm:null,
      sysList:[],
      formExtendedField: {
        form: [],
        formTable: [],
      },
      UPCLOUD_RDC_TMS_BUSINESS_SERVICE,
      spinning: false,
      groupItemNames: [],
      toggleType:'main',
      editType:'', // planDispatch 空-列表页 view-查看 address-地址解析 map-运单地图 schedule-调度 packetScheduling-分组调度 transit-中转 split-拆分
      editId: '',
      groupName: '',
      defaultGroupName:'',
      form: {
        recordTagWord:'',
        lineDirection:null,
        lineIds:'',
        cargoOwnerIds:'',
        cargoOwnerName: '',
        orderNo: '',
        shipbillNo: '',
        orderBusinessType: '',
        estimatedPickupStartTime: '',
        estimatedPickupEndTime: '',
        estimatedDeliveryStartTime: '',
        estimatedDeliveryEndTime: '',
        orderDateStart: '',
        orderDateEnd: '',
        createDateStart: '',
        createDateEnd: '',
        shipperAdministrativeAreas: [],
        administrativeAreas: [],
        lineName: '',
        consigneeLocation: '',
        shipperLocation: '',
        // consigneeAddress: '',
        carriersId: '',
        carriersName: '',
      },
      SELECT_GROUP_CONFIG:null,
      options: {
        ORDER_BUSINESS_TYPE: [],
        BACK_TYPE: [],
        LINE_CARRIER_TYPE: [],
        GROUP_DISPATCH_NEW: [],
        ORDER_TYPE: [],
        CONSIGNEE_LOCATION: [],
        SHIPPER_LOCATION: [],
        GROUP_CONFIG: [],



      },

      // 主表格
      dataSource: [],
      selectedRowKeys: [],
      selectedRowData: [],
      listRemoteUrl,
      listParams: {
        consigneeLocation: '',
        shipperLocation: '',
      },
      selectedRow: {},
      mx_columns: setMainColumns(this, this.tableExtendedField),
      mextendedField_list: [],
      tableExtendedField: [],
      mainPages: { pageNum: 1, pageSize: 15 },

      // 商品表格
      goodsDataSource: [],
      goodsSelectedRowKeys: [],
      goodsListRemoteUrl: page_detail_item,
      goodsListParams: {},
      page_detail_item,
      goods_columns: setGoodsColums(this, this.goods_tableExtendedField),
      goods_tableExtendedField: [],

      // 包裹表格
      packDataSource: [],
      packSelectedRowKeys: [],
      packListRemoteUrl: page_detail_package,
      packListParams: {},
      page_detail_package,
      pack_columns: setPackColums(this),

      addressSearchData: {}, // 列表点击地址解析时的查询传参

      addressAnalysisShow: 0,

      // 策略拆分
      visible: false,
      confirmLoading: false,
      strategySplitMatchingDTOS: [],
      rules: {
        strategy: [{ required: true, message: '拆分策略不能为空', trigger: 'change' }],
      },

      // 分组调度
      groupDimensionList: [],
      groupDimensionLabel: '',


      waybillMap_serchData: {},
    };
  },
  mounted() {

    initDictionary([{ objectcode: 'GROUP_DISPATCH_PLAN' },{ objectcode: 'VEHICLE_TYPE' },{ objectcode: 'CONSIGNEE_LOCATION' }, { objectcode: 'SHIPPER_LOCATION' }, { objectcode: 'ORDER_BUSINESS_TYPE' }, { objectcode: 'BACK_TYPE' }, { objectcode: 'LINE_CARRIER_TYPE' }, { objectcode: 'GROUP_DISPATCH_NEW' }, { objectcode: 'ORDER_TYPE' }]).then((res) => {
        for (let key in res) {
        res[key].forEach((item) => {
          if (!isNaN(item.value)) {
            item.value = +item.value
          }
        })
        }
        //计划分组默认选中值
      res.GROUP_DISPATCH_PLAN.forEach(item => {
        item.checked = ['department_name', 'order_no', 'plan_delivery_date'].includes(item.value);
      })
      this.options = { ...this.options, ...res }

      }
    );
    resultExtendedField({ extendedObjectCode: '15' }).then((res) => {
      if (res) {
        this.mextendedField_list = res.list;
        this.tableExtendedField = res.table;
        this.formExtendedField.form = res.form;
        this.mx_columns = setMainColumns(this, this.tableExtendedField);
      }
    });
    resultExtendedField({ extendedObjectCode: '17' }).then((res) => {
      if (res) {
        this.goods_tableExtendedField = res.table;
        this.formExtendedField.formTable = res.table;
        this.goods_columns = setGoodsColums(this, this.goods_tableExtendedField);
      }
    });
  },
  methods: {

    viewUrl,
    customRow,
    //计划调度
    onPlan() {
      let groupDimensionList =this.planGroupDimensionList
      if (groupDimensionList.length > 0) {
        this.toggleType = 'planDispatch';

      } else {
        this.$message.error('请选择类型条件！')
      }



    },
    handleBack(editType='',params=null){

      if(editType==='packetScheduling'){
        this.sys_group_query(params);

      }else{
        this.editType=editType

      }

    },
    handleSystemGroupClick() {
      if (this.defaultGroupName) {
        let params = {
          groupDimensionList: [],
          shipbillIdList: this.selectedRowKeys,
          groupConfigName: this.defaultGroupName,
          groupNumber:1
        };

      this.sys_group_query(params);

      } else {
        this.visibleSystemGroup=true

      }

    },
    settingGroupClick() {
      this.visibleSystemGroup=true


    },
    onFormChange(name, item, ...args) {
      if (!args[1]) {
        if (name === 'cargoOwner') {
          this.$set(item,name+'Name', '')
          return this.$delete(item,name+'Ids')
        } else if (name === 'line') {
          this.$set(item,name+'Name', '')
          return this.$delete(item,name+'Ids')
        }  else if (name === 'carriers') {
          this.$set(item,name+'Name', '')
          return this.$delete(item,name+'Id')
        }
      }

      let ids = [],names=[]
      if (name==='cargoOwner') {
        args[2].forEach((item) => {
          ids.push(item.cargoOwnerId)

          names.push(item.cargoOwnerName)
        });
        this.$set(item, name + 'Ids', ids.join(','))
        this.$set(item,name+'Name', names.join(','))

      } else if (name === 'line') {

          args[2].forEach((item) => {
          ids.push(item.lineId)
          names.push(item.lineName)
          });
        this.$set(item,name+'Ids', ids.join(','))
        this.$set(item,name+'Name', names.join(','))
      } else if (name === 'carriers') {
        this.$set(item,name+'Id', args[2][0].id)
        this.$set(item,name+'Name', args[2][0].name)
      }
    },
    selectChange(selectedRowKeys, selectedRows) {
      this.selectedRowData = selectedRows
      this.selectedRowKeys=selectedRowKeys
    },
    onLocation() {
      let list = this.selectedRowData.map(item => {
        return {
          shipbillId: item.shipbillId,
          shipperType: item.shipperType,
          shipperId: item.shipperId,
          consigneeType: item.consigneeType,
          consigneeId: item.consigneeId,
        }
      })
      Location(this, list);
      //this.$refs.childrenTable.dataSource = [];
    },
    handelSubmit(event) {
      event.preventDefault()
      event.submitter.focus();
      this.onSearch()
    },
    // 查询
    onSearch() {
      this.dataSource = [];
      this.selectedRowKeys = [];
      this.goodsDataSource = [];
      this.goodsSelectedRowKeys = [];
      this.packDataSource = [];
      this.packSelectedRowKeys = [];
      this.listParams = { ...this.form };
    },
    // 重置
    onReset() {
      this.form = {
        recordTagWord:'',
        lineDirection:null,
        cargoOwnerIds:'',
        cargoOwnerName: '',
        orderNo: '',
        shipbillNo: '',
        orderBusinessType: '',
        estimatedPickupStartTime: '',
        estimatedPickupEndTime: '',
        estimatedDeliveryStartTime: '',
        estimatedDeliveryEndTime: '',
        orderDateStart: '',
        orderDateEnd: '',
        createDateStart: '',
        createDateEnd: '',
        shipperAdministrativeAreas: [],
        administrativeAreas: [],
        lineName: '',
        lineIds:'',
        consigneeLocation: '',
        shipperLocation: '',
        // consigneeAddress: '',
        carriersId: '',
        carriersName: '',
      };

    },
    doneBefore(res) {
      if (res.data) {
        const { pageNum, pageSize } = res.data;
        this.mainPages = { pageNum, pageSize };
      }
    },
    masterClickRow(event, activeID, rowRecord) {

      this.goodsListRemoteUrl = page_detail_item;
      this.packListRemoteUrl = page_detail_package;
      this.goodsListParams = { shipbillId: rowRecord.shipbillId };
      this.packListParams = { shipbillId: rowRecord.shipbillId };
    },
    goodsClickRow(event, activeID, rowRecord) {
      this.packListRemoteUrl = page_package_item;
      this.packListParams = { shipbillId: rowRecord.shipbillId, itemId: rowRecord.itemId };
    },
    packClickRow(event, activeID, rowRecord) {
      this.goodsListRemoteUrl = page_item_package;
      this.goodsListParams = { shipbillId: rowRecord.shipbillId, packageId: rowRecord.packageId };
    },

    // 查看
    toView(editData = { shipbillId: '' }) {
      this.preverType = this.editType;
      this.editId = editData.shipbillId;
      this.editType = 'view';
    },

    onWaybillMap() {
      if (this.selectedRowKeys.length === 0) {
        this.waybillMap_serchData = {...this.form,shipbillIdList:[]}
      } else {
        this.waybillMap_serchData = {
          shipbillIdList: this.selectedRowKeys
        }
      }

      this.editType = 'map';
    },
    // 调度/分组调度
    onSchedule(editType) {

      //调用承运商策略,不是分组调度
      if (editType !== 'packetScheduling') {

        query_dispatch_strategy(this.selectedRowKeys).then(res => {
        //配置
          if (res.success) {
            if (res.data) {
              let data = res.data
              data.vehicleDeviceName = data.deviceName
              data.vehicleDeviceId = data.deviceId
              data.vehicleDeviceCode = data.deviceCode
              data.vehicleTypeCategoryName = data.typeCategoryName
              data.vehicleTypeCategory = data.typeCategory
            }
          //承运商策略数据
          this.carrierStrategyForm=res.data
        } else {
          this.$exception(res)
        }
      })
      }

      this.editType = editType;
    },
    // 中转
    onTransit() {
      this.editType = 'transit';
    },

    // 拆分
    toSplit(editData = { shipbillId: '' }) {
      this.selectedRow = { ...editData };
      this.editType = 'split';
    },
    // 中转
    toTransit(editData = { shipbillId: '' }) {
      this.selectedRowKeys = [editData.shipbillId];
      this.editType = 'transit';
    },
    // 撤销
    toRevoke(editData) {
      let self = this;
      this.$confirm({
        title: '是否撤销',
        onOk() {
          return new Promise((resolve, reject) => {
            self.spinning = true;
            Revoke({ fatherShipbillId: editData.fatherShipbillId, shipbillId: editData.shipbillId })
              .then((res) => {
                self.spinning = false;
                if (res.success) {
                  self.$message.success(res.message);
                  self.onSearch();
                  resolve();
                } else {
                  self.$exception(res);
                  resolve();
                }
              })
              .finally(() => {
                self.spinning = false;
                reject();
              });
          });
        },
      });
    },
    toPrint(editData = { shipbillId: '' }) {},

    // 地址解析
    mapPase() {
      this.addressSearchData = {
        shipbillIds: this.selectedRowKeys,
      };
      this.addressAnalysisShow = 2;
      this.editType = 'address';
    },
    addressBack() {
      this.addressAnalysisShow = 0;
      this.editType = '';
    },
    //线路配置
    onLineMatch() {
      this.spinning = true;
      let serchData = {
          shipbillIdList: this.selectedRowKeys,
          ...this.form
        }
      return match_line(serchData).then((res) => {
        if (res.success) {
             this.onSearch();
            this.$message.success(res.message);
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },
    // 策略拆分
    onPolicySplit() {
      this.spinning = true;
      smart_split({ shipbillIds: this.selectedRowKeys })
        .then((res) => {
          if (res.success) {
            if (res.data.length) {
              this.strategySplitMatchingDTOS = res.data.map((item) => {
                item.strategy = item.strategySplitMatchingDTOS[0].id;
                item.strategyEnums = item.strategySplitMatchingDTOS.map((item2) => {
                  return {
                    value: item2.id,
                    label: item2.name,
                  };
                });
                return item;
              });
              this.visible = true;
            } else {
              this.$message.success(res.message);
              this.onSearch();
            }
          } else {
            self.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },
    // 策略调度
    onPolicyScheduling() {
      this.spinning = true;
      carrier_dispatch_strategy(this.selectedRowKeys)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.onSearch();
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    handleOk() {
      let list = this.strategySplitMatchingDTOS.map((item) => {
        let index = item.strategySplitMatchingDTOS.findIndex((item2) => item2.id === item.strategy);
        return { ...item.strategySplitMatchingDTOS[index], shipbillId: item.shipbillId, strategyId: item.strategySplitMatchingDTOS[index].id };
      });

      this.confirmLoading = true;
      smart_split_strategy(list)
        .then((res) => {
          if (res.success) {
            this.visible = false;
            this.$message.success(res.message);
            this.onSearch();
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },

    // 分组调度
    handleMenuClick(event, type,value) {
      event.preventDefault();
      event.stopPropagation();

      const {checked ,name} = event.target
      if (type == 'sub1') {
        this.groupDimensionList = []
        this.groupName = checked?name:''

      } else if (type == 'sub2') {
        this.groupName = ''
        if (checked) {
          this.groupDimensionList.push(value)
        } else {
          this.groupDimensionList=this.groupDimensionList.filter(str=>value!==str)
        }



      }



    },
    //更新分组信息
    updateGroupList(filterShipbillId) {
      let params = {
        groupDimensionList: this.groupDimensionList,
        shipbillIdList: this.selectedRowKeys.filter(id => !filterShipbillId.includes(id)) || [],

      };

      if (!params.shipbillIdList.length) {

         return this.sysList =[];
      }
      return sys_group_query(params)
        .then((res) => {
          if (res.success) {
            this.sysList = res.data;
          } else {
            this.$exception(res);
          }
        })
    },
    // 首页跳分组调度
    onSystemGroup() {
      let params = {
        groupDimensionList:this.groupDimensionList,
        shipbillIdList: this.selectedRowKeys,
        groupConfigName: this.groupName,
        groupNumber:1
      };


      this.sys_group_query(params);
    },
    // 调度跳分组调度
    onPacketScheduling(params) {
      this.sys_group_query(params);
    },
    sys_group_query(params) {
      this.spinning = true;
      params = { ...params, ...this.form }
      if (params.groupDimensionList&&!params.groupConfigName) {
        let groupDimensionLabelList = [];
        this.options.GROUP_DISPATCH_NEW.forEach((item) => {
        if (this.groupDimensionList.includes(item.value)) {
          groupDimensionLabelList.push(item.label);
        }
        this.groupDimensionLabel=groupDimensionLabelList.join(',');
      });
      } else {
        this.groupDimensionLabel = params.groupConfigName
      }

      sys_group_query(params)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.sysList = res.data.groupQueryDTOS;
            this.groupItemNames = res.data.groupItemNames||[]
            this.SELECT_GROUP_CONFIG = res.data.groupCfgDTOS
            this.onSchedule('packetScheduling');
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });

    },

    disRevoke(record) {
      if (record.splitOrderStatus === 0 && (record.splitOrderType === 3 || record.splitOrderType === 5)) {
        return false;
      }
      if (record.carrierSplitOrderStatus === 0 && (record.carrierSplitOrderType === 3 || record.carrierSplitOrderType === 5)) {
        return false;
      }
      if (record.fatherShipbillId) {
        return false;
      }
      return true;
    },

    // 策略中转
    onSmartTransit() {
      let self = this;
      this.$confirm({
        title: '是否策略中转?',
        onOk() {
          return new Promise((resolve, reject) => {
            self.spinning = true;
            smart_transfer(self.selectedRowKeys)
              .then((res) => {
                self.spinning = false;
                if (res.success) {
                  self.$message.success(res.message);
                  self.onSearch();
                  resolve();
                } else {
                  self.$exception(res);
                  resolve();
                }
              })
              .finally(() => {
                self.spinning = false;
                reject();
              });
          });
        },
      });
    },

    getAreaChange(key, list) {
      this.form[key] = list
    },
  },
};
</script>
<style lang="less">
  .dropdown-mini-menu.ant-menu-root{
    border-radius: 2px;
    box-shadow: 0 2px 8px rgba(0,0,0,.15)!important;
    .ant-menu-submenu-title{
      padding-left: 12px !important;
      }
      .ant-menu-sub .ant-menu-item{
        padding-left: 12px !important;

      }

    .ant-menu-item,.ant-menu-submenu-title{
      font-size: 12px;
      margin: 0;
      padding: 0 8px;
      height: 32px;
     line-height:32px;

    }
  }

</style>