<template>
  <basic-container v-loading="details.loadingObj.submitLoading">
    <div class="avue-crud">
      <!-- 标题 基础信息 -->
      <el-divider content-position="left">
        <div class="flex-c-c">
          <el-icon class="mr10"><Document /></el-icon> 基础信息
        </div>
      </el-divider>
      <!-- 表单 -->
      <el-form
        :scroll-to-error="true"
        :inline="true"
        :rules="details.rules"
        ref="ruleFormRef"
        label-width="120px"
        :model="form"
        class="el-fr-d"
      >
        <div class="fo-fl">
          <div style="display: flex">
            <el-form-item label="中转承运商" prop="carrierName" style="flex: 1; margin-right: 10px">
              <el-select
                v-model="form.carrierName"
                filterable
                :teleported="false"
                remote
                reserve-keyword
                placeholder="中转承运商"
                @change="carrierNameChange"
                :remote-method="value => debounce(remoteMethod(value), 500)"
                :loading="details.loadingObj.carrierName"
              >
                <el-option
                  v-for="val in details.carrierNameOptions"
                  :key="val.carrierName"
                  :label="val.carrierName"
                  :value="val.carrierId"
                />
              </el-select>
            </el-form-item>
            <el-button type="primary" @click="handleAddCarrier" icon="Plus" />
          </div>
          <el-form-item label="经办人" prop="operator">
            <!-- <el-select
              v-model="form.operator"
              filterable
              :teleported="false"
              remote
              reserve-keyword
              placeholder="经办人"
              @change="val => carrierNameChange(val, index)"
              :remote-method="remoteMethod"
              :loading="details.loadingObj.loading"
              :disabled="index === 0"
            >
              <el-option
                v-for="val in details.carrierNameOptions"
                :key="val.operator"
                :label="val.operator"
                :value="val.carrierId"
              />
            </el-select> -->
            <el-input v-model="form.operator" />
          </el-form-item>
          <el-form-item label="送货方式" prop="deliveryType">
            <el-select
              :teleported="false"
              v-model="form.deliveryType"
              class="m-2"
              placeholder="送货方式"
              size="default"
              @change="
                val => {
                  console.log('val :>> ', val);
                  if (val + '' === '2') return;
                  details.form.driverName = '';
                  details.form.driverMobile = '';
                  details.form.carNumber = '';
                }
              "
            >
              <el-option
                v-for="item in details.pageInfo.deliveryType || []"
                :key="item.dictValue"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="付款方式" prop="payMethod">
            <el-select
              :teleported="false"
              v-model="form.payMethod"
              class="m-2"
              placeholder="付款方式"
              size="default"
            >
              <el-option
                v-for="item in details.pageInfo.payMethod || []"
                :key="item.dictValue"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="运费分摊方式" prop="chargeType">
            <el-select
              :teleported="false"
              v-model="form.chargeType"
              class="m-2"
              placeholder="运费分摊方式"
              size="default"
            >
              <el-option
                v-for="item in details.pageInfo.chargeType || []"
                :key="item.dictValue"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>
          <div style="display: flex">
            <el-form-item
              label="送货司机"
              prop="driverName"
              class="flex1 mr10"
              :rules="
                details.form.deliveryType + '' === '2'
                  ? [
                      {
                        required: true,
                        message: '请选择送货司机',
                        trigger: ['change', 'blur'],
                      },
                    ]
                  : [
                      {
                        required: false,
                      },
                    ]
              "
            >
              <SelectBox
                ref="driverSelectRef"
                className="goodsName"
                :input="() => remoteMethodDriver(details.form.driverName)"
                v-model="form.driverName"
                placeholder="输入司机名称"
                :disabled="details.form.deliveryType + '' !== '2'"
              >
                <div v-loading="details.loadingObj.driverName">
                  <template v-if="details.driverListByName.length > 0">
                    <div
                      v-for="val in details.driverListByName"
                      :key="val.carNumber"
                      class="carRow"
                      @click="() => handleNameChange(val)"
                    >
                      {{ val.driverName }}
                    </div>
                  </template>
                  <template v-else>
                    <div class="goodsNameRow">暂无数据</div>
                  </template>
                </div>
              </SelectBox>
            </el-form-item>

            <el-button type="primary" @click="handleAddVehicle" icon="Plus" />
          </div>

          <div style="display: flex">
            <el-form-item
              label="送货车辆"
              prop="carNumber"
              class="flex1 mr10"
              :rules="
                details.form.deliveryType + '' === '2'
                  ? [
                      {
                        required: true,
                        message: '请选择或输入车牌号',
                        trigger: ['change', 'blur'],
                      },
                    ]
                  : [
                      {
                        required: false,
                      },
                    ]
              "
            >
              <SelectBox
                ref="carSelectRef"
                className="goodsName"
                :input="handleFindCar"
                v-model="form.carNumber"
                placeholder="请选择车辆"
                :disabled="details.form.deliveryType + '' !== '2'"
              >
                <div v-loading="details.loadingObj.carNumber">
                  <template v-if="details.carListByName.length > 0">
                    <div
                      v-for="val in details.carListByName"
                      :key="val.carNumber"
                      class="carRow"
                      @click="() => handleChooseCar(val)"
                    >
                      {{ val.carNumber }}
                    </div>
                  </template>
                  <template v-else>
                    <div class="goodsNameRow">暂无数据</div>
                  </template>
                </div>
              </SelectBox>
            </el-form-item>

            <el-button type="primary" @click="handleAddCar" icon="Plus" />
          </div>

          <el-form-item label="客户类型" prop="customerType">
            <el-select
              :teleported="false"
              v-model="form.customerType"
              class="m-2"
              placeholder="客户类型"
              multiple
              size="default"
            >
              <el-option
                v-for="item in details.pageInfo.customerType || []"
                :key="item.dictValue"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否结算" prop="isSettlement">
            <el-select
              :teleported="false"
              v-model="form.isSettlement"
              class="m-2"
              placeholder="是否结算"
              size="default"
            >
              <el-option
                v-for="item in details.pageInfo.settlementStatus || []"
                :key="item.dictValue"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="代收贷款" prop="replacePrice">
            <el-input-number
              placeholder="代收贷款"
              v-model="form.replacePrice"
              :precision="2"
              :min="0"
              :step="1"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="承运单号" prop="carrierOrderCode">
            <el-input v-model="form.carrierOrderCode" placeholder="承运单号" />
          </el-form-item>
          <el-form-item label="承运时间" prop="carrierTimeStr">
            <el-date-picker
              v-model="form.carrierTimeStr"
              type="date"
              placeholder="承运时间"
              size="default"
              :teleported="false"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="客户收货时间" prop="receivingTimeStr">
            <el-date-picker
              v-model="form.receivingTimeStr"
              type="date"
              placeholder="客户收货时间"
              size="default"
              :teleported="false"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="运费" prop="countTransportCost">
            <el-input-number
              v-model="form.countTransportCost"
              :precision="2"
              placeholder="运费"
              :min="0"
              :step="1"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="司机结算费" prop="settlementValue">
            <el-input-number
              v-model="form.settlementValue"
              :precision="2"
              :min="0"
              placeholder="司机结算费"
              :step="1"
              controls-position="right"
            />
          </el-form-item>
          <div style="flex: none; width: 100%; padding-right: 0">
            <el-form-item style="width: 100%; margin: 0" label="备注" :inline="false">
              <el-input type="textarea" v-model="form.remark" placeholder="备注"
            /></el-form-item>
          </div>
        </div>
      </el-form>

      <!-- 标题 运单信息 -->
      <el-divider content-position="left">
        <div class="flex-c-c">
          <el-icon class="mr10"><Switch /></el-icon> 运单信息
        </div>
      </el-divider>

      <!-- 运单池 && 调度池 -->
      <div class="add_row">
        <!-- 列表模块 -->
        <div style="width: 49%">
          <div class="add_row_title">运单池</div>
          <div v-h5uShow="!search">
            <el-form
              :inline="true"
              label-width="80px"
              :model="details.oldQuery"
              class="header_search"
            >
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchReset()"
                  >搜 索</el-button
                >
                <el-button icon="el-icon-delete" @click="searchReset()">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 控件 -->
          <div style="margin-bottom: 10px" class="flex-c-sb">
            <div class="avue-crud__right">
              <el-button icon="el-icon-refresh" @click="searchChange" circle></el-button>
              <el-button icon="Operation" @click="showdrawer(true, '1')" circle></el-button>
              <el-button icon="el-icon-search" @click="searchHide" circle></el-button>
            </div>

            <el-button type="text" style="cursor: pointer" @click="handleAddWaybill">
              加入调度池
              <el-icon><CaretRight /></el-icon>
            </el-button>
          </div>
          <!-- 运单池表格 -->
          <tablecmt
            ref="oldColumnListNode"
            :columnList="details.columnList"
            :tableData="details.oldData"
            :loading="loadingObj.oldListLoading"
            @inputTxt="inputsc"
            @timeCheck="timesc"
            @selectCheck="selectsc"
            @selection="selectionChange"
            :tableRowClassName="handleSetRowClassName"
          >
          </tablecmt>
          <!-- 分页模块 -->
          <div class="avue-crud__pagination flex-c-sb" style="width: 100%">
            <el-pagination
              style="zoom: 0.9"
              background
              @size-change="sizeChange"
              @current-change="currentChange"
              :current-page="oldPage.pageNum"
              :page-sizes="[30, 50, 80, 120]"
              :page-size="oldPage.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="oldPage.total"
            >
            </el-pagination>
          </div>
        </div>

        <!-- 列表模块 -->
        <div style="width: 49%">
          <div class="add_row_title">调度池</div>
          <div v-h5uShow="!search">
            <el-form
              :inline="true"
              label-width="80px"
              :model="details.newQuery"
              class="header_search"
            >
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchReset()"
                  >搜 索</el-button
                >
                <el-button icon="el-icon-delete" @click="searchReset()">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <div style="margin-bottom: 10px" class="flex-c-sb">
            <el-button type="text" class="pointer" @click="handleRemoveWaybill">
              <el-icon><CaretLeft /></el-icon>
              移除调度池
            </el-button>

            <!-- 控件 -->
            <div class="avue-crud__right">
              <el-button icon="el-icon-refresh" @click="searchChange" circle></el-button>
              <el-button icon="Operation" @click="showdrawer(true, 2)" circle></el-button>
              <el-button icon="el-icon-search" @click="searchHide" circle></el-button>
            </div>
          </div>
          <!-- 调度池表格 -->
          <tablecmt
            ref="newColumnListNode"
            :columnList="details.newColumnList"
            :tableData="details.newData"
            @inputTxt="newInputsc"
            @timeCheck="newTimesc"
            @selectCheck="newSelectsc"
            @selection="newSelectionChange"
          >
            <template #default="slotProps">
              <template v-if="slotProps.scope.column.label === '计划数'">
                <!-- <el-text size="small" text @click="handleEditplanNum(slotProps.scope)">{{
                      slotProps.scope.row.planNum
                    }}</el-text> -->
                <el-input-number
                  v-model="slotProps.scope.row.planNum"
                  controls-position="right"
                  :precision="0"
                  :min="0"
                  :max="slotProps.scope.row.stockNum"
                  :step="1"
                />
              </template>
            </template>
          </tablecmt>
          <div>共 {{ details.newData.length }} 条</div>
        </div>

        <!-- <el-button></el-button> -->
      </div>

      <!-- 页面底部占位 -->
      <div class="footer"></div>
      <div class="button-container">
        <el-button class="submitButton" icon="Close" type="primary" @click="back"> 关闭 </el-button>

        <el-button
          class="submitButton"
          icon="Promotion"
          type="primary"
          :loading="details.loadingObj.submitLoading"
          @click="handleSubmit(ruleFormRef)"
        >
          提交
        </el-button>
      </div>
    </div>
  </basic-container>

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

