<template>
  <basic-container>
    <!-- 首页表格 -->
    <div class="avue-crud">
      <!-- 搜索模块 -->
      <div v-h5uShow="search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="query" class="header_search">
          <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
              value-format="YYYY-MM-DD"
            />
          </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="Edit" @click="editClientInfo"> 修改客户信息 </el-button>

            <!-- 删除 -->
            <el-button type="primary" icon="Delete" @click="handleDelete"> 删除 </el-button>

            <!-- 开标签 -->
            <el-button type="primary" icon="Plus" @click="handleOpenAddTagDlog">开标签</el-button>

            <!-- 批量开标签导入 -->
            <el-button
              type="primary"
              icon="Upload"
              @click="
                () => {
                  if (!ChecksWhetherTheWarehouseIsSelected())
                    return ElMessage.warning('多仓权限无法操作，请选择仓库');
                  details.popUpShow.UploadBatch = true;
                  details.ouPaiChooseType = 0;
                }
              "
            >
              批量开标签导入
            </el-button>

            <!-- 欧派数据导入 -->
            <el-button
              type="primary"
              icon="Upload"
              @click="
                () => {
                  details.popUpShow.UploadPackageDelivery = true;
                  details.ouPaiChooseType = 0;
                }
              "
            >
              欧派数据导入
            </el-button>

            <!-- 冻结 -->
            <el-button type="primary" icon="Rank" @click="handleFreeze">冻结</el-button>
          </div>
          <!-- 头部右侧按钮模块 -->
          <div class="avue-crud__right">
            <el-button icon="el-icon-refresh" @click="searchChangeS" circle></el-button>
            <el-button icon="Operation" @click="showdrawer(true)" circle></el-button>
            <el-button icon="Search" @click="searchHide" circle></el-button>
          </div>
        </div>
      </el-row>

      <!-- 首页表格 -->
      <el-row>
        <!-- 列表模块 -->
        <tablecmt
          class="tableNode"
          :columnList="details.columnList"
          :tableData="data"
          :loading="loadingObj.list"
          @inputTxt="inputsc"
          @timeCheck="timesc"
          @selectCheck="selectsc"
          @selection="selectionChange"
        >
          <template #default="slotProps">
            <template v-if="slotProps.scope.column.label === '操作'">
              <div class="ElBtnClass">
                <el-text @click="handleShowPackageOrderList(slotProps.scope)">包明细</el-text>
              </div>
            </template>
          </template>
        </tablecmt>
      </el-row>

      <!-- 分页模块 -->
      <el-row class="el-fy">
        <div class="avue-crud__pagination flex-c-sb" style="width: 100%">
          <div></div>
          <el-pagination
            align="right"
            background
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page.currentPage"
            :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>

    <!-- 开标签 -->
    <el-dialog
      destroy-on-close
      :modal-append-to-body="false"
      :append-to-body="false"
      class="el-dialog-addTagVisited"
      width="70%"
      v-model="details.popUpShow.addTagVisited"
      :fullscreen="details.fullscreenObj.addTagVisited"
      :show-close="false"
      draggable
    >
      <!-- 标题 -- 头部控件区 -->
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header flex-c-sb" draggable>
          <div class="fwb" :id="titleId" :class="titleClass">开标签</div>
          <div class="flex-c-c">
            <!-- 全屏显示按钮 -->
            <el-button
              type="text"
              @click="handleFullScrean('open', 'addTagVisited')"
              v-if="!details.fullscreenObj.addTagVisited"
            >
              <el-icon class=""><FullScreen /></el-icon>
            </el-button>
            <el-button type="text" @click="handleFullScrean('close', 'addTagVisited')" v-else>
              <el-icon class=""><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.addTagLoading">
        <el-form
          ref="ruleFormRef"
          :model="details.addTagForm"
          :rules="details.addTagFormRules"
          :inline="true"
          label-width="100px"
        >
          <!-- 货品信息 -->
          <el-divider style="font-size: 28px">货品信息</el-divider>
          <el-form-item
            v-for="(item, index) in details.addTagInfo.cargoInfo"
            :key="item.label"
            :label="item.label"
            :prop="item.prop"
          >
            <template v-if="item.type === 'text'">
              <el-input
                :placeholder="`请输入${item.label}`"
                v-model="details.addTagForm[item.prop]"
                style="width: 200px"
                clearable
              />
            </template>

            <template v-if="item.type === 'number'">
              <el-input-number
                v-model="details.addTagForm[item.prop]"
                style="width: 200px"
                :precision="item.precision"
                :min="0"
                controls-position="right"
                :placeholder="`请输入${item.label}`"
                clearable
              />
            </template>

            <template v-if="item.type === 'cascader'">
              <el-cascader
                :placeholder="`请选择${item.label}`"
                :options="item.checkArr"
                style="width: 200px"
                v-model="details.addTagForm[item.prop]"
                :props="{
                  checkStrictly: true,
                }"
                filterable
                clearable
              >
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </template>

            <template v-if="item.type === 'select'">
              <el-select
                v-model="details.addTagForm[item.prop]"
                clearable
                filterable
                style="width: 200px"
                :placeholder="`请选择${item.label}`"
              >
                <el-option
                  v-for="val in item.checkArr"
                  :key="val.brandName"
                  :label="val.brandName"
                  :value="val.brandName"
                />
              </el-select>
            </template>
          </el-form-item>

          <div class="addTagRow">
            <!-- 寄货人信息 -->
            <div>
              <el-divider style="font-size: 28px">寄货人信息</el-divider>

              <el-form-item
                v-for="(item, index) in details.addTagInfo.SenderInfo"
                :key="item.label"
                :label="item.label"
                :prop="item.prop"
              >
                <el-input
                  style="width: 200px"
                  :placeholder="`请输入${item.label}`"
                  v-model="details.addTagForm[item.prop]"
                  clearable
                />
              </el-form-item>
            </div>

            <!-- 收货人信息 -->
            <div>
              <el-divider style="font-size: 28px">收货人信息</el-divider>

              <el-form-item
                v-for="(item, index) in details.addTagInfo.consigneeInfo"
                :key="item.label"
                :label="item.label"
                :prop="item.prop"
                clearable
              >
                <el-input
                  style="width: 200px"
                  :placeholder="`请输入${item.label}`"
                  v-model="details.addTagForm[item.prop]"
                  clearable
                />
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>

      <div class="flex-c-c dialog-footer">
        <el-button icon="Close" @click="details.popUpShow.addTagVisited = false"> 取 消 </el-button>
        <!-- 重置 -->
        <el-button
          icon="Refresh"
          type="primary"
          :loading="details.loadingObj.addTagLoading"
          @click="() => handleRefreshAddTag(ruleFormRef)"
        >
          重 置
        </el-button>

        <!-- 提交 -->
        <el-button
          icon="Position"
          type="primary"
          :loading="details.loadingObj.addTagLoading"
          @click="() => handleSubmitAddTag(ruleFormRef)"
        >
          提 交
        </el-button>
      </div>
    </el-dialog>

    <!-- 导入 -- 批量开标签 -->
    <el-dialog
      :modal-append-to-body="false"
      :append-to-body="false"
      class="el-dialog-UploadBatch"
      title="批量开标签导入"
      :visible.sync="details.popUpShow.UploadBatch"
      :width="details.orderStatus !== 'haveData' || details.ouPaiChooseType !== 0 ? '70%' : '40%'"
      v-model="details.popUpShow.UploadBatch"
    >
      <!-- 选择导入类型 -->
      <div v-loading="details.loadingObj.UploadLoadong" element-loading-text="数据处理中...">
        <template v-if="details.ouPaiChooseType === 0 && details.orderStatus === 'haveData'">
          <div style="text-align: center">
            <el-button type="primary" icon="Upload" @click="details.ouPaiChooseType = 1">
              有数据导入
            </el-button>
            <el-button type="primary" icon="Upload" @click="details.ouPaiChooseType = 2">
              无数据导入
            </el-button>
          </div>
        </template>

        <template v-else-if="details.orderStatus !== 'haveData' || details.ouPaiChooseType !== 0">
          <div>
            <el-divider content-position="left">{{
              details.ouPaiChooseType === 1 ? '有数据导入' : '无数据导入'
            }}</el-divider>
          </div>

          <P>请确认传入的文件为Excel文件格式</P>

          <el-button type="primary" icon="Download" @click="handleDownLoadFile">
            {{ details.ouPaiChooseType === 1 ? '包条码导入模板' : '无包条码导入模板' }}
          </el-button>

          <div v-loading="details.loadingObj.UploadLoadong" class="mt10">
            <el-upload
              class="upload-demo"
              drag
              :headers="details.header"
              :action="
                details.orderStatus === 'notHaveData'
                  ? '/api/logpm-trunkline/openOrder/importOrderNoPackage'
                  : details.ouPaiChooseType === 1
                  ? '/api/logpm-trunkline/openOrder/openLabelHasPacakage'
                  : '/api/logpm-trunkline/openOrder/batchOpenLabel'
              "
              :before-upload="handleBeforeUpload"
              :on-success="handleSuccess"
              :on-error="handleClose"
              multiple
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">拖拽文件或 <em>点击上传</em></div>
            </el-upload>
          </div>
        </template>
      </div>
    </el-dialog>

    <!-- 导入 -- 欧派 -->
    <el-dialog
      :modal-append-to-body="false"
      :append-to-body="false"
      class="el-dialog-UploadPackageDelivery"
      title="欧派数据导入"
      :visible.sync="details.popUpShow.UploadPackageDelivery"
      :width="details.ouPaiChooseType === 0 ? '40%' : '70%'"
      v-model="details.popUpShow.UploadPackageDelivery"
    >
      <!-- 选择导入类型 -->
      <div v-loading="details.loadingObj.UploadLoadong" element-loading-text="数据处理中...">
        <template v-if="details.ouPaiChooseType === 0">
          <div style="text-align: center">
            <el-button type="primary" icon="Upload" @click="details.ouPaiChooseType = 1">
              标准品导入
            </el-button>
            <el-button type="primary" icon="Upload" @click="details.ouPaiChooseType = 2">
              定制品导入
            </el-button>
          </div>
        </template>

        <template v-else>
          <div>
            <el-divider content-position="left">{{
              details.ouPaiChooseType === 1 ? '标准品导入' : '定制品导入'
            }}</el-divider>
          </div>

          <P>请确认传入的文件为Excel文件格式</P>

          <div v-loading="details.loadingObj.UploadLoadong">
            <el-upload
              class="upload-demo"
              drag
              :headers="details.header"
              :action="
                details.ouPaiChooseType === 1
                  ? '/api/logpm-trunkline/openOrder/importStandardOuPai'
                  : '/api/logpm-trunkline/openOrder/importCustomizedOuPai'
              "
              :before-upload="handleBeforeUpload"
              :on-success="handleSuccess"
              :on-error="handleClose"
              multiple
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">拖拽文件或 <em>点击上传</em></div>
            </el-upload>
          </div>
        </template>
      </div>
    </el-dialog>
  </basic-container>
  <!-- 列表配置显示 -->
  <edittablehead
    @setcolum="setnewcolum"
    @closce="showdrawer"
    :drawerShow="drawerShow"
    :columnList="details.columnList"
    v-model="details.columnList"
  ></edittablehead>
