<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="结束时间"
              value-format="YYYY-MM-DD"
              :shortcuts="shortcuts"
              clearable
            />
          </el-form-item>

          <el-form-item label="车次号:" class="el-times">
            <el-input v-model="query.stockupArea" placeholder="请输入车次号"></el-input>
          </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 type="primary" icon="Plus" @click="addTransfer">新增中转 </el-button>
          <el-button type="primary" icon="Printer" @click="handleShowListOfLoadedWagons"
            >装载清单</el-button
          >
          <el-button type="primary" icon="Printer" @click="searchReset()"
            >装载卸车清单(财务)</el-button
          >
          <el-button type="primary" icon="Van" @click="handleConfirmStartCar">发 车</el-button>
          <el-button type="primary" icon="Delete" @click="handleCancelStartCar">
            取消发车
          </el-button>
          <!-- 到达 -->
          <el-button type="primary" icon="CircleCheck" @click="handleShowConfirm">
            到 达
          </el-button>
          <el-button type="primary" icon="Edit" @click="editTransfer">修 改</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"
      >
        <template #default="slotProps">
          <template v-if="slotProps.scope.column.label === '中转批次号'">
            <el-text @click="handleGoDetils(slotProps.scope)">{{
              slotProps.scope.row.carsNo
            }}</el-text>
          </template>

          <template v-if="slotProps.scope.column.label === '操作'">
            <!-- <el-text @click="handleShowzeroAdditionalRecording(slotProps.scope)"> 删除 </el-text> -->
            <el-text
              v-if="!slotProps.scope.row.signTime"
              @click="handleTheClerkSignsForIt(slotProps.scope)"
            >
              文员签收
            </el-text>
            <el-text @click="() => handleShowSiginImg(slotProps.scope)"> 上传签收图片 </el-text>
            <el-text
              v-if="Number(slotProps.scope.row.isSettlement) === 1"
              @click="handleShowCloseAnAccount(slotProps.scope)"
            >
              结算
            </el-text>
            <el-text @click="handleShowTruckLoadingDetails(slotProps.scope)">装车明细</el-text>
          </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.confirmArriveVisited"
    width="30%"
    :before-close="beforeClose"
    append-to-body
    class="confirmArriveVisited"
  >
    <el-form :inline="false" label-width="100px" :model="query">
      <el-form-item label="到达时间">
        <el-date-picker
          v-model="details.form.arriveDateStr"
          type="datetime"
          placeholder="到达时间"
          size="default"
        />
      </el-form-item>

      <el-form-item label="备注(非必填)">
        <el-input v-model="details.form.remark" type="textarea" placeholder="备注" size="default" />
      </el-form-item>
    </el-form>
    <div class="flex-c-c">
      <el-button
        @click="
          () => {
            details.form = {};
            details.popUpShow.confirmArriveVisited = false;
          }
        "
      >
        取消
      </el-button>
      <el-button type="primary" icon="Promotion" @click="submitConfirmArrive">提交</el-button>
    </div>
  </el-dialog>

  <!-- 确认到达信息 -->
  <el-dialog
    title="结算"
    v-model="details.popUpShow.closeAnAccountVisited"
    width="30%"
    append-to-body
    class="closeAnAccountVisited"
  >
    <el-form :inline="false" label-width="100px" :model="details.closeAnAccountForm">
      <el-form-item label="结算金额">
        <el-input-number
          style="width: 100%"
          :precision="2"
          :min="0"
          :step="1"
          controls-position="right"
          placeholder="请输入结算金额"
          v-model="details.closeAnAccountForm.number"
        />
      </el-form-item>
    </el-form>
    <div class="flex-c-c">
      <el-button
        @click="
          () => {
            details.form = {};
            details.popUpShow.closeAnAccountVisited = false;
          }
        "
      >
        取消
      </el-button>
      <el-button type="primary" icon="Promotion" @click="handleSubmitCloseAnAccount"
        >提交</el-button
      >
    </div>
  </el-dialog>

  <!-- 配置装车目的地 -->
  <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>

  <!-- 配载清单 -->
  <el-dialog
    title="配载清单"
    v-model="details.popUpShow.listOfLoadedWagons"
    width="80%"
    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,
      }"
    >
      <TripartiteTransferPrintTemplate :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>

  <!-- 列表配置显示 -->
  <edittablehead
    @setcolum="setnewcolum"
    @closce="showdrawer"
    :drawerShow="drawerShow"
    :columnList="details.editColumnList"
    v-model="details.editColumnList"
  ></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,
  deepClone,
  setNodeHeight,
  debounce,
  handleClearTableQuery,
} from '@/utils/util';
import { columnList, detailsColumnList } from '@/option/distribution/TripartiteTransfer';
import { packageColumnList } from '@/option/distribution/VehicleStowage';
import {
  postArriveCars,
  postTripartiteTransferPageList,
  postStartCars,
  postCancelStartCars,
  postSignCars,
  postSettlementCars,
  postTripartiteTransferFindSignPhoto,
  postTripartiteTransferUploadSignPhoto,
} from '@/api/distribution/TripartiteTransfer.js';
import { postFindLoadingListData } from '@/api/distribution/VehicleStowage';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import type { UploadProps } from 'element-plus';
import { getToken } from '@/utils/auth';

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

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: deepClone(columnList),
  /** 装车明细表头信息 */
  detailsColumnList: deepClone(detailsColumnList),
  /** 修改的列表信息 */
  editColumnList: [],
  /** 列表数据 */
  data: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    /** 配置装车目的地详情 */
    truckLoadingDetailPopUpLoading: false,
    /** 页面loading */
    pageLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 弹出层显示 */
  popUpShow: {
    /** 到达确认 */
    confirmArriveVisited: false,
    /** 配置目的地 */
    truckLoadingDetailVisited: false,
    /** 选择目的地弹窗 */
    chooseDestinationVisited: false,
    /** 结算弹窗 */
    closeAnAccountVisited: false,
    /** 装载清单 */
    listOfLoadedWagons: false,
    /** 上传签收图片 */
    uploadSiginImg: false,
  },
  /** 列表Dom节点 */
  listNode: '',
  form: {},
  /** 无用 */
  options: [],
  /** 付款方式 */
  payMethodOptions: [
    { value: 1, label: '现付' },
    { value: 2, label: '回付' },
  ],
  /** 配载状态 */
  loadStatusOptions: [
    { 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 },
  ],
  /** 是否结算 */
  isSettlementOptions: [
    { value: 1, label: '未结算' },
    { value: 2, label: '已结算' },
  ],
  /** 客户类型 */
  customerTypeOptions: [
    { value: 1, label: '商城' },
    { value: 2, label: 'C端客户' },
    { value: '1,2', label: '商城,C端客户' },
  ],
  /** 送货方式 */
  deliveryTypeOptions: [
    { value: 1, label: '自提' },
    { value: 2, label: '送货' },
  ],
  /** 全屏 */
  fullscreenObj: {
    /** 配置节点 */
    truckLoadingDetailPopUp: false,
    comparativeStatementPopUp: false,
    /** 装载清单 */
    listOfLoadedWagonsPopUp: false,
  },
  packageColumnList: deepClone(packageColumnList),
  /** 配置装车目的地数据 */
  packageData: [],
  /** 配置装车目的地数据 -- 渲染数据 */
  packageRenderData: [],
  /** 后续装车目的地 */
  nextNodeData: [],
  /** 配置目的地 -- 被选中的数据 */
  packageSelectedData: [],
  /** 被修改的数据 */
  modifyData: [],
  /** 被选中的数据 */
  chooseNodeId: '',
  packageQuery: {},
  /** 结算金额表单 */
  closeAnAccountForm: { number: 0 },
  listOfLoadedWagonsData: {},
  /** 预览图片地址 */
  dialogImageUrl: '',
  /** 上传图片文件list */
  fileList: [],
  viewImgList: [],
  viewImgIndex: 0,
  // 图片上传必须携带TOKEN
  headers: { 'Blade-Auth': 'Bearer ' + getToken() },
});