<script lang="ts">
export default {
  name: '/distribution/artery/addTripartiteTransfer',
};
</script>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, nextTick, watch } from 'vue';
import functions from '@/utils/functions';
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import {
  downloadXls,
  computeNumber,
  setNodeHeight,
  debounce,
  deepClone,
  getObjType,
} from '@/utils/util';
import { columnList, newColumnList } from '@/option/distribution/addVehicleStowage';
import {
  postloadFindLoadInitData,
  postFindAllOrderList,
  postFindCarrierByName,
  postFindUseOrderList,
  postSelectEditDetailByLoadId,
  postFindCarListByName,
} from '@/api/distribution/AddVehicleStowage';
import {
  postSaveNewTripartiteTransfer,
  postUpdateTripartiteTransfer,
  postFindDriverListByNameAndWarehouseId,
} from '@/api/distribution/addTripartiteTransfer.js';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';

// 获取vuex仓库
const $store = useStore();

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

// 表单实例
const ruleFormRef = ref();

// 表格实例
const oldColumnListNode = ref();
const newColumnListNode = ref();

// 选择车辆
const carSelectRef = ref();
const driverSelectRef = ref();

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];
      },
    },
  ],
  /** 修改的列表信息 */
  editColumnList: [],
  /** 运单池 */
  columnList: deepClone(columnList),
  /** 调度池 */
  newColumnList: deepClone(newColumnList),
  /** 列表数据 */
  newData: [],
  newRenderData: [],
  oldData: [],
  rules: {
    /** 中转承运商 */
    carrierName: [
      {
        required: true,
        message: '请选择承运商',
        trigger: ['change', 'blur'],
      },
    ],
    /** 经办人 */
    operator: [
      {
        required: true,
        message: '请输入经办人',
        trigger: ['change'],
      },
    ],
    /** 送货方式 */
    deliveryType: [
      {
        required: true,
        message: '请选择送货方式',
        trigger: ['change'],
      },
    ],
    /** 付款方式 */
    payMethod: [
      {
        required: true,
        message: '请选择付款方式',
        trigger: ['change'],
      },
    ],
    /** 运费分摊方式 */
    chargeType: [
      {
        required: true,
        message: '请选择运费分摊方式',
        trigger: ['change'],
      },
    ],
    /** 是否结算 */
    isSettlement: [
      {
        required: true,
        message: '请选择结算状态',
        trigger: ['change'],
      },
    ],
    /** 客户类型 */
    customerType: [
      {
        required: true,
        message: '请选择客户类型',
        trigger: ['change'],
      },
    ],
    /** 承运单号 */
    carrierOrderCode: [
      {
        required: true,
        message: '请选择承运单号',
        trigger: ['change', 'blur'],
      },
    ],
    /** 承运时间 */
    carrierTimeStr: [
      {
        required: true,
        message: '请选择承运时间',
        trigger: ['change'],
      },
    ],
    /** 运费 */
    countTransportCost: [
      {
        required: true,
        message: '请填写运费',
        trigger: ['change'],
      },
    ],
    /** 签收时间 */
    receivingTimeStr: [
      {
        required: true,
        message: '请选择客户收货时间',
        trigger: ['change'],
      },
    ],
  },
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    oldListLoading: false,
    /** 承运商 */
    carrierName: false,
    /** 司机 */
    driverName: false,
    /** 车牌 */
    carNumber: false,
    /** 提交 */
    submitLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  newSelectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  oldPage: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 弹出层显示 */
  popUpShow: {
    /** 装车详情 */
    truckLoadingDetailVisited: false,
    /** 零担补录 */
    transferVisited: false,
  },
  form: {
    customerType: [],
  },
  /** 页面数据 */
  pageInfo: {},
  /** 承运商 */
  carrierNameOptions: [],
  /** 客户类型 */
  customerType: [],
  /** 送货司机 */
  driverListByName: [],
  /** 车辆 */
  carListByName: [],
  /** 被选中在调度池的订单列表 */
  orderCodeList: [],
  /** 修改时, 已存在调度池中的运单数据 */
  MappingData: [],
});

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

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