</template>

<script setup>
import { ref, reactive, toRefs, computed, onMounted, nextTick, watch } from 'vue';
import { columnList } from '@/option/warehouse/Prewarehouseorder.js';
import { processRowPropertyName, setNodeHeight, deepClone, downloadFileBase64 } from '@/utils/util';
import { getLazyTreeAll } from '@/api/base/region';
import { getToken } from '@/utils/auth';
import {
  $_getopenOrderAdvancePageList,
  postOpenOrderDeletedAdvance,
  postFindBrandList,
  postOpenLabel,
  postOpenOrderFreezeByAdvanceIds,
} from '@/api/waybill/TemporaryStorageList';
import { ElMessageBox, ElMessage } from 'element-plus';
import {
  downloadXls,
  handleClearTableQuery,
  ChecksWhetherTheWarehouseIsSelected,
} from '@/utils/util';
import { useStore } from 'vuex';
import { getDictionaryBiz } from '@/api/system/dict';
import dayjs from 'dayjs';
const $router = useRouter(); //跳转
const $useStore = useStore(); //权限
const $route = useRoute(); //获取地址栏参数
const ruleFormRef = ref(null);
const details = reactive({
  /** 是否开启搜索 */
  search: true,
  data: [],
  /** 表格搜索条件 */
  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),
  /** 列表数据 */
  haveDataData: [],
  notHaveDataData: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    haveDataList: false,
    notHaveDataList: false,
    packageListLoading: false,
    /** 开标签 */
    addTagLoading: false,
    /** 上传 */
    UploadLoadong: false,
    pageLoading: false,
    /** 列表加载loading */
    list: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    currentPage: 1,
    pageSize: 50,
    total: 0,
  },

  /** 包明细分页参数 */
  packageListPage: {
    currentPage: 1,
    pageSize: 30,
    total: 0,
  },
  /** 弹出层显示 */
  popUpShow: {
    /** 包件明细 */
    packageOrderListlVisited: false,
    /** 导入 -- 家配 */
    UploadPackageDelivery: false,
    /** 导入 -- 批量开标前 */
    UploadBatch: false,
    /** 新增标签 */
    addTagVisited: false,
    /** 生成包条 */
    createPackge: false,
  },
  /** 列表Dom节点 */
  listNode: '',
  form: {},
  /** 全屏 */
  fullscreenObj: {
    /** 包明细 */
    packageOrderListlVisited: false,
    /** 开标签 */
    addTagVisited: false,
  },
  /** 打印的html */
  html: '',
  /** 头部 */
  header: {
    'Blade-Auth': 'bearer ' + getToken(),
  },
  /** 欧派上传选择上传类型 1 为 标准品 2 为 定制品 */
  ouPaiChooseType: 0,
  /** 开标签配置项 */
  addTagInfo: {
    // 货物信息
    cargoInfo: [
      {
        prop: 'serviceNum',
        type: 'text',
        label: '服务号',
        value: '',
        checkArr: [],
        rule: [
          { required: true, message: '请输入服务号', trigger: 'change' },
          { required: true, message: '请输入服务号', trigger: 'blur' },
        ],
      },
      {
        prop: 'orderCode',
        type: 'text',
        label: '订单自编号',
        value: '',
        checkArr: [],
        rule: [
          { required: true, message: '请输入订单自编号', trigger: 'change' },
          { required: true, message: '请输入订单自编号', trigger: 'blur' },
        ],
      },
      {
        prop: 'totalNumber',
        type: 'number',
        label: '订单总数量',
        value: 0,
        checkArr: [],
        precision: 0,
        rule: [
          { required: true, message: '请输入订单总件数', trigger: 'change' },
          { required: true, message: '请输入订单总件数', trigger: 'blur' },
        ],
      },
      {
        prop: 'area',
        type: 'cascader',
        label: '所属区域',
        value: '',
        checkArr: [],
        rule: [
          { required: true, message: '请选择所属区域', trigger: 'change' },
          { required: true, message: '请选择所属区域', trigger: 'blur' },
        ],
      },
      {
        prop: 'brand',
        type: 'select',
        label: '品牌',
        value: '',
        checkArr: [],
        rule: [
          { required: true, message: '请选择品牌', trigger: 'change' },
          { required: true, message: '请选择品牌', trigger: 'blur' },
        ],
      },
      {
        prop: 'firsts',
        type: 'text',
        label: '一级品类',
        value: '',
        checkArr: [],
        rule: [
          { required: true, message: '请输入一级品类', trigger: 'change' },
          { required: true, message: '请输入一级品类', trigger: 'blur' },
        ],
      },
      {
        prop: 'sencods',
        type: 'text',
        label: '二级品类',
        value: '',
        checkArr: [],
        rule: [
          { required: false, message: '请输入二级品类', trigger: 'change' },
          { required: false, message: '请输入二级品类', trigger: 'blur' },
        ],
      },
      {
        prop: 'thirds',
        type: 'text',
        label: '三级品类',
        value: '',
        checkArr: [],
        rule: [
          { required: false, message: '请输入三级品类', trigger: 'change' },
          { required: false, message: '请输入三级品类', trigger: 'blur' },
        ],
      },
      {
        prop: 'materialName',
        type: 'text',
        label: '物料名称',
        value: '',
        checkArr: [],
        rule: [{ required: false }],
      },
      {
        prop: 'volume',
        type: 'number',
        label: '体积',
        value: 0,
        checkArr: [],
        precision: 4,
        rule: [
          { required: false, message: '请输入体积', trigger: 'change' },
          { required: false, message: '请输入体积', trigger: 'blur' },
        ],
      },
      {
        prop: 'dealerCode',
        type: 'text',
        label: '商场编码',
        value: '',
        checkArr: [],
        rule: [
          { required: false, message: '请输入商场编码', trigger: 'change' },
          { required: false, message: '请输入商场编码', trigger: 'blur' },
        ],
      },
      {
        prop: 'dealerName',
        type: 'text',
        label: '商场名称',
        value: '',
        checkArr: [],
        rule: [
          { required: true, message: '请输入商场名称', trigger: 'change' },
          { required: true, message: '请输入商场名称', trigger: 'blur' },
        ],
      },
    ],
    // 寄件人信息
    SenderInfo: [
      {
        prop: 'senderName',
        type: 'text',
        label: '寄件人',
        value: '',
        checkArr: [],
        rule: [
          { required: false, message: '请输入寄件人名称', trigger: 'change' },
          { required: false, message: '请输入寄件人名称', trigger: 'blur' },
        ],
      },
      {
        prop: 'senderPhone',
        type: 'text',
        label: '寄件人电话',
        value: '',
        checkArr: [],
        rule: [
          { required: false, message: '请输入寄件人电话', trigger: 'change' },
          { required: false, message: '请输入寄件人电话', trigger: 'blur' },
        ],
      },
      {
        prop: 'senderAddress',
        type: 'text',
        label: '寄件人地址',
        value: '',
        checkArr: [],
        rule: [
          { required: false, message: '请输入寄件人地址', trigger: 'change' },
          { required: false, message: '请输入寄件人地址', trigger: 'blur' },
        ],
      },
    ],
    // 收件人信息
    consigneeInfo: [
      {
        prop: 'customerName',
        type: 'text',
        label: '客户名称',
        value: '',
        checkArr: [],
        rule: [
          { required: true, message: '请输入客户名称', trigger: 'change' },
          { required: true, message: '请输入客户名称', trigger: 'blur' },
        ],
      },
      {
        prop: 'customerPhone',
        type: 'text',
        label: '联系方式',
        value: '',
        checkArr: [],
        rule: [
          { required: true, message: '请输入联系方式', trigger: 'change' },
          { required: true, message: '请输入联系方式', trigger: 'blur' },
        ],
      },
      {
        prop: 'customerAddress',
        type: 'text',
        label: '收货地址',
        value: '',
        checkArr: [],
        rule: [
          { required: true, message: '请输入收货地址', trigger: 'change' },
          { required: true, message: '请输入收货地址', trigger: 'blur' },
        ],
      },
    ],
  },
  /** 开标签表单 */
  addTagForm: {},
  /** 开标签的必填项 */
  addTagFormRules: {},
  /** tab标签有无数据 */
  orderStatus: 'haveData',
});