/** 表格实例 */
const tableNode = ref();
// details.columnList.payMethodName.checkArr = details.payMethodOptions;

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);

/** 转换码值 */
const handleConversionCodeValue = (item, label, Arr) => {
  const codes = Arr.map(item => item.value);
  console.log('codes :>> ', codes);

  let _index = codes.indexOf(Number(item[label]));
  if (_index === -1) _index = codes.indexOf(item[label]);
  item[label + 'Name'] = _index !== -1 ? Arr[_index].label : '未知';
};

/** 输入框赋值 */
const handleSetOption = (label, Arr) => {
  for (const iterator of details.columnList) {
    if (iterator.prop === label + 'Name') {
      iterator.checkarr = Arr;
      break;
    }
  }
};

onMounted(() => {
  // 表格下拉框赋值
  handleSetOption('payMethod', details.payMethodOptions);
  handleSetOption('loadStatus', details.loadStatusOptions);
  handleSetOption('isSettlement', details.isSettlementOptions);
  handleSetOption('customerType', details.customerTypeOptions);
  handleSetOption('deliveryType', details.deliveryTypeOptions);
});

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

    // 请求页面数据
    const res = await postTripartiteTransferPageList({
      ...details.page,
      ...details.query,
      ...params,
    });
    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = data.records;

    for (const item of details.data) {
      handleConversionCodeValue(item, 'payMethod', details.payMethodOptions);
      handleConversionCodeValue(item, 'loadStatus', details.loadStatusOptions);
      handleConversionCodeValue(item, 'isSettlement', details.isSettlementOptions);
      handleConversionCodeValue(item, 'customerType', details.customerTypeOptions);
      handleConversionCodeValue(item, 'deliveryType', details.deliveryTypeOptions);
    }
    details.page.total = data.total;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.list = false;
  }
}, 10);