onMounted(async () => {
  await nextTick();
  setNodeHeight(document.querySelectorAll('.maboxhi'), '50vh', true);
});

/** 请求页面数据 */
const onLoad = async () => {
  const res = await postloadFindLoadInitData();

  details.form = {};
  await nextTick();
  ruleFormRef.value.resetFields();

  const { code, data } = res.data;
  if (code !== 200) return;
  details.pageInfo = data;
  details.customerType = data.customerType;
  console.log('data :>> ', data);
  details.form.startWarehouseName = data.startWarehouseInfo.warehouseName;
  details.form.startWarehouseId = data.startWarehouseInfo.warehouseId;
  details.form.endWarehouseNames = data.startWarehouseInfo.warehouseName;
  details.form.endWarehouseIds = data.startWarehouseInfo.warehouseId;
  details.form.carsLineName = data.startWarehouseInfo.warehouseName;

  details.form.operator = JSON.parse(localStorage.getItem('TWMS-userInfo')).content.nick_name;

  return await initOriginWarehouseOrder();
};

const onLoadEidt = async () => {
  // 获取表单信息
  const promiseAll = await Promise.all([
    // 获取下拉列表
    postloadFindLoadInitData(),
    // 获取表单数据
    postSelectEditDetailByLoadId({ loadId: $route.query.loadId }),
  ]);

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

  const [
    {
      data: { code, data },
    },
    {
      data: { code: code1, data: data1 },
    },
  ] = promiseAll;

  console.log('code :>> ', code);
  console.log('code1 :>> ', code1);

  if (code !== 200 && code1 !== 200) return;

  details.pageInfo = data;
  details.customerType = data.customerType;
  console.log('data :>> ', data);

  details.form = data1.carsLoadEntity;
  details.form.customerType = data1.carsLoadEntity.customerType.split(',');

  details.form.startWarehouseName = data.startWarehouseInfo.warehouseName;
  details.form.startWarehouseId = data.startWarehouseInfo.warehouseId;
  details.form.endWarehouseNames = data.startWarehouseInfo.warehouseName;
  details.form.endWarehouseIds = data.startWarehouseInfo.warehouseId;
  details.form.carsLineName = data.startWarehouseInfo.warehouseName;
  details.form.carrierTimeStr = details.form.carrierTime;
  details.form.receivingTimeStr = details.form.receivingTime;

  delete details.form.carrierTime;
  delete details.form.receivingTime;

  // 获取调度池数据
  await initDispatchOrder();

  // 获取运单池数据
  return await initOriginWarehouseOrder();
};

