<template>
  <basic-container v-loading="details.loadingObj.pageLoading">
    <div class="avue-crud">
      <!-- 搜索模块 -->
      <div v-h5uShow="search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="query" class="header_search">
          <el-form-item label="车次号:">
            <el-input v-model="query.serviceNumber" placeholder="请输入车次号" clearable></el-input>
          </el-form-item>
          <el-form-item label="预计发车:" class="el-times">
            <el-date-picker
              v-model="stockupDate"
              type="daterange"
              unlink-panels
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              value-format="YYYY-MM-DD"
              clearable
            />
          </el-form-item>
          <el-form-item label="实际发车:" class="el-times">
            <el-date-picker
              v-model="stockupDate"
              type="daterange"
              unlink-panels
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              value-format="YYYY-MM-DD"
              clearable
            />
          </el-form-item>
          <el-form-item label="到车时间:" class="el-times">
            <el-date-picker
              v-model="stockupDate"
              type="daterange"
              unlink-panels
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              value-format="YYYY-MM-DD"
              clearable
            />
          </el-form-item>
          <el-form-item label="创建时间:" class="el-times">
            <el-date-picker
              v-model="stockupDate"
              type="daterange"
              unlink-panels
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              value-format="YYYY-MM-DD"
              clearable
            />
          </el-form-item>
          <!-- 查询按钮 -->
          <el-form-item class="el-btn">
            <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>
      </div>

      <!-- 控件模块 -->

      <div class="avue-crud__header">
        <!-- 头部左侧按钮模块 -->
        <div class="avue-crud__left">
          <!-- 发车 -->
          <el-button
            v-if="permissionObj.VehicleArrivalManagement_startCar"
            type="primary"
            icon="el-icon-van"
            @click="handleStartCar"
            >发车
          </el-button>

          <!-- 网点取消发车 -->
          <el-button
            v-if="permissionObj.VehicleArrivalManagement_nodeCancelStartCar"
            type="primary"
            icon="el-icon-close"
            @click="handleEndCar"
            >网点取消发车
          </el-button>

          <!-- 装载清单 -->
          <el-button
            v-if="permissionObj.VehicleArrivalManagement_listOfLoadedWagons"
            type="primary"
            icon="el-icon-printer"
            @click="handleShowListOfLoadedWagons"
          >
            装载清单
          </el-button>

          <!-- 到达 -->
          <el-button
            v-if="permissionObj.VehicleArrivalManagement_arrive"
            type="primary"
            icon="el-icon-printer"
            @click="handleArrive"
            >到达
          </el-button>

          <!-- 取消到达 -->
          <el-button
            v-if="permissionObj.VehicleArrivalManagement_cancelArrive"
            type="primary"
            icon="el-icon-printer"
            @click="handleCloseArrive"
          >
            取消到达
          </el-button>

          <!-- 中途到达卸车 -->
          <el-button
            v-if="permissionObj.VehicleArrivalManagement_HalfwayToUnloadTheCar"
            type="primary"
            icon="el-icon-delete"
            @click="handleUnloadByLoadId(1)"
          >
            中途到达卸车
          </el-button>

          <!-- 对比报表 -->
          <!-- <el-button type="primary" icon="el-icon-delete" @click="handleShowComparativeStatement()">
            对比报表
          </el-button> -->

          <!-- 终点到达卸车 -->
          <el-button
            v-if="permissionObj.VehicleArrivalManagement_UnloadAtTheEnd"
            type="primary"
            icon="el-icon-document"
            @click="handleUnloadByLoadId(2)"
          >
            终点到达卸车
          </el-button>

          <!-- 卸车报告 -->
          <el-button
            v-if="permissionObj.VehicleArrivalManagement_UnloadReport"
            type="primary"
            icon="el-icon-document"
            @click="handleShowUnloadReport"
          >
            卸车报告
          </el-button>
          <!-- <el-button type="primary" icon="el-icon-document" @click="searchReset()">
              欧派TIMS数据关联
            </el-button> -->
        </div>
        <!-- 头部右侧按钮模块 -->
        <div class="avue-crud__right">
          <el-button icon="el-icon-refresh" @click="searchChange" circle></el-button>
          <el-button icon="Operation" @click="showdrawer(true)" circle></el-button>
          <el-button icon="el-icon-search" @click="searchHide" circle></el-button>
        </div>
      </div>

      <!-- 表格 -->

      <!-- 列表模块 -->
      <tablecmt
        ref="tableNode"
        :columnList="details.columnList"
        :tableData="data"
        :loading="loadingObj.list"
        @inputTxt="inputsc"
        @timeCheck="timesc"
        @btnCheck="btnsc"
        @selectCheck="selectsc"
        @selection="selectionChange"
        :isselectfun="CanOperate"
        :tableRowClassName="
          (row, rowIndex) => {
            console.log('row :>> ', row);
            console.log('rowIndex :>> ', rowIndex);
            if (rowIndex === 0) return 'denger';
            else return '';
          }
        "
      >
        <template #default="slotProps">
          <template v-if="slotProps.scope.column.label === '批次号'">
            <el-text @click="handleGoWaybill(slotProps.scope)">{{
              slotProps.scope.row.carsNo
            }}</el-text>
          </template>

          <template v-else-if="slotProps.scope.column.label === '路线'">
            <span
              v-for="(item, index) in slotProps.scope.row.carsLoadLineList"
              :key="item"
              class="flex-c-c carsLineName"
            >
              <el-tooltip placement="top" effect="dark">
                <template #content>
                  <div>
                    <span class="mr-10">网点:</span>
                    <span>{{ item.nodeName }}</span>
                  </div>
                  <div>
                    <span class="mr-10">计划总件数:</span>
                    <span>{{ item.planLoadingNumber || 0 }}</span>
                  </div>
                  <div>
                    <span class="mr-10">实际装车件数:</span>
                    <span>{{ item.realLoadingNumber || 0 }}</span>
                  </div>
                  <div>
                    <span class="mr-10">卸车件数:</span>
                    <span>{{ item.unloadNumber || 0 }}</span>
                  </div>
                  <div>
                    <span class="mr-10">操作人:</span>
                    <span>{{ item.arriveUserName || item.startUserName || '暂无数据' }}</span>
                  </div>
                  <div>
                    <span class="mr-10">状态:</span>
                    <span>{{
                      (details.nodeStatus.find(val => val.value === Number(item.nodeStatus)) || {})
                        .label
                    }}</span>
                  </div>
                </template>
                <!-- <el-text style="margin: 0 !important">{{ item.nodeName }}</el-text> -->
                <el-text
                  :class="
                    (
                      details.nodeStatus.find(val => val.value === Number(item.nodeStatus)) || {
                        className: 'gray',
                      }
                    ).className + ' mr0'
                  "
                >
                  {{ item.nodeName }}
                </el-text>
              </el-tooltip>
              <!-- <el-text @click="handleGoWaybill(slotProps.scope)">
                {{ item.nodeName }}
              </el-text> -->
              <el-icon class="ml" v-if="index !== slotProps.scope.row.carsLoadLineList.length - 1"
                ><Right
              /></el-icon>
            </span>
          </template>

          <template v-else-if="slotProps.scope.column.label === '车辆状态'">
            <el-tag type="danger">{{ slotProps.scope.row.loadStatusName }}</el-tag>
          </template>

          <template v-else-if="slotProps.scope.column.label === '是否直发商家'">
            <el-tag
              v-if="slotProps.scope.row.isCustomer"
              :class="slotProps.scope.row.isCustomer === '1' ? 'green' : 'red'"
              >{{ slotProps.scope.row.isCustomerName }}</el-tag
            >
          </template>

          <template
            v-else-if="
              slotProps.scope.column.label === '操作' &&
              Number(slotProps.scope.row.loadStatus) !== 100
            "
          >
            <!-- 装车明细 -->
            <el-text
              v-if="permissionObj.VehicleArrivalManagement_shippingSpecification"
              @click="handleShowTruckLoadingDetails(slotProps.scope)"
              >装车明细
            </el-text>

            <!-- 编辑 -->
            <el-text
              v-if="
                permissionObj.VehicleArrivalManagement_edit &&
                Mydata.id === slotProps.scope.row.nowWarehouseId &&
                Number(slotProps.scope.row.loadStatus) === 20
              "
              @click="handleEditStowage(slotProps.scope)"
              >编辑
            </el-text>

            <el-dropdown v-if="Number(slotProps.scope.row.loadStatus) !== 0">
              <span class="el-dropdown-link">
                <el-text>
                  更多 <el-icon class="el-icon--right"><arrow-down /></el-icon
                ></el-text>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="
                      Mydata.id === slotProps.scope.row.nowWarehouseId &&
                      Number(slotProps.scope.row.loadStatus) === 20
                    "
                  >
                    <el-text @click="handleNodeCost(slotProps.scope)"> 节点费用 </el-text>
                  </el-dropdown-item>

                  <el-dropdown-item
                    v-if="
                      Mydata.id === slotProps.scope.row.nowWarehouseId &&
                      Number(slotProps.scope.row.loadStatus) === 20
                    "
                  >
                    <el-text @click="handleDirectGoMarketVesited(slotProps.scope)">
                      配置直发商家
                    </el-text>
                  </el-dropdown-item>

                  <el-dropdown-item>
                    <el-text @click="handleDirectGoMarketDetails(slotProps.scope)">
                      签收详情
                    </el-text>
                  </el-dropdown-item>

                  <!-- 手动装车 -->
                  <el-dropdown-item
                    v-if="
                      permissionObj.VehicleArrivalManagement_ManualLoading &&
                      Mydata.id === slotProps.scope.row.nowWarehouseId &&
                      Number(slotProps.scope.row.loadingType) === 1 &&
                      Number(slotProps.scope.row.loadStatus) === 20
                    "
                  >
                    <el-text @click="handleManualLoading(slotProps.scope)"> 手动装车 </el-text>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </template>
      </tablecmt>

      <!-- 分页模块 -->
      <el-row class="el-fy">
        <div class="avue-crud__pagination flex-c-sb" style="width: 100%">
          <div style="font-size: 14px">勾选数量: {{ selectionList.length }}</div>
          <!-- 分页模块 -->
          <el-pagination
            align="right"
            background
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page.pageNum"
            :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>
    </div>
  </basic-container>

  <!-- 配置装车目的地 -->
  <el-dialog
    title="配置装车目的地"
    v-model="details.popUpShow.truckLoadingDetailVisited"
    width="80%"
    :before-close="beforeClose"
    append-to-body
    :fullscreen="details.fullscreenObj.truckLoadingDetailPopUp"
    :show-close="false"
    class="truckLoadingDetailPopUp"
    v-loading="details.loadingObj.truckLoadingDetailPopUpTable"
  >
    <!-- 标题 -- 头部控件区 -->
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header flex-c-sb">
        <div class="fwb" :id="titleId" :class="titleClass">配置装车目的地</div>
        <div class="flex-c-c">
          <!-- 全屏显示按钮 -->
          <el-button type="text" v-if="!details.fullscreenObj.truckLoadingDetailPopUp">
            <el-icon class="" @click="handleFullScrean('open', 'truckLoadingDetailPopUp')"
              ><FullScreen
            /></el-icon>
          </el-button>
          <el-button type="text" v-else>
            <el-icon class="" @click="handleFullScrean('close', 'truckLoadingDetailPopUp')"
              ><CopyDocument
            /></el-icon>
          </el-button>

          <!-- 弹窗关闭按钮 -->
          <el-button type="text">
            <el-icon class="" @click="close"><Close /></el-icon>
          </el-button>
        </div>
      </div>
    </template>

    <div v-loading="details.loadingObj.truckLoadingDetailPopUpLoading">
      <el-button
        icon="Edit"
        type="primary"
        v-if="details.nextNodeData.length > 1"
        @click="handleOpenConfiguration('batch')"
      >
        配置目的地
      </el-button>

      <tablecmt
        class="truckLoadingDetailPopUpTable mt10"
        :columnList="details.packageColumnList"
        :tableData="details.packageRenderData"
        :loading="loadingObj.list"
        @inputTxt="packageInputsc"
        @selection="list => (details.packageSelectedData = list)"
        :isShowRefresh="false"
      >
        <template #default="slotProps">
          <el-text
            v-if="details.nextNodeData.length > 1"
            @click="handleOpenConfiguration('one', slotProps.scope)"
            >配置目的地</el-text
          >
          <el-text @click="removePackage(slotProps.scope)">移除</el-text>
        </template>
      </tablecmt>

      <div class="dialog-footer">
        <el-button
          icon="el-icon-circle-close"
          @click="details.popUpShow.truckLoadingDetailVisited = false"
          >取 消</el-button
        >
        <el-button type="primary" icon="el-icon-circle-check" @click="handleSubmit"
          >提 交</el-button
        >
      </div>
    </div>
  </el-dialog>

  <!-- 配置装车目的地 -->
  <el-dialog
    title="配置装车目的地"
    v-model="details.popUpShow.chooseDestinationVisited"
    width="30%"
    append-to-body
    class="truckLoadingDetailPopUp"
  >
    <el-form-item label="目的地" prop="region">
      <el-select v-model="details.chooseNodeId" placeholder="请选择目的地" class="w100">
        <el-option
          v-for="item in details.nextNodeData"
          :key="item"
          :label="item.warehouseName"
          :value="item.warehouseId"
        />
      </el-select>
    </el-form-item>

    <!-- 表单按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button
          icon="el-icon-circle-close"
          @click="details.popUpShow.chooseDestinationVisited = false"
          >取 消</el-button
        >
        <el-button type="primary" icon="el-icon-circle-check" @click="handleEditSubmit">
          确 认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 配载清单 -->
  <el-dialog
    title="配载清单"
    v-model="details.popUpShow.listOfLoadedWagons"
    width="80%"
    :before-close="beforeClose"
    append-to-body
    :fullscreen="details.fullscreenObj.listOfLoadedWagonsPopUp"
    :show-close="false"
    class="listOfLoadedWagonsPopUp"
  >
    <!-- 标题 -- 头部控件区 -->
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header flex-c-sb">
        <div class="fwb" :id="titleId" :class="titleClass">配载清单</div>
        <div class="flex-c-c">
          <!-- 全屏显示按钮 -->
          <el-button type="text" v-if="!details.fullscreenObj.listOfLoadedWagonsPopUp">
            <el-icon class="" @click="handleFullScrean('open', 'listOfLoadedWagonsPopUp')"
              ><FullScreen
            /></el-icon>
          </el-button>
          <el-button type="text" v-else>
            <el-icon class="" @click="handleFullScrean('close', 'listOfLoadedWagonsPopUp')"
              ><CopyDocument
            /></el-icon>
          </el-button>

          <!-- 弹窗关闭按钮 -->
          <el-button type="text">
            <el-icon class="" @click="close"><Close /></el-icon>
          </el-button>
        </div>
      </div>
    </template>

    <div
      :class="{
        dialog_container: true,
        fullScreen: details.fullscreenObj.listOfLoadedWagonsPopUp,
      }"
    >
      <ArteryPrintTemplate
        v-if="details.popUpShow.listOfLoadedWagons"
        :waybillInfo="details.listOfLoadedWagonsData"
      />
    </div>
    <div class="flex-c-c mt10">
      <el-button icon="el-icon-circle-close" @click="details.popUpShow.listOfLoadedWagons = false">
        取 消
      </el-button>
      <el-button type="primary" icon="Printer" @click="handleSubmit"> 打 印 </el-button>
    </div>
  </el-dialog>

  <!-- 卸车清单 -->
  <el-dialog title="卸车清单" v-model="details.popUpShow.unloadReport" width="780px" append-to-body>
    <div class="unloadInfo_Container">
      <!-- 装车卸车信息 -->
      <div class="title">装车卸车信息</div>

      <div class="content">
        {{ details.unloadReportInfo.one }}
      </div>

      <!-- 卸车异常 -->
      <div class="title mt20">卸车异常</div>

      <div class="content">
        {{ details.unloadReportInfo.two }}
      </div>

      <!-- 待处理和已处理信息 -->
      <div class="title mt20">待处理和已处理信息</div>

      <div class="content">
        {{ details.unloadReportInfo.three }}
      </div>

      <div class="dialog-footer mt20">
        <el-button
          icon="el-icon-circle-close"
          type="primary"
          @click="details.popUpShow.unloadReport = false"
        >
          关 闭
        </el-button>
      </div>
    </div>
  </el-dialog>

  <!-- 列表配置显示 -->
  <edittablehead
    @setcolum="setnewcolum"
    @closce="showdrawer"
    :drawerShow="drawerShow"
    :columnList="columnList"
    v-model="columnList"
  ></edittablehead>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, nextTick } from 'vue';
