<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="公司名" prop="companyId">
        <el-select filterable v-model="queryParams.companyId" placeholder="请选择公司名" @change="companyChange" clearable size="small">
          <el-option
            v-for="item in companys"
            :key="item.companyId"
            :label="item.companyName"
            :value="item.companyId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <treeselect style="width: 220px" :clearable="false" v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
      </el-form-item>

      <el-form-item label="订单类型" prop="orderTypeFilter">
        <el-select v-model="queryParams.orderTypeFilter" placeholder="请选择订单类型" clearable size="small">
          <el-option label="全部" :value="null" />
          <el-option label="销售订单" :value="1" />
          <el-option label="商城订单" :value="2" />
          <el-option label="直播订单" :value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="销售名称" prop="salesName">
        <el-input
          v-model="queryParams.salesName"
          placeholder="请输入销售名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="订单号" prop="orderCodes">
        <div class="tag-input-container">
          <div class="tags-wrapper" @click="focusInput">
            <el-tag
              v-for="(code, index) in queryParams.orderCodes"
              :key="index"
              closable
              size="small"
              @close="removeOrderCode(index)"
              class="order-tag"
            >
              {{ code }}
            </el-tag>
            <el-input
              ref="tagInput"
              v-model="currentInput"
              v-show="inputVisible || queryParams.orderCodes.length === 0"
              :placeholder="queryParams.orderCodes.length === 0 ? '请输入订单号，按回车或逗号分隔' : '继续输入...'"
              size="small"
              class="tag-input"
              @keydown.native="handleKeyDown"
              @keyup.native="handleKeyUp"
              @blur="handleInputConfirm"
              @focus="inputVisible = true"
              clearable
            />
            <el-button
              v-if="!inputVisible && queryParams.orderCodes.length > 0"
              class="button-new-tag"
              size="small"
              @click="showInput"
              icon="el-icon-plus"
              type="text"
            >
              添加订单号
            </el-button>
          </div>
          <div class="input-tips">
            <span class="tip-text">
              支持：回车、逗号、空格分隔 |
              已添加 {{ queryParams.orderCodes.length }} 个订单号
            </span>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="运单号" prop="deliveryId">
        <el-input
          v-model="queryParams.deliveryId"
          placeholder="请输入运单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="银行交易流水号" prop="bankTransactionId">
        <el-input
          v-model="queryParams.bankTransactionId"
          placeholder="请输入银行交易流水号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="手机号" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="收件人" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入收件人姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="支付方式" prop="payType">
        <el-select v-model="queryParams.payType" placeholder="请选择支付方式" clearable size="small">
          <el-option
            v-for="item in payTypeOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>

<!--      <el-form-item label="上传凭证" prop="isUpload">-->
<!--        <el-select v-model="queryParams.isUpload" placeholder="请选择" clearable size="small">-->
<!--          <el-option key="0" label="未上传" value="0" />-->
<!--          <el-option key="1" label="已上传" value="1" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="物流状态" prop="deliveryStatus">-->
<!--        <el-select v-model="queryParams.deliveryStatus" placeholder="请选择物流状态" clearable size="small">-->
<!--          <el-option-->
<!--            v-for="item in deliveryStatusOptions"-->
<!--            :key="item.dictValue"-->
<!--            :label="item.dictLabel"-->
<!--            :value="item.dictValue"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="结算状态" prop="deliveryPayStatus">-->
<!--        <el-select v-model="queryParams.deliveryPayStatus" placeholder="请选择物流结算状态" clearable size="small">-->
<!--          <el-option-->
<!--            v-for="item in deliveryPayStatusOptions"-->
<!--            :key="item.dictValue"-->
<!--            :label="item.dictLabel"-->
<!--            :value="item.dictValue"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="小程序" prop="appId">-->
<!--        <el-select v-model="queryParams.appId" placeholder="请选择所属小程序" clearable size="small">-->
<!--          <el-option-->
<!--            v-for="dict in appMallOptions"-->
<!--            :key="dict.appid"-->
<!--            :label="dict.name + '(' + dict.appid + ')'"-->
<!--            :value="dict.appid"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="商品规格" prop="productSpec">-->
<!--        <el-input-->
<!--          v-model="queryParams.productSpec"-->
<!--          placeholder="请输入商品规格"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