const {
  search,
  query,
  shortcuts,
  stockupDate,
  data,
  loadingObj,
  selectionList,
  drawerShow,
  page,
  trickleLoadingPage,
  zeroAdditionalRecordingInfo,
  popUpShow,
  recorddata,
  defaultTime2,
} = toRefs(details);
/** 展开列表控件 */
const showdrawer = _flag => {
  details.drawerShow = _flag;
};
/** 表格表头输入框搜索 */
const inputsc = (index, row) => {
  processRowPropertyName(index, row, details.query);
  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 selectsc = (index, row) => {
  processRowPropertyName(index, row, details.query);
  onLoad();
};
/** 表格表头复选框选择 */
const selectionChange = list => {
  console.log(list);
  details.selectionList = list;
};
// 网页顶部搜索按钮
/** 搜索 */
const searchChange = () => {
  if (!details.stockupDate?.length) {
    delete details.query.startCreateTimeStr;
    delete details.query.endCreateTimeStr;
  } else {
    details.query.startCreateTimeStr = dayjs(details.stockupDate[0]).format('YYYY-MM-DD');
    details.query.endCreateTimeStr = dayjs(details.stockupDate[1]).format('YYYY-MM-DD');
  }
  onLoad();
};
// 每页多少条
const sizeChange = val => {
  details.page.pageSize = val;
  onLoad();
};
/** 页码改变执行的回调 */
const currentChange = val => {
  details.page.currentPage = val;
  onLoad();
};
// 刷新按钮
const searchChangeS = () => {
  details.search = false; //关闭搜索
  onLoad();
};
//清空
const searchReset = () => {
  details.query = {};
  details.page.currentPage = 1;
  handleClearTableQuery(details.columnList);
  onLoad();
};
// 顶部搜索
const searchHide = () => {
  console.log(details);
  details.search = !details.search;
  const _node = document.querySelector('.tableNode');
  setNodeHeight(_node, '', true);
};
// 字典公共函数
function updateDictionary(targetArray, dictionaryType) {
  getDictionaryBiz(dictionaryType).then(res => {
    console.log(res, '字典');
    res.data.data.forEach(item => {
      targetArray.push({
        value: item.dictKey,
        label: item.dictValue,
      });
    });
  });
}

const onLoad = async () => {
  try {
    // 获取初始化页面数据
    let _data = {
      freezeStatus: '0',
      hasPackage: 1,
      pageNum: details.page.currentPage,
      pageSize: details.page.pageSize,
      ...details.query,
    };
    details.loadingObj.list = true;
    let _res = await $_getopenOrderAdvancePageList(_data);
    const { code, data } = _res.data;
    if (code === 200) {
      details.data = data.records;
      details.page.total = data.total;
    }
    console.log(_res, '初始化数据');
  } catch (e) {
    console.log(e, 'error');
  } finally {
    details.loadingObj.list = false;
  }
};
const handleRules = () => {
  details.addTagFormRules = {};

  for (const key in details.addTagInfo) {
    if (Object.prototype.hasOwnProperty.call(details.addTagInfo, key)) {
      const element = details.addTagInfo[key];

      for (const iterator of element) {
        details.addTagFormRules[iterator.prop] = iterator.rule;

        details.addTagForm[iterator.prop] = iterator.value;
      }
    }
  }
  console.log('details.addTagFormRules :>> ', details.addTagFormRules);
};

// 获取省市区
const Obtainprovinces = () => {
  getLazyTreeAll().then(res => {
    if (res.data.success) {
      details.addTagInfo.cargoInfo.find(val => val.label === '所属区域').checkArr = res.data.data;
    }
  });
};
// 获取所有品牌
const Obtainbrand = () => {
  postFindBrandList({}).then(res => {
    const { code, data } = res.data;
    if (code !== 200) return;
    details.addTagInfo.cargoInfo.find(val => val.label === '品牌').checkArr = data;
  });
};
// 初始化页面
const onLoadPage = () => {
  onLoad();
  handleRules();
  Obtainprovinces();
  Obtainbrand();
};
onLoadPage();
/** 修改客户信息 */
const editClientInfo = () => {
  if (details.selectionList.length === 0) {
    return ElMessage({
      type: 'warning',
      message: '最少选择一条数据',
    });
  }

  const ids = JSON.stringify(details.selectionList.map(item => item.id));
  const info = JSON.stringify(details.selectionList[0]);

  // $router.push(`/waybill/EditCustomerInfo?ids=${ids}&info=${info}`);
  $router.push({
    path: `/waybill/EditCustomerInfo/${ids}/${info}`,
    query: {
      name: `订单 -- ${details.selectionList[0].orderCode} 客户信息修改`,
    },
  });
};
/** 查看包明细 */
const handleShowPackageOrderList = ({ row }) => {
  $router.push({
    path: '/waybill/orderPackageListDetailsByMarket?name=包明细',
    query: {
      id: row.id,
      name: `订单 -- ${row.orderCode} 包明细`,
    },
  });
};
/** 批量删除 */
const handleDelete = () => {
  if (details.selectionList.length === 0) {
    return ElMessage({
      type: 'warning',
      message: '最少选择一条数据',
    });
  }

  ElMessageBox.confirm('确认删除数据吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      details.loadingObj.list = true;

      const ids = details.selectionList.map(item => item.id);

      const res = await postOpenOrderDeletedAdvance({ advanceIds: ids, freezeStatus: '1' });
      const { code } = res.data;
      if (code !== 200) {
        return;
      }
      ElMessage({
        type: 'success',
        message: '操作成功',
      });
      details.page.currentPage = 1;
      await onLoad();
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.list = false;
    }
  });
};