import functions from '@/utils/functions';
import dayjs from 'dayjs';
import { mapGetters, useStore } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import {
  downloadXls,
  deepClone,
  setNodeHeight,
  debounce,
  handleClearTableQuery,
  handleTranslationDataSeclect,
} from '@/utils/util';
import { columnList } from '@/option/distribution/VehicleArrivalManagement';
import { packageColumnList } from '@/option/distribution/VehicleStowage';
import {
  postloadArriveCarsPageList,
  postloadArriveCarByLoadId,
  postloadCancelArriveCarByLoadId,
  postUnloadByLoadId,
} from '@/api/distribution/VehicleArrivalManagement';
import {
  postStartCarByLoadId,
  postDetermineHasNoFinalNode,
  postFindNextNodeList,
  postUpdateLoadScanFinalNodeIdById,
  postRemoveCarsLoadScan,
  postCancelStartCarByLoadId,
  postManualLoadingloadId,
  postFindLoadingListData,
  postFindWarehouseUnloadReport,
} from '@/api/distribution/VehicleStowage';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

// 获取路由实例
const $router = useRouter();
const $route = useRoute();

const $store = useStore();

const Mydata = ref<any>({});

Mydata.value = JSON.parse(localStorage.getItem('my_data')); //获取本地仓库信息