<!--      <el-form-item label="商品数量" prop="totalNum">-->
<!--        <el-input-->
<!--          v-model="queryParams.totalNum"-->
<!--          placeholder="请输入商品数量"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

<!--      <el-form-item label="销售价格" prop="price">-->
<!--        <el-input-->
<!--          v-model="queryParams.price"-->
<!--          placeholder="请输入销售价格"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item label="收货地址" prop="userAddress">
        <el-input
          v-model="queryParams.userAddress"
          placeholder="请输入收货地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="商品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入商品ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="汇付商户订单号" prop="hfshh">
        <el-input
          v-model="queryParams.hfshh"
          placeholder="请输入汇付商户订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

<!--      <el-form-item label="成本价格" prop="cost">-->
<!--        <el-input-->
<!--          v-model="queryParams.cost"-->
<!--          placeholder="请输入成本价格"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

<!--      <el-form-item label="供应商" prop="supplierName">-->
<!--        <el-input-->
<!--          v-model="queryParams.supplierName"-->
<!--          placeholder="请输入供应商名称"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

<!--      <el-form-item label="档期归属" prop="scheduleId">-->
<!--        <el-select filterable style="width: 215px" v-model="queryParams.scheduleId" placeholder="请选择档期" clearable size="small">-->
<!--          <el-option-->
<!--            v-for="item in scheduleOptions"-->
<!--            :key="item.id"-->
<!--            :label="item.name"-->
<!--            :value="item.id"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

      <el-form-item label="代服账户" prop="erpAccount" v-if="SFDFopen">
        <el-select v-model="queryParams.erpAccount" style="width: 215px" placeholder="ERP账户" clearable size="small">
          <el-option
            v-for="dict in erpAccountQueryList"
            :key="dict"
            :label="dict"
            :value="dict"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="代服电话" prop="erpPhoneNumber" v-if="SFDFopen">
        <el-input
          v-model="queryParams.erpPhoneNumber"
          placeholder="ERP电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="下单时间" prop="createTimeRange">
        <el-date-picker
          style="width:215px"
          clearable
          size="small"
          v-model="createTimeRange"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          @change="handleOrderTimeChange"
        />
      </el-form-item>

      <el-form-item label="支付时间" prop="payTimeRange">
        <el-date-picker
          style="width: 215px"
          clearable
          size="small"
          v-model="payTimeRange"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          @change="handlePayTimeChange"
        />
      </el-form-item>

<!--      <el-form-item label="发货时间" prop="deliverySendTimeRange">-->
<!--        <el-date-picker-->
<!--          style="width:215px"-->
<!--          clearable-->
<!--          size="small"-->
<!--          v-model="deliverySendTimeRange"-->
<!--          type="daterange"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--        />-->
<!--      </el-form-item>-->

<!--      <el-form-item label="回单时间" prop="deliveryImportTimeRange">-->
<!--        <el-date-picker-->
<!--          style="width:215px"-->
<!--          clearable-->
<!--          size="small"-->
<!--          v-model="deliveryImportTimeRange"-->
<!--          type="daterange"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          plain-->
<!--          type="info"-->
<!--          icon="el-icon-upload2"-->
<!--          size="mini"-->
<!--          @click="handleImport"-->
<!--        >导入银行回单</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          v-hasPermi="['live:order:export']"
          :loading="exportLoading"
          @click="handleExport"
        >导出订单</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExportItems"-->
<!--        >导出订单明细</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          icon="el-icon-s-order"-->
<!--          size="mini"-->
<!--          @click="openDeliveryNote"-->
<!--        >批量导入物流单号</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          v-hasPermi="['live:order:exportAll']"
          @click="handleExportDetails"
        >导出订单(明文)</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExportItemsDetails"-->