// onLoad();
/** 初始化页面 */
const initPage = () => {
  details.page.pageNum = 1;
  onLoad();
};

initPage();

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

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

/** 展开列表控件 */
const showdrawer = (_flag?: boolean, _type?: string) => {
  switch (_type) {
    case 'truckLoadingDetail':
      details.editColumnList = details.detailsColumnList;
      break;

    default:
      console.log('123 :>> ', 123);
      details.editColumnList = details.columnList;
      break;
    // details.
  }
  details.drawerShow = _flag;
};

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

  setNodeHeight(tableNode.value.$el, '', true);
};

/** 表格表头输入框搜索 */
const inputsc = (index, row) => {
  details.query[row.prop] = index;
  if (index === '') 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) => {
  const _name = row.prop.replace('Name', '');

  details.query[_name] = index;
  if (!index) delete details.query[_name];

  onLoad();
};

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

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

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

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

/** 跳转零担补录 */
const handleShowzeroAdditionalRecording = ({ row }) => {
  // 跳转到零担补录页面
  $router.push('/distribution/artery/zeroAdditionalRecording');
};

/** 新增中转 */
const addTransfer = async () => {
  $router.push({
    path: '/distribution/artery/addTripartiteTransfer',
    query: { name: '新增中转', type: 'add' },
  });
};

/** 修改中转 */
const editTransfer = async () => {
  const _length = details.selectionList.length;

  if (_length === 0) return ElMessage.warning('请选择一条修改数据');

  if (_length > 1) return ElMessage.warning('只能选择一条数据修改');

  if (Number(details.selectionList[0].isSettlement) === 1)
    return ElMessage.warning('已结算, 无法修改');

  if (Number(details.selectionList[0].loadStatus) === 90)
    return ElMessage.warning('已签收, 无法修改');

  if (Number(details.selectionList[0].loadStatus) === 91)
    return ElMessage.warning('部分签收, 无法修改');

  const _item = details.selectionList[0];

  $router.push({
    path: '/distribution/artery/addTripartiteTransfer',
    query: {
      name: '编辑中转',
      type: 'edit',
      loadId: _item.id,
    },
  });
};

/** 开启到达弹窗 */
const handleShowConfirm = () => {
  if (details.selectionList.length === 0) {
    return ElMessage({
      message: '请选择到达数据',
      type: 'warning',
    });
  } else if (details.selectionList.length !== 1) {
    return ElMessage({
      message: '仅支持单条数据操作',
      type: 'warning',
    });
  }
  const _item = details.selectionList[0];
  details.popUpShow.confirmArriveVisited = true;
};

/** 提交到达 */
const submitConfirmArrive = async () => {
  if (!details.form.arriveDateStr) {
    return ElMessage({
      message: '请选择到达日期',
      type: 'warning',
    });
  }
  try {
    const submitData = {
      loadId: details.selectionList.map(val => val.id).join(','),
      ...details.form,
    };

    const res = await postArriveCars(submitData);
    const { code } = res.data;
    if (code !== 200) return;

    onLoad();

    ElMessage({
      type: 'success',
      message: '到达成功',
    });
    details.popUpShow.confirmArriveVisited = false;
  } catch (error) {
    console.log('error :>> ', error);
  }
};