const details = reactive({
  /** 是否开启搜索 */
  search: false,
  /** 表格搜索条件 */
  query: {},
  /** 时间快捷选择设置 */
  shortcuts: [
    {
      text: '最近一周',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      },
    },
    {
      text: '最近一个月',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      },
    },
    {
      text: '最近三个月',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      },
    },
  ],
  /** 时间选择器数据 */
  stockupDate: [],
  /** 列表 */
  columnList: deepClone(columnList),
  /** 列表数据 */
  data: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    /** 配置装车目的地详情 */
    truckLoadingDetailPopUpLoading: false,
    /** 全屏Loading */
    pageLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 列表Dom节点 */
  listNode: '',
  /** 弹出层显示 */
  popUpShow: {
    /** 配置目的地 */
    truckLoadingDetailVisited: false,
    /** 选择目的地弹窗 */
    chooseDestinationVisited: false,
    /** 配载清单 */
    listOfLoadedWagons: false,
    /** 卸车清单 */
    unloadReport: false,
  },
  /** 全屏 */
  fullscreenObj: {
    /** 装车明细 */
    truckLoadingDetailPopUp: false,
    comparativeStatementPopUp: false,
    /** 配载清单 */
    listOfLoadedWagonsPopUp: false,
  },
  /** 弹出层表单 */
  form: {},
  /** 是否为查看模式 */
  view: false,
  /** 车辆状态 */
  carsStatus: [
    { label: '未发车', value: 0 },
    { label: '已发车', value: 10 },
    { label: '网点到车', value: 20 },
    { label: '网点发车', value: 30 },
    { label: '终点到车', value: 40 },
    { label: '已卸车', value: 80 },
    { label: '已签收', value: 90 },
    { label: '部分签收', value: 91 },
    { label: '取消配载', value: 100 },
  ],
  /** 节点状态 */
  nodeStatus: [
    { label: '未到达', value: 0, className: 'gray' },
    { label: '已到车', value: 10, className: 'green' },
    { label: '已发车', value: 20, className: 'red' },
  ],
  packageColumnList: deepClone(packageColumnList),
  /** 配置装车目的地数据 */
  packageData: [],
  /** 配置装车目的地数据 -- 渲染数据 */
  packageRenderData: [],
  /** 后续装车目的地 */
  nextNodeData: [],
  /** 配置目的地 -- 被选中的数据 */
  packageSelectedData: [],
  /** 被修改的数据 */
  modifyData: [],
  /** 被选中的数据 */
  chooseNodeId: '',
  packageQuery: {},
  /** 配载清单数据 */
  listOfLoadedWagonsData: {},
  /** 卸车报告信息 */
  unloadReportInfo: {},
});