const initPageInfo = async () => {
  details.loadingObj.submitLoading = true;
  try {
    const { type } = $route.query;
    if (type === 'add') await onLoad();
    else if (type === 'edit') await onLoadEidt();
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.submitLoading = false;
  }
};

/** 请求添加在调度池中的数据 */
const initDispatchOrder = async () => {
  // 开启列表加载动画
  const submitData = {
    loadId: $route.query.loadId,
    finalNodeId: details.form.startWarehouseId,
  };
  const res = await postFindUseOrderList(submitData);
  const { code, data } = res.data;
  if (code !== 200) return;
  details.newData = data;
  details.newRenderData = data;
  details.MappingData = JSON.parse(JSON.stringify(data));

  details.orderCodeList = [];

  details.orderCodeList = [
    ...new Set([...details.orderCodeList, ...data.map(val => val.orderCode + ',' + val.waybillNo)]),
  ];
};

// watch(
//   $route,
//   () => {
//     initPageInfo();
//   },
//   { immediate: true }
// );
initPageInfo();

/** 请求运单数据 */
const initOriginWarehouseOrder = debounce(async function (params = {}) {
  try {
    details.loadingObj.oldListLoading = true;
    const submitData = {
      ...details.page,
      loadId: details.pageInfo.startWarehouseInfo.warehouseId,
      orderCodes: details.orderCodeList,
      ...details.query,
      ...params,
      isTransfer: 1,
    };
    if (submitData.orderCodes.length === 0) delete submitData.orderCodes;
    const res = await postFindAllOrderList(submitData);
    console.log('res :>> ', res);
    const { code, data } = res.data;
    if (code !== 200) return;
    details.oldData = data.records;
    details.oldPage.total = data.total;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.oldListLoading = false;
  }
}, 100);

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

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

