<template>
  <basic-container>
    <div class="avue-crud" v-loading="details.loadingObj.pageLoading">
      <!-- 搜索模块 -->
      <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-input v-model="query.stockupArea" placeholder="请输入备货区"></el-input>-->
            <el-date-picker
              v-model="stockupDate"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              clearable
            />
          </el-form-item>
          <el-form-item label="实际发车:" class="el-times">
            <!--            <el-input v-model="query.stockupArea" placeholder="请输入备货区"></el-input>-->
            <el-date-picker
              v-model="stockupDate"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              clearable
            />
          </el-form-item>
          <el-form-item label="创建时间:" class="el-times">
            <!--            <el-input v-model="query.stockupArea" placeholder="请输入备货区"></el-input>-->
            <el-date-picker
              v-model="stockupDate"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              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>

      <!-- 控件模块 -->
      <el-row>
        <div class="avue-crud__header">
          <!-- 头部左侧按钮模块 -->
          <div class="avue-crud__left">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增配载 </el-button>
            <el-button type="primary" icon="el-icon-printer" @click="searchReset">打 印</el-button>
            <el-button type="primary" icon="el-icon-printer" @click="searchReset"
              >装载清单</el-button
            >
            <el-button type="primary" icon="el-icon-printer" @click="searchReset"
              >装载卸车清单(财务)</el-button
            >
            <el-button type="primary" icon="el-icon-van" @click="handleStartCar">发 车</el-button>
            <el-button type="primary" icon="el-icon-delete" @click="handleCancelStartCar"
              >取消发车</el-button
            >
            <el-button type="primary" icon="el-icon-delete" @click="handleCancelCarsLoad"
              >取消配载</el-button
            >
            <el-button type="primary" icon="el-icon-document" @click="handleComparativeStatement"
              >对比报表</el-button
            >
            <el-button type="primary" icon="el-icon-document" @click="searchReset"
              >卸车报告</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>
      </el-row>

      <!-- 表格 -->
      <!-- 列表模块 -->
      <tablecmt
        :columnList="details.columnList"
        :tableData="data"
        :loading="loadingObj.list"
        @inputTxt="inputsc"
        @timeCheck="timesc"
        @btnCheck="btnsc"
        @selectCheck="selectsc"
        @selection="selectionChange"
      >
        <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-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.realLoadingNumber || 0 }}</span>
                  </div>
                  <div>
                    <span class="mr-10">操作人:</span>
                    <span>{{ item.arriveUserName || item.startUserName || '暂无数据' }}</span>
                  </div>
                  <div>
                    <span class="mr-10">状态:</span>
                    <span>{{
                      loadStatus.find(val => val.code === Number(item.nodeStatus)).label
                    }}</span>
                  </div>
                </template>
                <el-text>{{ item.nodeName }}</el-text>
              </el-tooltip>
              <!-- <el-text @click="handleGoWaybill(slotProps.scope)">
                {{ item.nodeName }}
              </el-text> -->
              <el-icon
                style="margin: 5px"
                v-if="index !== slotProps.scope.row.carsLoadLineList.length - 1"
                ><Right
              /></el-icon>
            </span>
          </template>

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

          <template v-if="slotProps.scope.column.label === '操作'">
            <div class="handleControl">
              <el-text @click="handleShowzeroAdditionalRecording(slotProps.scope)">
                零担补录
              </el-text>
              <el-text @click="handleShowTruckLoadingDetails(slotProps.scope)"> 装车明细 </el-text>
              <el-text
                v-if="Mydata.id === slotProps.scope.row.nowWarehouseId"
                @click="handleEditStowage(slotProps.scope)"
              >
                编辑
              </el-text>

              <el-dropdown>
                <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">
                      <el-text @click="handleNodeCost(slotProps.scope)"> 节点费用 </el-text>
                    </el-dropdown-item>

                    <el-dropdown-item v-if="Mydata.id === slotProps.scope.row.nowWarehouseId">
                      <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="Mydata.id === slotProps.scope.row.nowWarehouseId">
                      <el-text @click="handleManualLoading(slotProps.scope)"> 手动装车 </el-text>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </template>
      </tablecmt>

      <!-- 统计 -->
      <!-- <el-row>
        <div>选择数: , 运单数: , 件数: , 重量: , 体积: , 提货费: ,</div>
        <div>总计: 总数: , 运单数: , 件数: , 重量: , 体积: , 提货费: ,</div>
      </el-row> -->

      <!-- 分页模块 -->
      <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)"
      >
        <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>

  <!-- 列表配置显示 -->
  <edittablehead
    @setcolum="setnewcolum"
    @closce="showdrawer"
    :drawerShow="drawerShow"
    :columnList="details.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 } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import { downloadXls, setNodeHeight, debounce } from '@/utils/util';