const tableNode = ref();

const { search, query, shortcuts, stockupDate, data, loadingObj, selectionList, drawerShow, page } =
  toRefs(details);

/** 能否操作 */
const CanOperate = row => {
  const black = [100];

  if (black.includes(Number(row.loadStatus))) return false;
  return true;
};

/** vuex */
const permission = computed(() => mapGetters(['permission', 'tagWel', 'tagList']));
console.log('permission :>> ', permission);

/** 权限按钮 */
const permissionObj = reactive({
  /** 发车 */
  VehicleArrivalManagement_startCar: computed(() => {
    return $store.getters.permission.VehicleArrivalManagement_startCar;
  }),
  /** 网点取消发车 */
  VehicleArrivalManagement_nodeCancelStartCar: computed(() => {
    return $store.getters.permission.VehicleArrivalManagement_nodeCancelStartCar;
  }),
  /** 装载清单 */
  VehicleArrivalManagement_listOfLoadedWagons: computed(() => {
    return $store.getters.permission.VehicleArrivalManagement_listOfLoadedWagons;
  }),
  /** 到达 */
  VehicleArrivalManagement_arrive: computed(() => {
    return $store.getters.permission.VehicleArrivalManagement_arrive;
  }),
  /** 取消到达 */
  VehicleArrivalManagement_cancelArrive: computed(() => {
    return $store.getters.permission.VehicleArrivalManagement_cancelArrive;
  }),
  /** 中途到达卸车 */
  VehicleArrivalManagement_HalfwayToUnloadTheCar: computed(() => {
    return $store.getters.permission.VehicleArrivalManagement_HalfwayToUnloadTheCar;
  }),
  /** 终点到达卸车 */
  VehicleArrivalManagement_UnloadAtTheEnd: computed(() => {
    return $store.getters.permission.VehicleArrivalManagement_UnloadAtTheEnd;
  }),
  /** 卸车报告 */
  VehicleArrivalManagement_UnloadReport: computed(() => {
    return $store.getters.permission.VehicleArrivalManagement_UnloadReport;
  }),
  /** 装车明细 */
  VehicleArrivalManagement_shippingSpecification: computed(() => {
    return $store.getters.permission.VehicleArrivalManagement_shippingSpecification;
  }),
  /** 编辑 */
  VehicleArrivalManagement_edit: computed(() => {
    return $store.getters.permission.VehicleArrivalManagement_edit;
  }),
  /** 手动装车 */
  VehicleArrivalManagement_ManualLoading: computed(() => {
    return $store.getters.permission.VehicleArrivalManagement_ManualLoading;
  }),
});