// 清空复选框
const clearSelectionList = () => {
  details.selectionList = [];
  details.newSelectionList = [];
  console.log('newColumnListNode :>> ', newColumnListNode);
  console.log('oldColumnListNode :>> ', oldColumnListNode);
  newColumnListNode.value.handleCheckSelect([]);
  oldColumnListNode.value.handleCheckSelect([]);
};

/** 展开列表控件 */
const showdrawer = (_flag?: boolean, _type?: string) => {
  switch (_type) {
    default:
      console.log('123 :>> ', 123);
      details.editColumnList = details.columnList;
      break;
    // details.
  }
  details.drawerShow = _flag;
};

/** 是否开启搜索区 */
const searchHide = async () => {
  details.search = !details.search;
  await nextTick();
  setNodeHeight(document.querySelectorAll('.maboxhi'), '50vh', true);
};

/** 远程搜索承运商 */
const remoteMethod = async value => {
  try {
    console.log('value :>> ', value);
    details.loadingObj.carrierName = true;
    // if (!value) return;

    const res = await postFindCarrierByName({ carrierName: value });
    const { code, data } = res.data;
    if (code !== 200) return;
    details.carrierNameOptions = data;
  } catch (error) {
  } finally {
    details.loadingObj.carrierName = false;
  }
};