import { columnList, packageColumnList } from '@/option/distribution/VehicleStowage';
import {
  postloadCarsPageList,
  postStartCarByLoadId,
  postCancelStartCarByLoadId,
  postCancelCarsLoadByLoadId,
  postDetermineHasNoFinalNode,
  postFindNextNodeList,
  postUpdateLoadScanFinalNodeIdById,
  postRemoveCarsLoadScan,
  postManualLoadingloadId,
} from '@/api/distribution/VehicleStowage';
import { useStore } from 'vuex';
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')); //获取本地仓库信息

console.log('Mydata :>> ', Mydata);

const details = reactive<any>({
  /** 是否开启搜索 */
  search: true,
  /** 表格搜索条件 */
  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,
  /** 列表数据 */
  data: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    /** 配置装车目的地详情 */
    truckLoadingDetailPopUpLoading: false,
    /** 页面laoding */
    pageLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 弹出层显示 */
  popUpShow: {
    /** 配置目的地 */
    truckLoadingDetailVisited: false,
    /** 对比报表 */
    comparativeStatementPopUp: false,
    /** 选择目的地弹窗 */
    chooseDestinationVisited: false,
  },
  /** 列表Dom节点 */
  listNode: '',
  form: {},
  /** 全屏 */
  fullscreenObj: {
    /** 装车明细 */
    truckLoadingDetailPopUp: false,
    comparativeStatementPopUp: false,
  },
  packageColumnList,
  /** 配置装车目的地数据 */
  packageData: [],
  /** 配置装车目的地数据 -- 渲染数据 */
  packageRenderData: [],
  /** 后续装车目的地 */
  nextNodeData: [],
  /** 配置目的地 -- 被选中的数据 */
  packageSelectedData: [],
  /** 被修改的数据 */
  modifyData: [],
  /** 被选中的数据 */
  chooseNodeId: '',
  packageQuery: {},
});

/** 车辆状态字典 */
const carStateDictionaries = reactive([
  { label: '未发车', code: 0 },
  { label: '已发车', code: 10 },
  { label: '网点到车', code: 20 },
  { label: '网点发车', code: 30 },
  { label: '终点到车', code: 40 },
  { label: '取消配载', code: 100 },
]);

const loadStatus = reactive([
  { label: '未到达', code: 0 },
  { label: '已到车', code: 10 },
  { label: '已发车', code: 20 },
]);

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

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

onMounted(() => {
  const timer = setTimeout(() => {
    details.listNode = document.querySelector('.maboxhi');
    details.listNode.style.transition = 'all .5s ease-out';
    console.log('details.listNode :>> ', details.listNode);
    clearTimeout(timer);
  }, 100);

  /**
   * 初始化获取本地缓存的编辑隐藏的列表
   *  固定搭配，不能更改
   */
  let checkListnewarr = functions.getStorage(window.location.pathname + 'checkList');
  let flexListnewarr = functions.getStorage(window.location.pathname + 'flexList');
  let sortlistnewarr = functions.getStorage(window.location.pathname + 'sortlist');
  if (checkListnewarr) {
    details.columnList.map(item => {
      item.head = false;
    });
    checkListnewarr.map(ite => {
      details.columnList.map(item => {
        if (ite == item.label) {
          item.head = true;
        }
      });
    });
  } else {
    let arr = [];
    details.columnList.map(item => {
      if (item.head) {
        arr.push(item.label);
      }
    });
    functions.setStorage(window.location.pathname + 'checkList', arr);
  }
  if (flexListnewarr) {
    details.columnList.map(item => {
      item.fixed = false;
    });
    flexListnewarr.map(ite => {
      details.columnList.map(item => {
        if (ite == item.label) {
          if (item.type == 6) {
            item.fixed = 'right';
          } else {
            item.fixed = true;
          }
        }
      });
    });
  } else {
    let arr = [];
    details.columnList.map(item => {
      if (item.fixed) {
        arr.push(item.label);
      }
    });
    functions.setStorage(window.location.pathname + 'flexList', arr);
  }
  if (sortlistnewarr) {
    details.columnList.map(item => {
      item.sortable = false;
    });
    sortlistnewarr.map(ite => {
      details.columnList.map(item => {
        if (ite == item.label) {
          item.sortable = true;
        }
      });
    });
  } else {
    let arr = [];
    details.columnList.map(item => {
      if (item.sortable) {
        arr.push(item.label);
      }
    });
    functions.setStorage(window.location.pathname + 'sortlist', arr);
  }
});

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

    // 请求页面数据
    const res = await postloadCarsPageList(details.page, { ...details.query, ...params });
    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = data.records.map(val => {
      val.loadStatusName = carStateDictionaries.find(
        item => Number(val.loadStatus) === item.code
      ).label;
      return val;
    });
    details.page.total = data.total;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.list = false;
  }
};

const initOnload = () => {
  details.page.pageNum = 1;
  onLoad();
};