/** 请求页面数据 */
const onLoad = debounce(async (params = {}) => {
  try {
    // 开启loading
    details.loadingObj.list = true;

    // 请求页面数据
    const res = await postloadArriveCarsPageList(details.page, { ...details.query, ...params });
    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = data.records;
    // 装车状态
    // const codes = details.carsStatus.map(val => val.value);
    // for (let item of details.data) {
    //   const _index = codes.indexOf(Number(item.loadStatus));
    //   item.loadStatusName = _index !== -1 ? details.carsStatus[_index].label : '未知';
    //   item.NumberOfPiecesInTheCar = item.realLoadingNumber - item.unloadNumber;
    // }
    handleTranslationDataSeclect(details.data, details.columnList);
    details.page.total = data.total;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.list = false;
  }
}, 10);

onLoad();

/** 搜索 */
const searchChange = () => {
  onLoad();
};

/** 清空表单 */
const searchReset = () => {
  details.query = {};
  details.stockupDate = [];
  handleClearTableQuery(details.columnList);
  details.page.pageNum = 1;
  onLoad();
};

/** 展开列表控件 */
const showdrawer = (_flag?: boolean) => {
  details.drawerShow = _flag;
};

/** 是否开启搜索区 */
const searchHide = () => {
  details.search = !details.search;
  console.log('tableNode :>> ', tableNode);
  setNodeHeight(tableNode.value.$el, '', true);
};

/** 表格表头输入框搜索 */
const inputsc = (index, row) => {
  details.query[row.prop] = index;
  if (!index && index !== 0) delete details.query[row.prop];
  onLoad();
};

/** 表格表头时间选择 */
const timesc = (index, row) => {
  console.log(index, row);
  if (!!index) {
    index = dayjs(index).format('YYYY-MM-DD');
  }
  details.query[row.prop] = index;
  if (!index) {
    delete details.query[row.prop];
  }
  onLoad();
};