remoteMethod('');

/** 查询司机信息 */
const remoteMethodDriver = debounce(async val => {
  try {
    details.loadingObj.driverName = true;

    const res = await postFindDriverListByNameAndWarehouseId({ driverName: val });
    console.log('res :>> ', res);
    const { code, data } = res.data;
    if (code !== 200) return;
    details.driverListByName = data;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.driverName = false;
  }
}, 500);

remoteMethodDriver('');

/** 查询车辆 */
const handleFindCar = debounce(async value => {
  try {
    details.loadingObj.carNumber = true;
    console.log('value :>> ', value);

    const res = await postFindCarListByName({ carNumber: details.form.carNumber });

    const { code, data } = res.data;
    if (code !== 200) return;
    details.carListByName = data;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.carNumber = false;
  }
}, 500);

/** 选择车辆 */
const handleChooseCar = val => {
  details.form.carNumber = val.carNumber;
  // 关闭下拉框
  carSelectRef.value.handleClose();
};

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

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

/** 表格表头下拉框选择 */
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'];
  }
  initOriginWarehouseOrder();
};

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

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

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

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

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

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

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

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

/** 加入调度池 */
const handleAddWaybill = () => {
  details.selectionList.forEach(val => {
    val.planNum = val.stockNum;
    val.loadingNum = 0;
    details.newData.push(val);
  });
  details.orderCodeList = [
    ...new Set([
      ...details.orderCodeList,
      ...details.selectionList.map(val => val.orderCode + ',' + val.waybillNo),
    ]),
  ];
  console.log('details.orderCodeList :>> ', details.orderCodeList);

  const orderCodes = details.selectionList.map(val => val.orderCode);
  clearSelectionList();
  details.page.pageNum = 1;
  initOriginWarehouseOrder();
};

/** 移除调度池 */
const handleRemoveWaybill = () => {
  // 将被选中的数据筛选出去
  details.newData = details.newData.filter((val, index) => {
    const _flag = !details.newSelectionList.includes(val);
    if (!_flag) {
      const _code = val.orderCode + ',' + val.waybillNo;
      const _index = details.orderCodeList.indexOf(_code);
      // 删除映射的订单号+运单号
      details.orderCodeList.splice(_index, 1);
    }
    return _flag;
  });
  clearSelectionList();
  initOriginWarehouseOrder();
};