<!--        >导出订单明细(明文)</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          icon="el-icon-tickets"
          size="mini"
          type="success"
          :loading="exportShippingLoading"
          @click="handleExportShippingOrder"
        >导出发货单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-tabs type="card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="全部订单" name="00"></el-tab-pane>
      <el-tab-pane label="待支付" name="0"></el-tab-pane>
      <el-tab-pane label="待发货" name="1"></el-tab-pane>
      <el-tab-pane label="待收货" name="2"></el-tab-pane>
      <el-tab-pane label="交易完成" name="3"></el-tab-pane>
      <el-tab-pane label="退款中" name="-1"></el-tab-pane>
      <el-tab-pane label="已退款" name="-2"></el-tab-pane>
      <el-tab-pane label="已取消" name="-3"></el-tab-pane>
    </el-tabs>

    <el-table
      ref="orderTable"
      border
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
      :default-sort="{prop: 'createTime', order: 'descending'}"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单类型" align="center" prop="orderTypeName" width="100px">
        <template slot-scope="scope">
          <el-tag :type="getOrderTypeTagType(scope.row.orderType)">
            {{ scope.row.orderTypeName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单号" align="center" prop="orderCode" width="200px" />
      <el-table-column label="银行交易流水号" align="center" prop="bankTransactionId" width="200px" />
      <el-table-column label="所属公司" align="center" prop="companyName" />
      <el-table-column label="销售名称" align="center" prop="salesName" width="120px" />
      <el-table-column label="员工昵称" align="center" prop="companyUserNickName" width="120px" />
      <el-table-column label="用户昵称" align="center" prop="nickname" width="150px" />
      <el-table-column label="收件人" align="center" prop="realName" width="120px" />
      <el-table-column label="手机号" align="center" prop="userPhone" width="120px" />
      <el-table-column label="商品规格" align="center" prop="productSpec" width="120px" />
      <el-table-column label="商品数量" align="center" prop="totalNum" width="100px" />
      <el-table-column label="汇付商户订单号" align="center" prop="hfshh" width="100px" />
      <el-table-column label="订单金额" align="center" prop="totalPrice" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.totalPrice != null">{{ scope.row.totalPrice.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应付金额" align="center" prop="payPrice" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.payPrice != null">{{ scope.row.payPrice.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实付金额" align="center" prop="payMoney" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.payMoney != null">{{ scope.row.payMoney.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="createTime" width="180" />
      <el-table-column label="支付时间" align="center" prop="payTime" width="180" />
      <el-table-column label="支付方式" align="center" prop="payType" width="100px">
        <template slot-scope="scope">
          <el-tag v-for="(item, index) in payTypeOptions" :key="index" v-if="scope.row.payType == item.dictValue" size="mini">
            {{ item.dictLabel }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100px">
        <template slot-scope="scope">
          <el-tag v-for="(item, index) in statusOptions" :key="index" v-if="scope.row.status == item.dictValue" size="mini">
            {{ item.dictLabel }}
          </el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="物流状态" align="center" prop="deliveryStatus" width="100px">-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag v-for="(item, index) in deliveryStatusOptions" :key="index" v-if="scope.row.deliveryStatus == item.dictValue" size="mini">-->
<!--            {{ item.dictLabel }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="运单号" align="center" prop="deliveryId" width="150px" />
      <el-table-column label="商品ID" align="center" prop="productId" width="120px" />
      <el-table-column label="商品名称" align="center" prop="productName" width="150px" />
      <el-table-column label="条码" align="center" prop="barCode" width="120px" />
      <el-table-column label="分类" align="center" prop="cateName" width="120px" />
      <el-table-column label="运费" align="center" prop="payDelivery" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.payDelivery != null">{{ scope.row.payDelivery }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成本价" align="center" prop="cost" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.cost != null">{{ scope.row.cost }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="80px" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 订单详情侧边栏 -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawerVisible"
      direction="rtl"
      size="75%"
      :before-close="closeDrawer"
    >
      <div v-loading="drawerLoading" style="min-height: 200px;">
        <!-- 直播订单详情 -->
        <liveDetail
          v-if="currentOrderType === 3 && drawerVisible"
          ref="liveDetailRef"
          :order-id="currentOrderId"
        />
        <!-- 销售订单详情 -->
        <userDetail
          v-if="currentOrderType === 1 && drawerVisible"
          ref="userDetailRef"
          :order-id="currentOrderId"
        />
        <!-- 商城订单详情 -->
        <storeDetail
          v-if="currentOrderType === 2 && drawerVisible"
          ref="storeDetailRef"
          :order-id="currentOrderId"
        />
      </div>
    </el-drawer>

    <!-- 批量导入物流单号对话框 -->
    <el-dialog
      :before-close="cancelResetDeliveryNote"
      :visible.sync="deliveryNoteOpen"
      center
      title="批量发货"
      width="35%"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="小程序:" prop="miniAppId">
          <el-select
            v-model="ruleForm.miniAppId"
            clearable
            placeholder="请选择发货小程序"
            style="width: 100%"
          >
            <el-option
              v-for="item in miniAppList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-upload ref="upload" :action="uploadUrl" :auto-upload="false" :disabled="orderUpload.isUploading" :headers="orderUpload.headers"
                 :limit="1" :on-progress="handleFileUploadProgress"
                 :on-success="handleFileSuccess" accept=".xlsx, .xls" drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          <el-link style="font-size:12px" type="info" @click="importDeliveryNoteTemplate">下载模板</el-link>
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入"xls"或"xlsx"格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelResetDeliveryNote">取 消</el-button>
        <el-button type="primary" @click="submitDeliveryNote('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 导入银行回单对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" append-to-body width="400px">
      <el-upload ref="upload" :action="upload.url + '?updateSupport=' + upload.updateSupport" :auto-upload="false" :disabled="upload.isUploading"
                 :headers="upload.headers" :limit="1"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" accept=".xlsx, .xls" drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入"xls"或"xlsx"格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMergedOrder, exportMergedOrder, exportMergedShipping, exportMergedOrderItems, exportMergedOrderDetails, exportMergedOrderItemsDetails, importDeliveryNoteExpressTemplate } from '@/api/live/mergedOrder'
import { getCompanyList } from '@/api/company/company'
import { treeselect } from '@/api/company/companyDept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import liveDetail from './liveDetail.vue'
import userDetail from './userDetail.vue'
import storeDetail from './storeDetail.vue'
import { getToken } from '@/utils/auth'
import { getTcmScheduleList } from '@/api/company/schedule'
import { list as getAppMallOptions } from '@/api/course/coursePlaySourceConfig'
import { getErpAccount } from '@/api/hisStore/storeOrder'
import { getConfigByKey } from '@/api/system/config'

export default {
  name: 'MergedOrder',
  components: {Treeselect, liveDetail, userDetail, storeDetail },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      exportLoading: false,
      exportShippingLoading: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 公司列表
      companys: [],
      companyId: null,
      // 部门树选项
      deptOptions: [],
      // 字典
      payTypeOptions: [],
      deliveryStatusOptions: [],
      deliveryPayStatusOptions: [],
      statusOptions: [],
      orderTypeOptions: [],
      appMallOptions: [],
      scheduleOptions: [],
      erpAccountQueryList: [],
      SFDFopen: false,
      // 订单号标签输入相关
      maxOrderCodes: 50,
      inputVisible: false,
      currentInput: '',
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      createTimeRange: [],
      payTimeRange: [],
      deliverySendTimeRange: [],
      deliveryImportTimeRange: [],
      activeName: '00',
      // 侧边栏相关
      drawerVisible: false,
      drawerTitle: '订单详情',
      currentOrderType: null,
      currentOrderId: null,
      drawerLoading: false,
      // 上传相关
      upload: {
        open: false,
        title: '',
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: 'Bearer ' + getToken() },
        url: process.env.VUE_APP_BASE_API + '/order/importExpress'
      },
      orderUpload: {
        open: false,
        title: '',
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: 'Bearer ' + getToken() }
      },
      deliveryNoteOpen: false,
      miniAppList: [],
      ruleForm: {
        miniAppId: null
      },
      rules: {
        miniAppId: [
          { required: true, message: '发货小程序不能为空' }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        deptId: null,
        hfshh: null,
        orderTypeFilter: 1,
        salesName: null,
        orderCodes: [],
        orderCode: null,
        orderCodeList: null,
        deliveryId: null,
        userPhone: null,
        realName: null,
        productName: null,
        bankTransactionId: null,
        productSpec: null,
        productId: null,
        totalNum: null,
        price: null,
        userAddress: null,
        cost: null,
        supplierName: null,
        companyUserNickName: null,
        orderType: null,
        isUpload: null,
        payType: null,
        deliveryStatus: null,
        deliveryPayStatus: null,
        appId: null,
        scheduleId: null,
        erpAccount: null,
        erpPhoneNumber: null,
        status: null,
        createTimeStart: null,
        createTimeEnd: null,
        createTimeRange: null,
        payTimeRange: null,
        deliverySendTimeRange: null,
        deliveryImportTimeRange: null
      }
    }
  },
  created() {
    // 初始化公司列表
    getCompanyList().then(response => {
      this.companys = response.data || []
      if (this.companys != null && this.companys.length > 0) {
        this.companyId = this.companys[0].companyId
        this.getTreeselect()
      }
    }).catch(error => {
      console.error('获取公司列表失败:', error)
      this.companys = []
    })

    // 初始化支付方式字典
    this.getDicts('store_pay_type').then((response) => {
      this.payTypeOptions = response.data || []
    }).catch(error => {
      console.error('获取支付方式字典失败:', error)
      this.payTypeOptions = []
    })

    // 初始化订单状态字典
    this.getDicts('store_order_status').then((response) => {
      this.statusOptions = response.data || []
    }).catch(error => {
      console.error('获取订单状态字典失败:', error)
      this.statusOptions = []
    })

    // 初始化物流状态字典
    this.getDicts('store_order_delivery_status').then((response) => {
      this.deliveryStatusOptions = response.data || []
    }).catch(error => {
      console.error('获取物流状态字典失败:', error)
      this.deliveryStatusOptions = []
    })

    // 初始化物流结算状态字典
    this.getDicts('store_delivery_pay_status').then((response) => {
      this.deliveryPayStatusOptions = response.data || []
    }).catch(error => {
      console.error('获取物流结算状态字典失败:', error)
      this.deliveryPayStatusOptions = []
    })

    // // 初始化订单类型字典
    // this.getDicts('store_order_type').then((response) => {
    //   this.orderTypeOptions = response.data || []
    // }).catch(error => {
    //   console.error('获取订单类型字典失败:', error)
    //   this.orderTypeOptions = []
    // })

    // 初始化档期归属列表
    getTcmScheduleList().then(response => {
      this.scheduleOptions = response.data || []
    }).catch(error => {
      console.error('获取档期归属列表失败:', error)
      this.scheduleOptions = []
    })

    // 初始化小程序列表
    this.getAppMallOptions()

    // 初始化ERP账户列表
    this.getErpAccountList()

    // 加载订单列表
    this.getList()
  },
  computed: {
    uploadUrl() {
      return process.env.VUE_APP_BASE_API +
        '/order/importDeliveryNoteExpress?miniAppId=' +
        this.ruleForm.miniAppId
    }
  },
  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true
      if (this.queryParams.status == '00') {
        this.queryParams.status = null
      }

      // 处理订单号数组
      if (this.queryParams.orderCodes && this.queryParams.orderCodes.length > 0) {
        this.queryParams.orderCodeList = this.queryParams.orderCodes.join(',')
      } else {
        this.queryParams.orderCodeList = null
      }

      // 处理时间范围
      if (this.createTimeRange != null && this.createTimeRange.length === 2) {
        this.queryParams.createTimeRange = this.createTimeRange[0] + '--' + this.createTimeRange[1]
      } else {
        this.queryParams.createTimeRange = null
      }

      if (this.payTimeRange != null && this.payTimeRange.length === 2) {
        this.queryParams.payTimeRange = this.payTimeRange[0] + '--' + this.payTimeRange[1]
      } else {
        this.queryParams.payTimeRange = null
      }

      if (this.deliverySendTimeRange != null && this.deliverySendTimeRange.length === 2) {
        this.queryParams.deliverySendTimeRange = this.deliverySendTimeRange[0] + '--' + this.deliverySendTimeRange[1]
      } else {
        this.queryParams.deliverySendTimeRange = null
      }

      if (this.deliveryImportTimeRange != null && this.deliveryImportTimeRange.length === 2) {
        this.queryParams.deliveryImportTimeRange = this.deliveryImportTimeRange[0] + '--' + this.deliveryImportTimeRange[1]
      } else {
        this.queryParams.deliveryImportTimeRange = null
      }

      listMergedOrder(this.queryParams).then(response => {
        this.orderList = response.rows
        this.total = response.total
        this.loading = false
        if (response.msg == 'knt') {
          this.SFDFopen = true
        } else {
          this.SFDFopen = false
        }
      }).catch(error => {
        console.error('查询失败:', error)
        this.loading = false
        this.$message.error('查询数据失败')
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.createTimeRange = []
      this.payTimeRange = []
      this.deliverySendTimeRange = []
      this.deliveryImportTimeRange = []
      this.queryParams.orderCodes = []
      this.currentInput = ''
      this.inputVisible = false
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id || item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleClick(tab, event) {
      this.activeName = tab.name
      this.queryParams.status = tab.name
      this.getList()
    },
    handleOrderTimeChange(value) {

    },
    handlePayTimeChange(value) {

    },
    /** 导出订单 */
    handleExport() {
      this.prepareExportParams()
      this.$confirm('是否确认导出所有订单数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        return exportMergedOrder(this.queryParams)
      }).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => {
        this.exportLoading = false
      })
    },
    /** 导出发货单 */
    handleExportShippingOrder() {
      this.prepareExportParams()
      this.$confirm('是否确认导出所有订单明细数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportShippingLoading = true
        return exportMergedShipping(this.queryParams)
      }).then(response => {
        this.download(response.msg)
        this.exportShippingLoading = false
      }).catch(() => {
        this.exportShippingLoading = false
      })
    },
    handleDetails(row) {
      // 根据订单类型打开对应的侧边栏详情
      this.currentOrderType = row.orderType

      if (row.orderType === 1) {
        // 销售订单
        this.currentOrderId = row.id
        this.drawerTitle = '销售订单详情'
      } else if (row.orderType === 2) {
        // 商城订单
        this.currentOrderId = row.id
        this.drawerTitle = '商城订单详情'
      } else if (row.orderType === 3) {
        // 直播订单
        this.currentOrderId = row.orderId
        this.drawerTitle = '直播订单详情'
      }

      this.drawerVisible = true
    },
    closeDrawer() {
      this.drawerVisible = false
      this.currentOrderType = null
      this.currentOrderId = null
    },
    getOrderTypeTagType(orderType) {
      const typeMap = {
        1: 'success', // 销售订单
        2: 'warning', // 商城订单
        3: 'info' // 直播订单
      }
      return typeMap[orderType] || ''
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      var param = { companyId: this.companyId }
      treeselect(param).then((response) => {
        this.deptOptions = response.data
      })
    },
    companyChange(val) {
      this.companyId = val
      this.getTreeselect()
    },
    // 订单号标签输入相关方法
    handleKeyDown(event) {
      const { key, target } = event
      if (key === 'Backspace' && !target.value && this.queryParams.orderCodes.length > 0) {
        event.preventDefault()
        this.removeOrderCode(this.queryParams.orderCodes.length - 1)
      }
      if ([',', '，', ' ', 'Enter'].includes(key)) {
        event.preventDefault()
        this.handleInputConfirm()
      }
    },
    handleKeyUp(event) {
      const value = event.target.value
      if (/[,，\s]/.test(value)) {
        this.handleInputConfirm()
      }
    },
    handleInputConfirm() {
      const inputValue = this.currentInput.trim()
      if (inputValue) {
        const codes = inputValue.split(/[,，\s]+/).filter(code => code.trim())
        codes.forEach(code => {
          this.addOrderCode(code.trim())
        })
      }
      this.currentInput = ''
    },
    addOrderCode(code) {
      if (!code) return
      if (this.maxOrderCodes > 0 && this.queryParams.orderCodes.length >= this.maxOrderCodes) {
        this.$message.warning(`最多只能添加 ${this.maxOrderCodes} 个订单号`)
        return
      }
      if (this.queryParams.orderCodes.includes(code)) {
        this.$message.warning(`订单号 "${code}" 已存在`)
        return
      }
      this.queryParams.orderCodes.push(code)
    },
    removeOrderCode(index) {
      this.queryParams.orderCodes.splice(index, 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(() => {
        if (this.$refs.tagInput) {
          this.$refs.tagInput.focus()
        }
      })
    },
    focusInput() {
      if (!this.inputVisible) {
        this.showInput()
      }
    },
    // 导出相关方法
    handleExportItems() {
      this.prepareExportParams()
      this.$confirm('是否确认导出所有订单明细数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportMergedOrderItems(this.queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(() => {})
    },
    handleExportDetails() {
      this.prepareExportParams()
      this.$confirm('是否确认导出所有订单数据项(明文)?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportMergedOrderDetails(this.queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(() => {})
    },
    handleExportItemsDetails() {
      this.prepareExportParams()
      this.$confirm('是否确认导出所有订单明细数据项(明文)?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportMergedOrderItemsDetails(this.queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(() => {})
    },
    prepareExportParams() {
      if (this.queryParams.status == '00') {
        this.queryParams.status = null
      }
      if (this.createTimeRange != null && this.createTimeRange.length === 2) {
        this.queryParams.createTimeRange = this.createTimeRange[0] + '--' + this.createTimeRange[1]
      } else {
        this.queryParams.createTimeRange = null
      }
      if (this.payTimeRange != null && this.payTimeRange.length === 2) {
        this.queryParams.payTimeRange = this.payTimeRange[0] + '--' + this.payTimeRange[1]
      } else {
        this.queryParams.payTimeRange = null
      }
      if (this.deliverySendTimeRange != null && this.deliverySendTimeRange.length === 2) {
        this.queryParams.deliverySendTimeRange = this.deliverySendTimeRange[0] + '--' + this.deliverySendTimeRange[1]
      } else {
        this.queryParams.deliverySendTimeRange = null
      }
      if (this.deliveryImportTimeRange != null && this.deliveryImportTimeRange.length === 2) {
        this.queryParams.deliveryImportTimeRange = this.deliveryImportTimeRange[0] + '--' + this.deliveryImportTimeRange[1]
      } else {
        this.queryParams.deliveryImportTimeRange = null
      }
      if (this.queryParams.orderCodes && this.queryParams.orderCodes.length > 0) {
        this.queryParams.orderCodeList = this.queryParams.orderCodes.join(',')
      } else {
        this.queryParams.orderCodeList = null
      }
    },
    // 导入相关方法
    handleImport() {
      this.upload.title = '导入银行回单'
      this.upload.open = true
    },
    submitFileForm() {
      this.$refs.upload.submit()
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
      this.$message.success('导入成功')
      this.getList()
    },
    // 批量导入物流单号
    openDeliveryNote() {
      this.deliveryNoteOpen = true
      this.getAppList()
    },
    getAppList() {
      this.miniAppList = []
      const key = 'courseMa.config'
      getConfigByKey(key).then(response => {
        const { code, data } = response
        if (code === 200) {
          let value = data?.configValue
          if (value) {
            try {
              const appList = JSON.parse(value)
              this.miniAppList = appList.filter(v => v.type === '1').map(v => {
                return { appId: v.appid, appName: v.name }
              })
            } catch (parseError) {
              console.error('解析小程序配置失败:', parseError)
              this.miniAppList = []
            }
          }
        }
      }).catch(error => {
        console.error('获取小程序配置失败:', error)
        this.miniAppList = []
      })
    },
    importDeliveryNoteTemplate() {
      importDeliveryNoteExpressTemplate().then((response) => {
        this.download(response.msg)
      })
    },
    submitDeliveryNote(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const uploadFiles = this.$refs.upload.uploadFiles
          if (uploadFiles.length === 0) {
            this.$message.error('请选择要上传的文件')
            return
          }
          this.$refs.upload.submit()
        } else {
          return false
        }
      })
    },
    cancelResetDeliveryNote() {
      this.deliveryNoteOpen = false
      this.resetForm('ruleForm')
    },
    // 获取小程序选项列表
    getAppMallOptions() {
      getAppMallOptions({ pageNum: 1, pageSize: 100, isMall: 1 }).then(response => {
        this.appMallOptions = response.rows || []
      }).catch(error => {
        console.error('获取小程序选项列表失败:', error)
        this.appMallOptions = []
      })
    },
    // 获取ERP账户列表
    async getErpAccountList() {
      try {
        const response = await getErpAccount()
        if (response.code === 200) {
          const list = response.data || []
          this.erpAccountQueryList = [...list, '未分拣']
        } else {
          this.erpAccountQueryList = []
        }
      } catch (error) {
        console.error('获取ERP账户列表失败:', error)
        this.erpAccountQueryList = []
      }
    }
  }
}
</script>

<style scoped>
.tag-input-container {
  min-width: 445px;
}

.tags-wrapper {
  min-height: 32px;
  padding: 4px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: text;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
  transition: border-color 0.2s;
}

.tags-wrapper:hover {
  border-color: #c0c4cc;
}

.tags-wrapper:focus-within {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.order-tag {
  margin: 2px;
  flex-shrink: 0;
}

.tag-input {
  border: none;
  outline: none;
  flex: 1;
  min-width: 120px;
}

.tag-input >>> .el-input__inner {
  border: none;
  padding: 0;
  height: 24px;
  line-height: 24px;
}

.button-new-tag {
  height: 24px;
  line-height: 22px;
  padding: 0 8px;
  margin: 2px;
}

.input-tips {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.tip-text {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>