/** 表格表头输入框搜索 */
const btnsc = () => {};

/** 表格表头下拉框选择 */
const selectsc = (index, row) => {
  details.query[row.prop] = index;
  if (!index && index !== 0) delete details.query[row.prop];
  if (row.prop === 'certificateTypeName') {
    details.query['certificateType'] = index;
    if (!index) delete details.query['certificateType'];
  }
  onLoad();
};

/** 表格表头复选框选择 */
const selectionChange = (list: any) => {
  details.selectionList = list;
};

/** 每页数量改变执行的回调 */
const sizeChange = (pageSize: number) => {
  details.page.pageSize = pageSize;
  onLoad();
};

/** 页码改变执行的回调 */
const currentChange = () => {};

/**
 * 设置列表 -- 固定函数
 * 弹窗的勾选回调，用于更改头部数组
 * 固定搭配，只需要更换   columnList
 *  */
const setnewcolum = (newarr, headarr, type) => {
  console.log('type :>> ', type);
  if (type == 1) {
    details.columnList = newarr;
    functions.setStorage(window.location.pathname + 'checkList', headarr);
  } else if (type == 2) {
    details.columnList = newarr;
    functions.setStorage(window.location.pathname + 'flexList', headarr);
  } else if (type == 3) {
    details.columnList = newarr;
    functions.setStorage(window.location.pathname + 'sortlist', headarr);
  }
};

/** 弹出层开启前清除数据 */
const beforeClose = done => {
  done();
  details.form = {};
  details.view = false;
};

/** 显示装车详情 */
const handleShowTruckLoadingDetails = ({ row }) => {
  $router.push({
    path: '/distribution/artery/truckLoadingDetails',
    query: {
      loadId: row.id,
      name: row.carsNo + '--' + '装车明细',
      type: 'VehicleArrivalManagement',
    },
  });

  // details.popUpShow.truckLoadingDetailVisited = true;

  // nextTick(() => {
  //   // 获取弹窗内表格元素节点, 并设置高度
  //   const _node = document.querySelector('.truckLoadingDetailPopUp .maboxhi');
  //   _node.style.height = '550px';
  // });
};

/** 显示对比报表 */
const handleShowComparativeStatement = () => {
  $router.push('/waybill/ComparativeStatement');
};

/** 到车 */
const handleArrive = async () => {
  if (details.selectionList.length == 0) return ElMessage.warning('请选择需要到车的数据');

  ElMessageBox.confirm('确认到车?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      details.loadingObj.pageLoading = true;
      const submitData = {
        loadId: details.selectionList.map(val => val.id).join(','),
        ...details.form,
      };

      const res = await postloadArriveCarByLoadId(submitData);
      const { code } = res.data;
      if (code !== 200) {
        return;
      }
      ElMessage({
        type: 'success',
        message: '到达成功',
      });

      onLoad();
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.pageLoading = false;
    }
  });
};

/** 取消到车 */
const handleCloseArrive = async () => {
  ElMessageBox.confirm('确认取消到车?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      details.loadingObj.pageLoading = true;
      const submitData = {
        loadId: details.selectionList.map(val => val.id).join(','),
        ...details.form,
      };

      const res = await postloadCancelArriveCarByLoadId(submitData);
      const { code } = res.data;
      if (code !== 200) {
        return;
      }
      ElMessage({
        type: 'success',
        message: '取消成功',
      });

      onLoad();
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.pageLoading = false;
    }
  });
};

/** 编辑配载信息 */
const handleEditStowage = ({ row }) => {
  $store.commit('DEL_ONCE_TAG', '/distribution/artery/AddVehicleStowage');

  $router.push({
    path: '/distribution/artery/AddVehicleStowage',
    query: { name: `${row.carsNo} - 编辑配载`, type: 2, loadId: row.id },
  });
};

/** 前往配载详情 */
const handleGoWaybill = ({ row }) => {
  console.log('row :>> ', row);
  $router.push({
    path: '/distribution/artery/VehicleStowageDetails',
    query: {
      loadId: row.id,
      name: `${row.carsNo} - 配载详情`,
    },
  });
};

/**
 * 是否开启床车明细全屏
 * @params(_type) 开启或关闭
 */
const handleFullScrean = (_type: 'open' | 'close', _name: string) => {
  let _node = '';
  if (_name) _node = document.querySelectorAll(`.${_name} .maboxhi`);
  console.log('_node :>> ', _node);

  switch (_name) {
    case 'comparativeStatementPopUp':
      details.fullscreenObj.comparativeStatementPopUp =
        !details.fullscreenObj.comparativeStatementPopUp;
      break;

    default:
      details.fullscreenObj[_name] = !details.fullscreenObj[_name];
      if (_type === 'close') {
        if (_node) setNodeHeight(_node, '500px');
      } else {
        if (_node) setNodeHeight(_node);
      }
      break;
  }
};

/** 初始化请求数据 */
const init = async item => {
  const res = await postFindNextNodeList({ loadId: item.id });

  // 下一步节点数据
  const { code, data } = res.data;
  if (code !== 200) return;
  details.nextNodeData = data || [];

  if (details.nextNodeData.length !== 1) return;

  for (const iterator of details.packageData) {
    iterator.nodeName = details.nextNodeData[0].warehouseName;
    iterator.nodeId = details.nextNodeData[0].warehouseId;
  }
};