/** 新增承运商 */
const handleAddCarrier = () => {
  $router.push({ path: '/basicdata/carrier/basicdataCarrier' });
};

/** 新增车辆 */
const handleAddCar = () => {
  $router.push({ path: '/basicdata/vehicle/basicdataVehicleAddForm', query: { type: 'add' } });
};

/** 新增司机 */
const handleAddVehicle = () => {
  $store.commit('DEL_ONCE_TAG', 'basicdataDriverArteryAdd');

  $router.push({
    path: '/basicdata/driverArtery/basicdataDriverArteryAdd',
    query: {
      name: '司机信息新增',
      type: 'add',
      backPatch: '/basicdata/driverArtery/basicdataDriverArtery',
    },
  });
};

/** 选择承运商 */
const carrierNameChange = () => {
  const findValue = form.value.carrierName;
  const _value = details.carrierNameOptions.find(value => value.carrierId === findValue);

  form.value.carrierName = _value.carrierName;
  form.value.carrierId = _value.carrierId;
};

/** 司机改变时 */
const handleNameChange = val => {
  details.form.driverName = val.driverName;
  form.value.carNumber = val.carNumberList[0] || '';
  driverSelectRef.value.handleClose();
};

/** 关闭页面 */
const back = () => {
  $store.commit('DEL_TAG_CURRENT');
  $router.push({ path: '/distribution/artery/TripartiteTransfer' });
};

const addSubmit = async () => {
  const submitData = {
    ...form.value,
    addCarsLoadLineList: [
      {
        nodeType: '1',
        nodeName: details.pageInfo.startWarehouseInfo.warehouseName,
        nodeId: details.pageInfo.startWarehouseInfo.warehouseId,
        linkAddress: details.pageInfo.startWarehouseInfo.linkAddress,
        linkMan: details.pageInfo.startWarehouseInfo.linkMan,
        linkMobile: details.pageInfo.startWarehouseInfo.linkMobile,
        sort: '1',

        addList: JSON.parse(JSON.stringify(details.newData)).map(value => {
          value.nodeId = details.pageInfo.startWarehouseInfo.warehouseId;
          value.nodeName = details.pageInfo.startWarehouseInfo.warehouseName;
          value.finalNodeId = details.pageInfo.startWarehouseInfo.warehouseId;
          return value;
        }),
        removeList: [],
      },
    ],
    removeCarsLoadLineList: [],
  };

  submitData.customerType = submitData.customerType.join(',');

  if (submitData.carrierTimeStr)
    submitData.carrierTimeStr = dayjs(submitData.carrierTimeStr).format('YYYY-MM-DD');
  if (submitData.receivingTimeStr)
    submitData.receivingTimeStr = dayjs(submitData.receivingTimeStr).format('YYYY-MM-DD');
  console.log('submitData :>> ', submitData);

  const res = await postSaveNewTripartiteTransfer(submitData);
  const { code, msg } = res.data;
  if (code !== 200) return;
  ElMessage({
    message: msg,
    type: 'success',
  });
  back();
  console.log('res :>> ', res);
};