initOnload();
/** 初始化请求数据 */
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 searchChange = () => {
  initOnload();
};

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

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

/** 是否开启搜索区 */
const searchHide = () => {
  details.search = !details.search;

  setNodeHeight(details.listNode, '', true);
};

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

/** 表格表头时间选择 */
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];
  }
  initOnload();
};

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

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

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

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

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

/**
 * 设置列表 -- 固定函数
 * 弹窗的勾选回调，用于更改头部数组
 * 固定搭配，只需要更换   columnList
 *  */
const setnewcolum = (newarr, headarr, 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 handleComparativeStatement = () => {
  if (details.selectionList.length === 0) {
    return ElMessage({
      type: 'warning',
      message: '请选择要对比的数据',
    });
  }

  $router.push('/waybill/ComparativeStatement');
  /* details.popUpShow.comparativeStatementPopUp = true;

  nextTick(() => {
    // 获取弹窗内表格元素节点, 并设置高度
    const _node = document.querySelectorAll('.comparativeStatementPopUp .maboxhi');
    setNodeHeight(_node, 'auto');
  }); */
};

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

  // details.popUpShow.truckLoadingDetailVisited = true;

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

/** 显示零担补录 */
const handleShowzeroAdditionalRecording = ({ row }) => {
  // 跳转到零担补录页面
  $router.push({
    path: '/distribution/artery/zeroAdditionalRecording',
    query: {
      name: '零担补录',
      loadId: row.id,
    },
  });
};

/**
 * 是否开启床车明细全屏
 * @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 handleAdd = () => {
  $router.push({
    path: '/distribution/artery/AddVehicleStowage',
    query: { name: '新增配载', type: 1 },
  });
};

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

/** 节点费用 */
const handleNodeCost = ({ row }) => {
  $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,
    },
  });
};

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

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

  // 判断是否有未有终点的装车数据
  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 () => {
      const submitData = {
        loadId: details.selectionList.map(val => val.id).join(','),
        startCarType: '1',
      };

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

      initOnload();
    });
  }
};

/** 开启弹窗 */
const handleOpenConfiguration = (type: 'one' | 'batch', data = {} as any) => {
  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,
      carsLoadScanId: row.id,
    };

    const res = await postRemoveCarsLoadScan(submitData);
    if (res.data.code !== 200) return;

    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, 'i');

  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 handleCancelStartCar = () => {
  if (details.selectionList.length === 0) {
    return ElMessage({
      message: '请选择发车数据',
      type: 'warning',
    });
  } else if (details.selectionList.length !== 1) {
    return ElMessage({
      message: '仅支持单条数据操作',
      type: 'warning',
    });
  }
  ElMessageBox.confirm('确认取消发车吗?', 'Warning', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const submitData = {
      loadId: details.selectionList.map(val => val.id).join(','),
      startCarType: '1',
    };

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

/** 取消装车 */
const handleCancelCarsLoad = () => {
  if (details.selectionList.length === 0) {
    return ElMessage({
      message: '请选择发车数据',
      type: 'warning',
    });
  } else if (details.selectionList.length !== 1) {
    return ElMessage({
      message: '仅支持单条数据操作',
      type: 'warning',
    });
  }
  ElMessageBox.confirm('确认取消发车吗?', 'Warning', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const ids = [];
    const _flag = details.selectionList.every(val => {
      ids.push(val.id);
      console.log('val :>> ', val);
      return Number(val.loadStatus) === 0;
    });

    if (!_flag)
      return ElMessage({
        message: '车辆已发车, 无法取消配载计划',
        type: 'warning',
      });

    const submitData = {
      loadId: ids.join(','),
      startCarType: '1',
    };

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

/** 手动装车 */
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);
        initOnload();
      } catch (error) {
        console.log('error :>> ', error);
      } finally {
        details.loadingObj.pageLoading = false;
      }
    })
    .catch(() => {
      // catch error
    });
};
</script>

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

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

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

.fwb {
  font-weight: bold;
}

// 弹出层标题
.popUp_title {
  font-size: 18px;
  font-weight: bold;
  padding: 5px 20px;
  position: relative;
  margin: 20px 0;

  &:first-child {
    margin-top: 0;
  }

  &::before {
    width: 4px;
    height: 100%;
    background: #172e60;
    content: '';
    display: inline-block;
    position: absolute;
    top: 0;
    left: 0;
  }
}
.red {
  color: #ff0000;
}

.carsLineName {
  :deep(.el-text) {
    margin-right: 0px !important;
  }
}

.mr-10 {
  margin-right: 10px;
}

// 弹窗底部按钮
.dialog-footer {
  margin-top: 10px;
  text-align: center;
}

.w100 {
  width: 100%;
}

.handleControl {
  display: flex;
  align-items: center;

  :deep(.el-button) {
    font-size: 0.8rem;
  }

  :deep(.el-button + .el-button) {
    margin-left: 5px;
  }
}
</style>