/** 发车 */
const handleStartCar = async () => {
  if (details.selectionList.length === 0) {
    return ElMessage({
      message: '请选择发车数据',
      type: 'warning',
    });
  } else if (details.selectionList.length !== 1) {
    return ElMessage({
      message: '仅支持单条数据操作',
      type: 'warning',
    });
  }

  try {
    details.loadingObj.pageLoading = true;

    // 判断是否有未有终点的装车数据
    const res = await postDetermineHasNoFinalNode({ loadId: details.selectionList[0].id });

    const { code, data } = res.data;
    if (code !== 200) return;
    // 根据data是否返值判断能否发车
    if (data) {
      details.popUpShow.truckLoadingDetailVisited = true;

      details.packageData = data || [];
      details.packageRenderData = details.packageData;

      // 初始化数据
      const _item = details.selectionList[0];
      init(_item);

      await nextTick();
      const _node = document.querySelector('.truckLoadingDetailPopUpTable');
      setNodeHeight(_node, '500px');
    } else {
      details.popUpShow.truckLoadingDetailVisited = false;

      ElMessageBox.confirm('确认发车吗?', '', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          details.loadingObj.pageLoading = true;
          const submitData = {
            loadId: details.selectionList.map(val => val.id).join(','),
            startCarType: '2',
          };

          const res = await postStartCarByLoadId(submitData);
          const { code } = res.data;
          if (code !== 200) {
            return;
          }
          ElMessage({
            type: 'success',
            message: '发车成功',
          });

          onLoad();
        } catch (error) {
          console.log('error :>> ', error);
        } finally {
          details.loadingObj.pageLoading = false;
        }
      });
    }
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.pageLoading = false;
  }
};

/** 取消发车 */
const handleEndCar = async () => {
  if (details.selectionList.length === 0) {
    return ElMessage({
      message: '请选择发车数据',
      type: 'warning',
    });
  } else if (details.selectionList.length !== 1) {
    return ElMessage({
      message: '仅支持单条数据操作',
      type: 'warning',
    });
  }

  ElMessageBox.confirm('确认取消发车吗?', '', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      details.loadingObj.pageLoading = true;
      const submitData = {
        loadId: details.selectionList.map(val => val.id).join(','),
        startCarType: '2',
      };

      const res = await postCancelStartCarByLoadId(submitData);
      const { code } = res.data;
      if (code !== 200) {
        return;
      }
      ElMessage({
        type: 'success',
        message: '取消成功',
      });

      onLoad();
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.pageLoading = false;
    }
  });
};

/** 开启弹窗 */
const handleOpenConfiguration = (type: 'one' | 'batch', data = {}) => {
  if (type === 'batch' && details.packageSelectedData.length === 0)
    return ElMessage.warning('最少选择一条数据');
  details.modifyData = type === 'one' ? [data.row] : details.packageSelectedData;
  details.popUpShow.chooseDestinationVisited = true;
};

/** 配置装车目的地 */
const handleEditSubmit = () => {
  const chooseItem = details.nextNodeData.find(val => val.warehouseId === details.chooseNodeId);

  for (const iterator of details.modifyData) {
    iterator.nodeName = chooseItem.warehouseName;
    iterator.nodeId = chooseItem.warehouseId;
  }

  details.popUpShow.chooseDestinationVisited = false;
};

/** 移除 */
const removePackage = async ({ row }) => {
  try {
    details.loadingObj.truckLoadingDetailPopUpLoading = true;

    const submitData = {
      orderCode: row.orderCode,
      carsLoadScanIds: row.id,
    };

    const res = await postRemoveCarsLoadScan(submitData);
    if (res.data.code !== 200) return;
    ElMessage.success(res.data.msg || '移除成功');

    await handleStartCar();
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.truckLoadingDetailPopUpLoading = false;
  }
};

/** 确认配置 */
const handleSubmit = async () => {
  details.loadingObj.truckLoadingDetailPopUpLoading = true;
  try {
    const submitData = {
      loadId: details.selectionList[0].id,
      loadScanFinalNodeIdList: [],
    };

    details.packageData.forEach(val => {
      if (val.nodeId)
        submitData.loadScanFinalNodeIdList.push({ loadScanId: val.id, finalNodeId: val.nodeId });
    });

    const res = await postUpdateLoadScanFinalNodeIdById(submitData);

    if (res.data.code !== 200) return;
    details.popUpShow.truckLoadingDetailVisited = false;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.truckLoadingDetailPopUpLoading = false;
  }
};

/** 输入筛选 */
const packageInputsc = (value, row) => {
  // 动态设置正则
  const reg = new RegExp('^' + value);

  details.packageQuery[row.prop] = reg;

  if (value === '') delete details.packageQuery[row.prop];

  if (Object.keys(details.packageQuery).length === 0)
    return (details.packageRenderData = details.packageData);

  const _data = details.packageData.filter(item => {
    let _flag = true;
    for (let key in details.packageQuery) {
      if (!details.packageQuery[key].test(item[key])) _flag = false;
      if (!_flag) break;
    }

    return _flag;
  });

  details.packageRenderData = _data;
};