const editSubmit = async () => {
  const submitData = {
    ...form.value,
    addCarsLoadLineList: [
      {
        nodeType: '1',
        nodeName: details.pageInfo.startWarehouseInfo.warehouseName,
        nodeId: details.pageInfo.startWarehouseInfo.warehouseId,
        linkAddress: details.pageInfo.startWarehouseInfo.linkAddress,
        linkMan: details.pageInfo.startWarehouseInfo.linkMan,
        linkMobile: details.pageInfo.startWarehouseInfo.linkMobile,
        sort: '1',

        addList: [],
        removeList: [],
      },
    ],
    removeCarsLoadLineList: [],
  };

  const _deepCloneArr = JSON.parse(JSON.stringify(details.MappingData));

  for (const iterator of details.newData) {
    // 查看该运单是否已被添加在调度池 updateType 1: 编辑 2: 新增
    if (iterator.carsOrderId) {
      for (let index = 0; index < _deepCloneArr.length; index++) {
        const element = _deepCloneArr[index];

        if (element.carsOrderId === iterator.carsOrderId) {
          if (element.planNum !== iterator.planNum) {
            iterator.updateType = 1;
            submitData.addCarsLoadLineList[0].addList.push(iterator);
          }
          _deepCloneArr.splice(index, 1);
          // 退出循环
          break;
        }
      }
    } else {
      iterator.nodeId = details.pageInfo.startWarehouseInfo.warehouseId;
      iterator.nodeName = details.pageInfo.startWarehouseInfo.warehouseName;
      iterator.finalNodeId = details.pageInfo.startWarehouseInfo.warehouseId;
      iterator.updateType = 2;
      submitData.addCarsLoadLineList[0].addList.push(iterator);
    }
  }

  submitData.addCarsLoadLineList[0].removeList = _deepCloneArr;

  for (const iterator of submitData.addCarsLoadLineList[0].removeList) {
    iterator.id = iterator.carsOrderId;
  }

  submitData.customerType = submitData.customerType.join(',');

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

  const res = await postUpdateTripartiteTransfer(submitData);
  const { code, msg } = res.data;
  if (code !== 200) return;
  ElMessage({
    message: msg,
    type: 'success',
  });
  back();
};

/** 提交 */
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  console.log('111 :>> ', 111);
  formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('details.pageInfo :>> ', details.pageInfo);
      details.loadingObj.submitLoading = true;

      try {
        if ($route.query.type === 'add') await addSubmit();
        else if ($route.query.type === 'edit') await editSubmit();
      } catch (error) {
        console.log('error :>> ', error);
      } finally {
        details.loadingObj.submitLoading = false;
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/** 设置表格行样式 */
const handleSetRowClassName = (row, rowIndex) => {
  if (!row.warehouseEntryTimeStart) return 'timeOut';

  // 设置预警 -- 以入库时间为基准, 24小时后为超期, 临近2小时为临期

  // 当前时间 - 入库时间
  const time = Date.now() - new Date(row.warehouseEntryTimeStart).getTime();

  // 预警时间
  const WarningTime = 1000 * 60 * 60 * (24 * 2 - 2);

  // 超时
  const timeOut = 1000 * 60 * 60 * 24 * 2;

  if (time > timeOut) return 'timeOut';
  else if (time > WarningTime && time < timeOut) return 'WarningTime';
};
</script>

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

  > div {
    min-width: 25%;
    margin-right: 0px;
    padding: 0 10px;
    box-sizing: border-box;

    &:nth-child(4n) {
      padding-right: 0;
    }
  }
}

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

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

:deep(.el-select) {
  width: 100%;
  height: 100%;
}

:deep(.selectBox) {
  height: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

// 新增行
.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;
}

// 页面底部站位
.footer {
  height: 80px;
}

// 提交按钮
.button-container {
  z-index: 99;
  position: fixed;
  bottom: 30px;
  left: 50%;
}

// 标题
:deep(.el-divider__text.is-left) {
  font-size: 20px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.mr10 {
  margin-right: 10px;
  height: 40px;
}

:deep(.el-table__row) {
  height: 30px;
}

// 数字输入框
:deep(.nodeInfo .el-table .cell) {
  overflow: initial;
}

:deep(.slotbuts) {
  height: 30px;

  .el-input-number {
    height: 100%;
  }
}

// 错误提示
:deep(.el-form-item__error) {
  z-index: 99;
  --el-color-danger: #f00;
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  --el-color-danger: #f00;
}

:deep(
    .el-form-item.is-required:not(.is-no-asterisk).asterisk-left > .el-form-item__label:before,
    .el-form-item.is-required:not(.is-no-asterisk).asterisk-left
      > .el-form-item__label-wrap
      > .el-form-item__label:before
  ) {
  --el-color-danger: #f00;
}

.header_search > div {
  width: 40%;
}

.carRow {
  padding: 8px 10px;
  text-align: left;

  &:hover {
    background: #f5f7fa;
  }
}
</style>