/** 开启开标签弹窗 */
const handleOpenAddTagDlog = async () => {
  if (!ChecksWhetherTheWarehouseIsSelected())
    return ElMessage.warning('多仓权限无法操作，请选择仓库');

  details.popUpShow.addTagVisited = true;

  await nextTick();

  ruleFormRef.value.resetFields();
};
/** 开标签重置 */
const handleRefreshAddTag = formEl => {
  if (!formEl) return;
  ElMessageBox.confirm('确认重置吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    formEl.resetFields();
  });
};
/** 开标签提交 */
const handleSubmitAddTag = formEl => {
  if (!formEl) {
    return;
  }
  formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm('确认提交吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        console.log('submit!');

        console.log('details.addTagForm :>> ', details.addTagForm);
        try {
          if (details.addTagForm.area.length < 2) {
            return ElMessage.warning('区域最少选择到市');
          }

          details.loadingObj.addTagLoading = true;

          const res = await postOpenLabel({
            ...details.addTagForm,
            area: details.addTagForm.area.join(','),
          });
          const { code } = res.data;

          if (code !== 200) {
            return;
          }
          ElMessage.success('添加成功');
          details.popUpShow.addTagVisited = false;
          await onLoad();
        } catch (error) {
          console.log('error :>> ', error);
        } finally {
          details.loadingObj.addTagLoading = false;
        }
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};
/** 批量冻结 */
const handleFreeze = () => {
  if (details.selectionList.length === 0) {
    return ElMessage({
      type: 'warning',
      message: '最少选择一条数据',
    });
  }

  const ids = details.selectionList.map(item => item.id);
  ElMessageBox.confirm('确认冻结数据吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      details.loadingObj.list = true;

      const res = await postOpenOrderFreezeByAdvanceIds({ advanceIds: ids, freezeStatus: '1' });
      const { code } = res.data;
      if (code !== 200) {
        return;
      }
      ElMessage({
        type: 'success',
        message: '操作成功',
      });
      details.page.pageNum = 1;
      await onLoad();
    } catch (e) {
      console.log('error :>> ', e);
    } finally {
      details.loadingObj.list = false;
    }
  });
};
/** 上传文件 */
const handleBeforeUpload = file => {
  console.log('file :>> ', file);
  details.loadingObj.UploadLoadong = true;

  // 获取文件类型
  const _fileNameArr = file.name.split('.');
  const _fileType = _fileNameArr[_fileNameArr.length - 1];

  const whiteArr = ['xls', 'xlsx'];

  if (whiteArr.indexOf(_fileType) !== -1) return true;

  ElMessage.warning('请传入xls或xlsx格式的文件');
  details.loadingObj.UploadLoadong = false;
  return false;
};
/** 上传成功 */
const handleSuccess = res => {
  console.log('res :>> ', res);
  details.loadingObj.UploadLoadong = false;
  const { msg, code } = res;
  if (code !== 200) return ElMessage.warning(msg || '上传失败');
  ElMessage.success(msg || '上传成功');
  onLoad();
};
/** 上传失败 */
const handleClose = res => {
  details.loadingObj.UploadLoadong = false;

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

  console.log('JSON.parse() :>> ', JSON.parse(res));

  ElMessage.warning('上传失败');
};
/** 下载导入模板 */
const handleDownLoadFile = () => {
  const url =
    details.ouPaiChooseType === 1
      ? 'http://8.137.19.41:9000/logpm/bladex/upload/20240118/65c977fe6ac575ebb17803400a7abbc7.xlsx'
      : 'http://8.137.19.41:9000/logpm/bladex/upload/20240612/%E6%97%A0%E5%8C%85%E6%9D%A1%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88%28%E8%B4%A7%E6%97%A0%E5%BF%A7-%E7%94%9F%E6%88%90%E5%8C%85%E6%9D%A1%29.xlsx';
  const name =
    details.ouPaiChooseType === 1
      ? '包条导入模版（货无忧-生成包条）.xlsx'
      : details.orderStatus === 'notHaveData'
      ? '无包条导入模版（货无忧-不生成包条）.xlsx'
      : '无包条导入模版（货无忧-生成包条）.xlsx';

  downloadFileBase64(url, name);
};
</script>

<style scoped lang="scss">
.ElBtnClass button {
  border: none;
  padding: 0;
  background-color: transparent;
}
:deep(.el-card) {
  height: 100%;
}
:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.el-fy {
  flex: 1;
  display: flex;
  align-items: flex-end;
  margin-bottom: 10px;
}
.avue-crud {
  height: 100%;
  display: flex;
  flex-direction: column;
}
// 添加行
.addTagRow {
  display: flex;

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

// 标题
:deep(.el-divider__text.is-center) {
  font-size: 20px;
  font-weight: bold;
  color: var(--el-color-primary);
}
// 数字输入框
:deep(.el-input-number) {
  width: var(--el-input-width);
}

: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 {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  .el-btn {
    margin-right: 0;
    width: auto;
  }
}
</style>