/** 卸车确认 */
const handleUnloadByLoadId = (type: 1 | 2) => {
  if (details.selectionList.length === 0) return ElMessage.warning('请选择需要卸车的数据');
  if (details.selectionList.length > 1) return ElMessage.warning('只支持单条数据操作');

  ElMessageBox.confirm('确认卸车吗?', '', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      details.loadingObj.pageLoading = true;

      const submitData = {
        loadId: details.selectionList.map(val => val.id).join(','),
        unloadType: type,
      };

      const res = await postUnloadByLoadId(submitData);
      const { code } = res.data;
      if (code !== 200) {
        return;
      }
      ElMessage({
        type: 'success',
        message: '卸车成功',
      });

      onLoad();
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.pageLoading = false;
    }
  });
};

/** 显示装载清单 */
const handleShowListOfLoadedWagons = async () => {
  try {
    if (details.selectionList.length === 0) return ElMessage.warning('请选择装载清单');
    if (details.selectionList.length > 1) return ElMessage.warning('只能选择一个装载清单');
    details.loadingObj.pageLoading = true;
    const { id } = details.selectionList[0];

    const res = await postFindLoadingListData({ loadId: id });
    const { code, data } = res.data;

    if (code !== 200) return;
    details.popUpShow.listOfLoadedWagons = true;
    details.listOfLoadedWagonsData = data;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.pageLoading = false;
  }
};

/** 手动装车 */
const handleManualLoading = ({ row }) => {
  console.log('row :>> ', row);
  ElMessageBox.confirm(`是否进行手动装车?`)
    .then(async () => {
      try {
        details.loadingObj.pageLoading = true;

        const response = await postManualLoadingloadId({ loadId: row.id });
        if (response.data.code !== 200) return;
        ElMessage.success(response.data.msg);
        onLoad();
      } catch (error) {
        console.log('error :>> ', error);
      } finally {
        details.loadingObj.pageLoading = false;
      }
    })
    .catch(() => {
      // catch error
    });
};

/** 显示卸车报告 */
const handleShowUnloadReport = async () => {
  if (details.selectionList.length === 0) return ElMessage.warning('请选择装载清单');
  if (details.selectionList.length > 1) return ElMessage.warning('只能选择一个装载清单');
  try {
    details.loadingObj.pageLoading = true;

    const { id } = details.selectionList[0];

    const res = await postFindWarehouseUnloadReport({ loadId: id });
    const { code, data } = res.data;

    if (code !== 200) return;
    details.popUpShow.unloadReport = true;
    details.unloadReportInfo = data;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.pageLoading = false;
  }
};

/** 节点费用 */
const handleNodeCost = ({ row }) => {
  $store.commit('DEL_ONCE_TAG', '/distribution/artery/AddVehicleStowage');

  $router.push({
    path: '/distribution/artery/AddVehicleStowage',
    query: { name: '节点费用更改', type: 3, loadId: row.id },
  });
};

/** 配置直发商家弹窗显示 */
const handleDirectGoMarketVesited = ({ row }) => {
  $router.push({
    path: '/distribution/artery/directGoMarket',
    query: {
      loadId: row.id,
      name: row.carsNo + '--' + '配置直发商家',
      backPath: $route.fullPath,
    },
  });
};

/** 直发商家签收详情 */
const handleDirectGoMarketDetails = ({ row }) => {
  $router.push({
    path: '/distribution/artery/directGoMarketDetails',
    query: {
      loadId: row.id,
      name: row.carsNo + '--' + '签收详情',
      backPath: $route.fullPath,
    },
  });
};
</script>

<style scoped lang="scss">
.fo-fl {
  display: flex;
}

// 日期选择器
:deep(.el-date-editor.el-input) {
  height: 100% !important;
  width: 100% !important;
}

:deep(.el-range-editor.el-input__wrapper) {
  height: 100% !important;
}

.ml {
  margin: 5px;
  color: var(--el-color-primary);
}

.dialog_container {
  max-height: 60vh;
  overflow-y: scroll;

  &.fullScreen {
    max-height: 85vh;
  }
}

// 卸车
.unloadInfo_Container {
  .title {
    font-size: 1.3rem;
    color: var(--el-color-primary);
    font-weight: bold;
    display: flex;
    align-items: center;

    &::before {
      content: '';
      display: inline-block;
      width: 3px;
      height: 1rem;
      background-color: var(--el-color-primary);
      margin-right: 10px;
    }
  }

  .content {
    margin-top: 10px;
    font-weight: bold;
  }

  .dialog-footer {
    text-align: end;
  }
}

:deep(.el-text) {
  &.gray {
    color: #808080 !important;
    font-weight: bold;
  }

  &.red {
    color: red !important;
    font-weight: bold;
  }

  &.green {
    color: green !important;
    font-weight: bold;
  }
}

.mr0 {
  margin-right: 0 !important;
}
</style>