/** 发车 */
const handleConfirmStartCar = () => {
  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 () => {
    const submitData = {
      loadId: details.selectionList.map(val => val.id).join(','),
    };

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

/** 取消发车 */
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('确认取消发车吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const submitData = {
      loadId: details.selectionList.map(val => val.id).join(','),
    };

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

/** 查看详情 */
const handleGoDetils = ({ row }) => {
  $router.push({
    path: '/distribution/artery/TripartiteTransferDetails',
    query: {
      name: row.carsNo + '-' + '中转详情',
      loadId: row.id,
    },
  });
};

/** 文员签收 */
const handleTheClerkSignsForIt = ({ row }) => {
  ElMessageBox.confirm('确认签收吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'success',
  }).then(async () => {
    const submitData = {
      loadId: row.id,
    };

    const res = await postSignCars(submitData);
    const { code } = res.data;
    if (code !== 200) {
      return;
    }
    ElMessage({
      type: 'success',
      message: '签收成功',
    });
    onLoad();
  });
};

/** 开启结算提交弹窗 */
const handleShowCloseAnAccount = ({ row }) => {
  details.closeAnAccountForm = row;
  details.closeAnAccountForm.number = Number(row.settlementValue || 0);
  details.popUpShow.closeAnAccountVisited = true;
};

/** 结算提交 */
const handleSubmitCloseAnAccount = async () => {
  try {
    const submitData = {
      loadId: details.closeAnAccountForm.id,
      settlementValue: details.closeAnAccountForm.number,
    };
    const res = await postSettlementCars(submitData);

    const { code, data } = res.data;
    if (code !== 200) return;

    ElMessage.success('结算成功');
    details.popUpShow.closeAnAccountVisited = false;
    initPage();
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
  }
};

/**
 * 是否开启床车明细全屏
 * @params(_type) 开启或关闭
 */
const handleFullScrean = (_type: 'open' | 'close', _name: string) => {
  let _node: any = '';
  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 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 handleShowSiginImg = async ({ row }) => {
  try {
    details.loadingObj.pageLoading = true;

    const res = await postTripartiteTransferFindSignPhoto({ loadId: row.id });

    details.popUpShow.uploadSiginImg = true;
    details.viewImgList = [];
    details.fileList = [];
    details.viewImgIndex = 0;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.pageLoading = false;
  }
};

/** 已上传的文件 */
const handlePictureCardPreview: UploadProps['onPreview'] = uploadFile => {
  details.viewImgList = details.fileList.map(val => val.url);
  details.viewImgIndex = details.viewImgList.indexOf(uploadFile.url);
  details.dialogImageUrl = uploadFile.url!;
  details.popUpShow.dialogVisible = true;
};

/** 上传成功 */
const handleSiginImgSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  details.viewImgList = details.fileList.map(val => val.url);
  for (let i = 0; i < details.fileList.length; i++) {
    const value = details.fileList[i];
    console.log('value :>> ', value);
    value.imgUrl = !value.response ? value.imgUrl : value.response.data.link;
  }
};

/** 图片删除 */
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  for (let i = 0; i < details.fileList.length; i++) {
    const value = details.fileList[i];

    if (value.url === uploadFile.url) details.fileList.splice(i, 1);
  }
};

/** 上传签收图片 */
const handleSubmitSiginImg = async () => {
  if (details.fileList.length === 0) return ElMessage.warning('请上传签收图片');
  try {
    details.loadingObj.pageLoading = true;

    const submitData = {
      signOrderId: $route.query.loadId,
      signPhotoList: [],
    };

    for (let i = 0; i < details.fileList.length; i++) {
      const value = details.fileList[i];

      // 存在id, 为已存在数据, 不做上传
      // if (value.id) continue

      submitData.signPhotoList.push({
        signOrderId: $route.query.loadId,
        photoType: 1,
        photoUrl: value.imgUrl,
      });
    }

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

    const res = await postUploadSignPhoto(submitData);

    const { code, data, msg } = res;
    if (code !== 200) return;
    ElMessage.success(msg);
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.pageLoading = false;
  }
};
</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;
}

// 新增行
.add_row {
  display: flex;
  justify-content: space-between;
}

.add_row_title {
  text-align: center;
  margin-bottom: 10px;
  font-size: 18px;
  font-weight: bold;
}

// 统计行
.statistics_row {
  margin: 10px 0;
  font-size: 14px;
  zoom: 0.9;
  display: flex;

  > div {
    margin-right: 20px;
  }
}

// 卡片容器
.crad_container {
  display: flex;

  .card_container_item {
    flex: 1;
    // padding: 10px;
    border-radius: 5px;
    box-shadow: 0 0 5px #ccc;

    &:first-child {
      margin-right: 20px;
    }

    .card_container_item_title {
      padding: 10px;
      border-bottom: 1px solid #ccc;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card_container_item_box {
      padding: 10px;
    }
  }
}

.pointer {
  cursor: pointer;
}

.transferPopUp :deep(.el-textarea) {
  width: 500px;
}

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

  &.fullScreen {
    max-height: 85vh;
  }
}
</style>
