<template>
  <div class="app-container order-index">
    <el-tabs v-model="activeName" @tab-click="getList(activeName)">
      <el-tab-pane label="全部" name="0">
      </el-tab-pane>
      <el-tab-pane name="1">
        <span slot="label">待发货{{tabNum[0]}}
        <el-tooltip class="item" effect="dark" content="包含“待审单、待配货、待发货”订单类型的所有订单" placement="bottom">
          <i class="el-icon-info"></i>
        </el-tooltip></span>
      </el-tab-pane>
      <el-tab-pane name="2">
        <span slot="label">即将逾期发货{{tabNum[1]}}<el-tooltip class="item" effect="dark" content="包含“待审单、待配货、待发货”订单类型、且湘商整体发货时效到期小于4小时所有订单" placement="bottom">
          <i class="el-icon-info"></i>
        </el-tooltip></span>
      </el-tab-pane>
      <el-tab-pane name="3">
        <span slot="label">已逾期发货{{tabNum[2]}}<el-tooltip class="item" effect="dark" content="包含“待审单、待配货、待发货”订单类型、且湘商整体发货时效已逾期" placement="bottom">
          <i class="el-icon-info"></i>
        </el-tooltip></span>
      </el-tab-pane>
      <el-tab-pane name="4">
        <span slot="label">已发货未收货{{tabNum[3]}}<el-tooltip class="item" effect="dark" content="包含已发货、未签收完成的所有订单" placement="bottom">
          <i class="el-icon-info"></i>
        </el-tooltip></span>
      </el-tab-pane>
    </el-tabs>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="mini"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
      class="mini-form"
    >
      <el-form-item label="时间类型:" prop="dateType" >
        <el-select v-model="queryParams.dateType" style="width: 120px;" placeholder="请选择">
          <el-option
            v-for="dict in dateTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-date-picker
          v-model="queryParams.dateRange"
          style="width: 220px"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="电商平台:" prop="platformNo">
        <el-select
          multiple
          filterable
          v-model="queryParams.platformNo"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in platformLists"
            :key="dict.platformNo"
            :label="dict.platformName"
            :value="dict.platformNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="店铺:" prop="shopCode">
        <el-select
          multiple
          filterable
          v-model="queryParams.shopCode"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
        <el-option
            v-for="dict in channelList"
            :key="dict.channelCode"
            :label="dict.channelName"
            :value="dict.channelCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售部门:" prop="departmentCode">
        <el-select
        multiple
        filterable
          v-model="queryParams.departmentCode"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
        <el-option
            v-for="dict in brandNameList"
            :key="dict.deptCode"
            :label="dict.deptName"
            :value="dict.deptCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="订单状态:" prop="orderStatus" v-show="activeName==0">
        <el-select
          multiple
          filterable
          v-model="queryParams.orderStatus"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in orderStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单编码:" prop="platformCode">
        <el-input
          v-model.trim="queryParams.platformCode"
          placeholder="请输入平台单号/管易单号，多个逗号分隔"
          style="width: 155px;"
          clearable
          @input="value=>copySkus(value,'platformCode')"
        />
      </el-form-item>
      <el-form-item label="商品编码:" prop="goodCode">
        <el-input
          v-model="queryParams.goodCode"
          placeholder="多个商品编码使用逗号隔开"
          style="width: 155px;"
          clearable
          @input="value=>copySkus(value,'goodCode')"
        />
      </el-form-item>
      <el-form-item label="商品名称:" prop="goodName">
        <LoadMoreSelect
          :skuNo="queryParams.goodName"
          style="width: 155px;"
          @queryParams="(val) => (queryParams.goodName = val)"
        />
      </el-form-item>
      <el-form-item label="品牌:" prop="brandCode">
        <el-select
          v-model="queryParams.brandCode"
          filterable
          placeholder="品牌"
          clearable
          multiple
          style="width: 155px;"
        >
          <el-option
            v-for="(dict, index) in brandNameList2"
            :key="index"
            :label="dict.brandName"
            :value="dict.brandCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发货状态:" prop="deliveryStatus" v-show="showForm">
        <el-select
          multiple
          filterable
          v-model="queryParams.deliveryStatus"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in deliveryStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="串码:" prop="uniqueCode" v-show="showForm">
        <el-input
          v-model="queryParams.uniqueCode"
          placeholder="请输入完整串码，多个逗号分开"
          clearable
          style="width: 155px;"
          @input="value=>copySkus(value,'uniqueCode')"
        />
      </el-form-item>

      <!-- <el-form-item label="售后类型:" prop="afterSaleType" v-show="showForm">
        <el-select
          multiple
          filterable
          v-model="queryParams.afterSaleType"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in afterSaleTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="售后状态:" prop="afterSaleStatus" v-show="showForm">
        <el-select
        multiple
        filterable
          v-model="queryParams.afterSaleStatus"
          placeholder="请选择"

          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in afterSaleStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="付款状态:" prop="payStatus" v-show="showForm">
        <el-select
        multiple
        filterable
          v-model="queryParams.payStatus"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in payStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开票状态:" prop="invoiceStatus" v-show="showForm">
        <el-select
        multiple
        filterable
          v-model="queryParams.invoiceStatus"
          placeholder="请选择"

          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in invoiceStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发货方式:" prop="deliveryType" v-show="showForm">
        <el-select
        multiple
        filterable
          v-model="queryParams.deliveryType"
          placeholder="请选择"

          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in deliveryTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发货仓库:" prop="warehouseName" v-show="showForm">
        <el-select
        multiple
        filterable
          v-model="queryParams.warehouseName"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="(dict, index) in warehouseLists"
            :key="index"
            :label="dict.warehouseName"
            :value="dict.warehouseCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物流单号:" prop="expressNo" v-show="showForm">
        <el-input
          v-model="queryParams.expressNo"
          placeholder="请输入完整快递单号，多个逗号分开"
          clearable
          style="width: 155px;"
          @input="value=>copySkus(value,'expressNo')"
        />
      </el-form-item>
      <el-form-item label="购买用户:" prop="vipName" v-show="showForm">
        <el-select
          multiple
          filterable
          v-model="queryParams.vipName"
          allow-create
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="(dict, index) in brandNameList"
            :key="index"
            :label="dict.deptName"
            :value="dict.deptName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收货人姓名:" label-width="90px" prop="userName" v-show="showForm">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入完整姓名"
          clearable
          style="width: 155px;"
        />
      </el-form-item>
      <el-form-item label="收货人手机号:" label-width="110px" prop="userMobile" v-show="showForm">
        <el-input
          v-model="queryParams.userMobile"
          placeholder="请输入完整手机号"
          clearable
          style="width: 155px;"
        />
      </el-form-item>
      <el-form-item label="业务类型:" prop="businessType" v-show="showForm">
        <el-select
        multiple
        filterable
          v-model="queryParams.businessType"
          placeholder="请选择"

          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in businessTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务员:" prop="businessMan" v-show="showForm">
        <el-select
          multiple
          filterable
          v-model="queryParams.businessMan"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="(dict, index) in businessManList"
            :key="dict.name"
            :label="dict.name"
            :value="dict.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单异常标记:" label-width="110px" prop="abnormalTag" v-show="showForm">
        <el-select
          multiple
          filterable
          v-model="queryParams.abnormalTag"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in tags2"
            :key="dict.code"
            :label="dict.name"
            :value="dict.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单操作超时标记:" label-width="130px" prop="timeoutTag" v-show="showForm">
        <el-select
        multiple
        filterable
          v-model="queryParams.timeoutTag"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in tags1"
            :key="dict.code"
            :label="dict.name"
            :value="dict.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务标记:" prop="bussinessFlag" v-show="showForm">
        <el-select
          multiple
          filterable
          v-model="queryParams.businessFlag"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in bussinessFlagList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="下单时间:" prop="dateRange" v-show="showForm">
        <el-select
          v-model="queryParams.dateRange"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in sys_commerce_platform"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="收货信息是否解密:" label-width="130px" prop="configMonth" v-show="showForm">
        <el-select
          v-model="queryParams.platform"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in sys_commerce_platform"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->

      <el-form-item label="代发推送状态:" label-width="100px" prop="pushOrderStatus" v-show="showForm">
        <el-select
          v-model="queryParams.pushOrderStatus"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            label="已推送聚链代发"
            value="1"
          />
          <el-option
            label="撤销聚链代发"
            value="2"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
      <el-button type="text" :icon="!showForm?'el-icon-arrow-down':'el-icon-arrow-up'" size="mini" @click="zkForm"
        >{{ showForm?'收起':'展开' }}</el-button
      >
      <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 type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >新增订单</el-button
        >

        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImportOrder"
          >导入</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >批量修改收货地址</el-button
        >
        <el-dropdown size="mini" @command="handleCommand2">
          <span class="el-dropdown-link">
            业务打标<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="a">标记聚链代发</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown size="mini" @command="handleCommand">
          <span class="el-dropdown-link">
            聚链代发<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown" >
            <el-dropdown-item command="c">选择缺货商品代发</el-dropdown-item>
            <el-dropdown-item command="a">推送聚链代发</el-dropdown-item>
            <el-dropdown-item command="b">撤销聚链代发</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" :columns="columns" @sort="sortCol" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="proTable"
      :height="tableHeight"
      border
      v-loading="loading"
      :data="postList"
      :key="randomKey"
      @selection-change="handleSelectionChange"
      :cell-style="cellStyle"
      row-key="platformCode"
    >
    <el-table-column type="selection" width="55" align="left" :reserve-selection="true" />
      <el-table-column v-for="(item,index) in columns" :key="index" :label="item.label"
      :min-width="item.width||'90'" :align="item.align||'left'" :fixed="item.fixed||false" :prop="item.prop">
        <template slot-scope="scope" >
          <template v-if="item.label=='订单/商品'">
            <div v-show="scope.row.erpCode">管易:{{ scope.row.erpCode }} <i class="el-icon-document-copy" @click="copyText(scope.row.erpCode)"></i></div>
            <div>平台:{{ scope.row.platformCode }}<i class="el-icon-document-copy" @click="copyText(scope.row.platformCode)"></i></div>
            <div class="good-box" v-for="(item, index) in scope.row.orderListDetailDTOList" :key="index">
              <el-tooltip class="item" content="Top center" placement="top">
                <div slot="content" style="width: auto">
                  商品名称：{{ item.goodName }} <i class="el-icon-document-copy" @click="copyText(item.goodName)"></i> <br />
                  商品编码：{{ item.goodCode }} <i class="el-icon-document-copy" @click="copyText(item.goodCode)"></i>
                </div>
                <div class="table-overflow">{{ item.goodName }}</div>
              </el-tooltip> &nbsp; {{ item.num }}<span>件</span>
            </div>
          </template>
          <template v-else-if="item.label=='渠道/店铺'">
            {{scope.row.platformName}}/{{ scope.row.shopName }}
          </template>
          <template v-else-if="item.label=='配货/发货状态'">
            {{scope.row.assignStatusName}}/{{ scope.row.deliveryStatusName }}
          </template>

          <template v-else-if="item.label=='发货信息'">
            <div v-for="(item, index) in scope.row.orderListDeliveryDTOList" :key="index">
              <div>{{ index+1 }}，{{ item.warehouseName }}</div>
              <div>{{item.code}} <i class="el-icon-document-copy" @click="copyText(item.code)"></i></div>
            </div>
          </template>
          <template v-else-if="item.label=='收货信息'">

            <el-tooltip class="item" content="Top center" placement="top">
              <div slot="content" style="width: auto">
                <div>{{scope.row.userName}}</div>
              </div>
              <div class="table-overflow2 table-overflow">{{scope.row.userName}}</div>
            </el-tooltip>

            <el-tooltip class="item" content="Top center" placement="top">
              <div slot="content" style="width: auto">
                <div>{{scope.row.userMobile}}</div>
              </div>
              <div class="table-overflow2 table-overflow">{{scope.row.userMobile}}</div>
            </el-tooltip>

            <el-tooltip class="item" content="Top center" placement="top">
              <div slot="content" style="width: auto">
                <div>{{ scope.row.userAddress }}</div>
              </div>
              <div class="table-overflow2 table-overflow">{{scope.row.userAddress}}</div>
            </el-tooltip>

          </template>
          <template v-else-if="item.label=='物流信息'">
            <div v-for="(item, index) in scope.row.orderListDeliveryDTOList" :key="index">
              <div>{{ index+1 }}，{{ item.expressStatusName || '--' }}</div>
              <template v-if="item.expressNo">
                <div  @click="showEx(scope.row, t, item)" class="link-ex"  v-for="t in item.expressNo.split(',')">{{t || '--' }}<i class="el-icon-document-copy" @click.stop="copyText(t)"></i></div>
              </template>
            </div>
          </template>
          <template v-else-if="item.label=='订单金额(元)'">
            <div>销售-{{ scope.row.orderPrice }}</div>
            <div>实付-{{ scope.row.payPrice }}</div>
            <div>成本-{{ scope.row.costPrice }}</div>
            <div>退款-{{ scope.row.refundPrice }}</div>
          </template>
          <template v-else-if="item.label=='订单操作时间'">
            <div v-if="scope.row.orderAt">下单-{{ scope.row.orderAt }}</div>
            <div v-if="scope.row.dealtime">接入-{{ scope.row.dealtime }} &nbsp;<span :class="[timeOver(scope.row.orderAt, scope.row.dealtime, scope.row.dealHour)?'color-r':'color-y']">{{getTimeDifference(scope.row.orderAt,scope.row.dealtime)}}</span></div>
            <div v-if="scope.row.riskControlApproveAt">封控-{{ scope.row.riskControlApproveAt }} &nbsp;<span :class="[timeOver(scope.row.dealtime, scope.row.riskControlApproveAt, scope.row.dealHour)?'color-r':'color-y']">{{getTimeDifference(scope.row.dealtime,scope.row.riskControlApproveAt)}}</span></div>
            <div v-if="scope.row.approveAt">审核-{{ scope.row.approveAt }} &nbsp;<span :class="[timeOver(scope.row.dealtime,scope.row.approveAt, scope.row.approveHour)?'color-r':'color-y']">{{getTimeDifference(scope.row.dealtime,scope.row.approveAt)}}</span></div>
            <div v-if="scope.row.assignAt">配货-{{ scope.row.assignAt }} &nbsp;<span :class="[timeOver(scope.row.approveAt,scope.row.assignAt, scope.row.assignHour)?'color-r':'color-y']">{{getTimeDifference(scope.row.approveAt,scope.row.assignAt)}}</span></div>
            <div v-if="scope.row.deliveryAt">发货-{{ scope.row.deliveryAt }} &nbsp;<span :class="[timeOver(scope.row.assignAt,scope.row.deliveryAt, scope.row.deliveryHour)?'color-r':'color-y']">{{getTimeDifference(scope.row.assignAt,scope.row.deliveryAt)}}</span></div>
            <div v-if="scope.row.pickupAt">揽件-{{ scope.row.pickupAt }} &nbsp;<span :class="[timeOver(scope.row.deliveryAt,scope.row.pickupAt, scope.row.pickupHour)?'color-r':'color-y']">{{getTimeDifference(scope.row.deliveryAt,scope.row.pickupAt)}}</span></div>
            <div v-if="scope.row.deliveryReceiptAt">签收-{{ scope.row.deliveryReceiptAt }} &nbsp;<span class="color-y">{{getTimeDifference(scope.row.pickupAt,scope.row.deliveryReceiptAt)}}</span></div>
          </template>
          <template v-else-if="item.label=='管易订单标记'">
              <el-tooltip class="item" content="Top center" placement="top">
                <div slot="content" style="width: auto">
                  <div>1，平台旗帜：{{scope.row.erpOrderFlag==1?'红':''}}
                  {{scope.row.erpOrderFlag==2?'黄':''}}
                  {{scope.row.erpOrderFlag==3?'绿':''}}
                  {{scope.row.erpOrderFlag==4?'蓝':''}}
                  {{scope.row.erpOrderFlag==5?'紫':''}}
                  {{scope.row.erpOrderFlag==0?'未插旗':''}}</div>

                </div>
                <div class="table-overflow2 table-overflow">1，平台旗帜：{{scope.row.erpOrderFlag==1?'红':''}}
                {{scope.row.erpOrderFlag==2?'黄':''}}
                {{scope.row.erpOrderFlag==3?'绿':''}}
                {{scope.row.erpOrderFlag==4?'蓝':''}}
                {{scope.row.erpOrderFlag==5?'紫':''}}
                {{scope.row.erpOrderFlag==0?'未插旗':''}}</div>
              </el-tooltip>

              <el-tooltip class="item" content="Top center" placement="top">
                <div slot="content" style="width: auto">
                  <div>2，拦截：{{scope.row.erpHoldInfo || '--'}}</div>
                </div>
                <div class="table-overflow2 table-overflow">2，拦截：{{scope.row.erpHoldInfo || '--'}}</div>
              </el-tooltip>

              <el-tooltip class="item" content="Top center" placement="top">
                <div slot="content" style="width: auto">
                  <div>3，订单标记：{{scope.row.erpOrderTag || '--'}}</div>
                </div>
                <div class="table-overflow2 table-overflow">3，订单标记：{{scope.row.erpOrderTag || '--'}}</div>
              </el-tooltip>

              <el-tooltip class="item" content="Top center" placement="top">
                <div slot="content" style="width: auto">
                  <div>4，附加信息：{{scope.row.erpAddInfo || '--'}}</div>
                </div>
                <div class="table-overflow2 table-overflow">4，附加信息：{{scope.row.erpAddInfo || '--'}}</div>
              </el-tooltip>
              <el-tooltip class="item" content="Top center" placement="top">
                <div slot="content" style="width: auto">
                  <div>5，异常信息：{{scope.row.erpExceptionInfo || '--'}}</div>
                </div>
                <div class="table-overflow2 table-overflow">5，异常信息：{{scope.row.erpExceptionInfo || '--'}}</div>
              </el-tooltip>
          </template>
          <template v-else-if="item.label=='订单操作超时标记'">
            <el-tag type="warning" style="margin-right: 4px;" v-for="(item,index) in scope.row.orderListTimeoutTagDTOList" :key="index">{{ item.tagName }}</el-tag>
          </template>
          <template v-else-if="item.label=='订单异常标记'">
            <el-tag type="warning" style="margin-right: 4px;" v-for="(item,index) in scope.row.orderListAbnormalTagDTOList" :key="index">{{ item.tagName }}</el-tag>
          </template>
          <template v-else>
            {{ scope.row[item.prop] }}
          </template>
        </template>


      </el-table-column>
      <el-table-column
        label="操作"
        width="90"
        fixed="right"
        align="center"
        prop="status"
      >
      <template slot-scope="scope">
          <el-button size="mini" type="text" @click="showDetail(scope.row)"
            >订单详情</el-button
          >
          <el-button style="margin: 0;" v-if="scope.row.orderStatus=='6'||scope.row.orderStatus=='9'" size="mini" type="text" @click="getDetail(scope.row.orderId)"
            >修改订单</el-button
          >
          <el-button v-if="scope.row.orderStatusName=='待配货'||scope.row.assignStatusName=='部分配货'" size="mini" type="text" @click="editEx(scope.row)"
            >修改收货信息</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      class="fixed-pagination"
    />

    <el-dialog
      :title="title"
      top="20px"
      :visible.sync="open"
      width="1100px"
      append-to-body
      :center='true'
      :close-on-click-modal="false"
      class="order-dialog"
      v-loading="submitLoading"
    >
    <el-alert type="warning" show-icon title="仅支持湘商TO B销售、内部员工个人销售和部门间销售订单创建" :closable="false"/>
    <el-tabs v-model="activeName2">
      <el-tab-pane label="编辑订单" name="1">
        <h3><span></span>订单销售信息</h3>
        <el-form ref="addForm" size="small" :model="orderForm" label-width="120px">
        <el-row>
          <el-col :span="13">
            <el-form-item
              label="渠道:"
              :rules="[{ required: true, message: '请选择渠道', trigger: 'change' }]"
              prop="channel"
            >
              <el-radio-group
                v-model="orderForm.channel"
                @change="channelChange"
              >
                <el-radio label="TO_B">渠道-TO B商户</el-radio>
                <el-radio label="EMPLOYEE_IN_PURCHASE">渠道-员工内购</el-radio>
                <el-radio label="INTERNAL_TRANSACTION">渠道-内部交易</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-alert v-if="orderForm.channel=='TO_B'" type="warning" :closable="false" show-icon title='"渠道-TO B商户"包括代发、抛货等面向B端商户的销售业务'/>
            <el-alert v-if="orderForm.channel=='EMPLOYEE_IN_PURCHASE'" type="warning" :closable="false" show-icon title='"渠道-员工内购"包括员工内购、外部个人关系用户等销售业务'/>
            <el-alert v-if="orderForm.channel=='INTERNAL_TRANSACTION'" type="warning" :closable="false" show-icon title='"渠道-内部交易"包括销售部门间商品销售'/>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="销售部门:"
              :rules="[{ required: true, message: '请选择销售部门', trigger: 'change' }]"
              prop="deptCode"
            >
              <el-select
                v-model="orderForm.deptCode"
                filterable
                placeholder="请选择销售部门"
                @change="deptCodeChange"
                clearable
              >
                <el-option
                  v-for="(dict, index) in brandNameList"
                  :key="index"
                  :label="dict.deptName"
                  :value="dict.deptCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="业务员:"
              :rules="[{ required: true, message: '请选择业务员', trigger: 'change' }]"
              prop="businessMan"
            >
              <el-select
                v-model="orderForm.businessMan"
                filterable
                placeholder="请选择业务员"
                clearable
              >
                <el-option
                  v-for="(dict, index) in businessManList"
                  :key="index"
                  :label="dict.name"
                  :value="dict.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="业务类型:"
              :rules="[{ required: true, message: '请选择业务类型', trigger: 'change' }]"
              prop="businessType"
            >
              <el-radio-group
                v-model="orderForm.businessType"
              >
                <el-radio label="JETTISON" :disabled="orderForm.channel=='EMPLOYEE_IN_PURCHASE'||orderForm.channel=='INTERNAL_TRANSACTION'">抛货</el-radio>
                <el-radio label="REPLACE_SEND" :disabled="orderForm.channel=='EMPLOYEE_IN_PURCHASE'||orderForm.channel=='INTERNAL_TRANSACTION'">代发</el-radio>
                <el-radio label="IN_PURCHASE" :disabled="orderForm.channel=='TO_B'||orderForm.channel=='INTERNAL_TRANSACTION'">内购</el-radio>
                <el-radio label="INTERNAL_TRANSACTION" :disabled="orderForm.channel!='INTERNAL_TRANSACTION'">内部交易</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="orderForm.channel!='INTERNAL_TRANSACTION'"
              :label="orderForm.channel=='TO_B'?'下单商户:':'买家会员'"
              :rules="[{ required: true, message: orderForm.channel=='TO_B'?'请填写下单商户':'请填写买家会员', trigger: 'change' }]"
              prop="buyVip"
            >
              <el-input v-model="orderForm.buyVip" :placeholder="orderForm.channel=='TO_B'?'请填写下单商户':'请填写买家会员'"></el-input>
            </el-form-item>
            <el-form-item
              v-else
              label="购买部门"
              :rules="[{ required: true, message: '请填写购买部门', trigger: 'change' }]"
              prop="buyVip"
            >
              <el-select
                v-model="orderForm.buyVip"
                placeholder="请选择购买部门"
                clearable
              >
              <el-option
                  v-for="dict in brandNameList"
                  :key="dict.deptName"
                  :label="dict.deptName"
                  :value="dict.deptName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item
              label="付款方式:"
              :rules="[{ required: true, message: '请选择付款方式', trigger: 'change' }]"
              prop="payType"
            >
              <el-radio-group
                v-model="orderForm.payType"
                @change="payTypeChange"
              >
                <el-radio label="FIRST_MONEY">先款后货</el-radio>
                <el-radio label="FIRST_PRODUCT">先货后款</el-radio>
              </el-radio-group>

            </el-form-item>
            <el-col :span="12" v-if="orderForm.payType=='FIRST_MONEY'">
              <el-form-item
                label="下单时间:"
                :rules="[{ required: true, message: '请选择下单时间', trigger: 'change' }]"
                prop="orderTime"
              >
                <el-date-picker
                  v-model="orderForm.orderTime"
                  type="datetime"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd hh:mm:ss"
                />
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="12" v-if="orderForm.payType=='FIRST_PRODUCT'">
            <el-form-item
              label="预计付款日期:"
              :rules="[{ required: true, message: '请选择预计付款日期', trigger: 'change' }]"
              prop="perPayTime"
            >
              <el-date-picker
                v-model="orderForm.perPayTime"
                type="datetime"
                placeholder="选择日期"
                value-format="yyyy-MM-dd hh:mm:ss"
              />

            </el-form-item>
          </el-col>
          <el-col :span="12" v-else>
            <el-form-item
              label="打款凭证:"
              :rules="[{ required: true, message: '请选择打款凭证', trigger: 'change' }]"
              prop="proofPath"
            >
            <el-upload
              class="upload-demo"
              :action="fileAction"
              :on-preview="handlePreview"
              :before-remove="beforeRemove"
              :on-remove="handleRemove"
              :on-success="handleFileSuccess"
              :headers="upload.headers"
              :before-upload="beforeAvatarUpload"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList"
            >
              <el-button size="small" icon="el-icon-plus"
                >点击上传</el-button
              >
            </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
          <el-form-item
            label="买家备注:"
            prop="userRemark"
          >
            <el-input
              v-model="orderForm.userRemark"
              placeholder="填写买家备注，最多100个字"
              clearable
              type="textarea"
            />
          </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="卖家备注:"
              prop="salerRemark"
            >
              <el-input
                v-model="orderForm.salerRemark"
                placeholder="填写卖家备注，最多100个字"
                clearable
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <h3><span></span>商品信息</h3>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="发货仓库:"
              :rules="[{ required: true, message: '请选择发货仓库', trigger: 'change' }]"
              prop="warehouseCode"
            >
            <el-select
              v-model="orderForm.warehouseCode"
              filterable
              placeholder="请选择发货仓库"
              @change="skuItems=[]"
              clearable
            >
              <el-option
                v-for="(dict, index) in warehouseLists"
                :key="index"
                :label="dict.warehouseName"
                :value="dict.warehouseCode"
              />
            </el-select>
          </el-form-item>
          </el-col>
        </el-row>
          <el-table ref="addTable" border v-loading="loading" :data="skuItems">
              <!-- <el-table-column type="selection" width="55" align="center" /> -->
              <el-table-column min-width="110" label="商品编码" align="center" prop="skuNo" />
              <el-table-column
                label="商品名称"
                min-width="140"
                align="center"
                prop="skuName"
              />
              <el-table-column
                label="采购成本价(元)"
                min-width="100"
                align="center"
                prop="cost"
              >
              </el-table-column>
              <el-table-column
                label="销售价格(元)"
                min-width="120"
                align="center"
                prop="sellPrice"
              >
                <template slot-scope="scope">
                  <el-input size="small" type="number" v-model="scope.row.sellPrice" @change="value=>sellPriceChange(value,scope.row)"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="销售数量"
                min-width="80"
                align="center"
                prop="sellQty"
              >
                <template slot-scope="scope">
                  <el-input size="small" type="number" v-model="scope.row.sellQty" @change="value=>sellPriceChange(value,scope.row)"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="销售毛利"
                min-width="70"
                align="center"
                prop="profit"
              />
              <el-table-column
                label="毛利率"
                min-width="60"
                align="center"
                prop="profitRate2"
              />
              <el-table-column
                label="可销库存"
                min-width="70"
                align="center"
                prop="inStock"
              />
              <el-table-column
                label="市场参考价"
                min-width="120"
                align="left"
                prop="inStock"
              >
                <template slot-scope="scope">
                  <div class="goProcure"  @click="goProcure(item.url)" v-for="(item,index) in scope.row.marketPrice" :key="index">
                    {{ item.name }}:{{ item.price }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                min-width="80"
                align="center"
                prop="attrName4"
              >
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="deleteRow(scope.row, scope.$index)">
                  删除
                </el-button>
              </template>
              </el-table-column>
            </el-table>
            <div class="sku-table">
              <el-popover placement="bottom" width="600" v-model="goodsVisible">
                <el-input
                  v-model="goodsText"
                  type="textarea"
                  :rows="8"
                  placeholder="多个商品编码使用逗号隔开"
                  clearable
                  @input="value=>copySkus(value,goodsText,2)"
                />
                <div style="text-align: right; margin-top: 4px">
                  <el-button size="mini" type="text" @click="goodsVisible = false"
                    >取消</el-button
                  >
                  <el-button
                    type="primary"
                    :loading="saveGoodsLoading"
                    size="mini"
                    @click="saveGoods"
                    >确定</el-button
                  >
                </div>
                <el-button icon="el-icon-plus" type="text" slot="reference">添加商品</el-button>
              </el-popover>
              <div class="total-table"> <span>总销售金额：{{ tableTotal }}元</span><span>整单毛利：{{ tableTotal2 }}元</span>
              <el-alert v-show="minpPofit!=null" type="warning" :closable="false" show-icon :title="'代发订单毛利率不能小于'+minpPofit+'%'" /> </div>
            </div>
            <h3><span></span>收货信息</h3>
            <el-row>
            <el-col :span="12">
              <el-form-item
                label="收货人:"
                :rules="[{ required: true, message: '请填写收货人姓名', trigger: 'change' }]"
                prop="receiverName"
              >
                <el-input
                  v-model="orderForm.receiverName"
                  placeholder="请填写收货人姓名"
                  clearable
                  type="text"
                />
              </el-form-item>
            </el-col>
              <el-col :span="12">
                <el-form-item
                  label="收货人手机:"
                  :rules="[
                  { required: true, message: '请填写收货人手机', trigger: 'change' },
                  { validator: this.checkPhoneNum, trigger: 'blur' }]"
                  prop="receiverPhone"
                >
                  <el-input
                    v-model="orderForm.receiverPhone"
                    placeholder="请填写收货人手机"
                    clearable
                    type="text"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item
                  label="收货地址:"
                  :rules="[{ required: true, message: '请填写收货地址机', trigger: 'change' }]"
                  prop="receiverAddress"
                >
                  <el-input
                    v-model="orderForm.receiverAddress"
                    @blur="addressBlur"
                    placeholder="请填写收货地址"
                    clearable
                    type="text"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item
                  label="地区信息:"
                  :rules="[{ required: true, message: '省市区', trigger: 'change' }]"
                  prop="receiverAddress2"
                >
                  <el-cascader ref="address" @change="addressChange" v-model="orderForm.receiverAddress2" :props="props" filterable :options="geoData" clearable></el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
            <h3><span></span>发票信息</h3>
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="是否开票:"
                  :rules="[{ required: true, message: '请选择是否开票', trigger: 'change' }]"
                  prop="invoiceType"
                >
                  <el-radio-group
                    v-model="orderForm.needInvoice"
                  >
                    <el-radio label="0">是</el-radio>
                    <el-radio label="1">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="orderForm.needInvoice==0">
              <el-col :span="12">
                <el-form-item
                  label="发票种类:"
                  :rules="[{ required: true, message: '请选择发票种类', trigger: 'change' }]"
                  prop="invoiceType"
                >
                  <el-radio-group
                    v-model="orderForm.invoiceType"
                    @change="invoiceTypeChange"
                  >
                    <el-radio label="NORMAL">普通发票</el-radio>
                    <el-radio label="VAT">专用发票</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="发票类型:"
                  :rules="[{ required: true, message: '请选择发票类型', trigger: 'change' }]"
                  prop="invoiceCatalogue"
                >
                  <el-radio-group
                    v-model="orderForm.invoiceCatalogue"
                  >
                    <el-radio label="ELECTRONIC">电子票</el-radio>
                    <!-- <el-radio label="PAPER">纸质发票</el-radio> -->
                  </el-radio-group>
                </el-form-item>

              </el-col>
            <el-col :span="12">
              <el-form-item
                label="抬头类型:"
                :rules="[{ required: true, message: '请选择抬头类型', trigger: 'change' }]"
                prop="invoiceTitleType"
              >
                <el-radio-group
                  v-model="orderForm.invoiceTitleType"
                  @change="invoiceTitleTypeChange"
                >
                  <el-radio label="PERSONAL" :disabled="orderForm.invoiceType=='VAT'">个人</el-radio>
                  <el-radio label="COMPANY">公司</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="orderForm.invoiceTitleType!='COMPANY'">
              <el-form-item
                label="个人姓名:"
                :rules="[{ required: true, message: '请填写个人姓名', trigger: 'change' }]"
                prop="invoiceTitle"
              >
                <el-input
                  v-model="orderForm.invoiceTitle"
                  placeholder="请填写个人姓名"
                  clearable
                  type="text"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="orderForm.invoiceTitleType=='COMPANY'&&orderForm.needInvoice==0">
            <el-col :span="12">
              <el-form-item
                label="公司名称:"
                :rules="[{ required: true, message: '请填写公司名称', trigger: 'change' }]"
                prop="invoiceTitle"
              >
                <el-input
                  v-model="orderForm.invoiceTitle"
                  placeholder="请填写公司名称"
                  clearable
                  type="text"
                />
              </el-form-item>
            </el-col>
              <el-col :span="12">
                <el-form-item
                  label="纳税人识别号:"
                  :rules="[{ required: true, message: '请填写纳税人识别号', trigger: 'change' }]"
                  prop="ratepayerCode"
                >
                  <el-input
                    v-model="orderForm.ratepayerCode"
                    placeholder="请填写纳税人识别号"
                    clearable
                    type="text"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="注册地址:"
                  :rules="orderForm.invoiceType=='VAT'?[{ required: true, message: '请填写注册地址', trigger: 'change' }]:[]"
                  prop="registerAddress"
                >
                  <el-input
                    v-model="orderForm.registerAddress"
                    placeholder="请填写注册地址"
                    clearable
                    type="text"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="注册电话:"
                  :rules="orderForm.invoiceType=='VAT'?[{ required: true, message: '请填写注册电话', trigger: 'change' }]:[]"
                  prop="registerPhone"
                >
                  <el-input
                    v-model="orderForm.registerPhone"
                    placeholder="请填写注册电话"
                    clearable
                    type="text"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="开户银行:"
                  :rules="orderForm.invoiceType=='VAT'?[{ required: true, message: '请填写开户银行', trigger: 'change' }]:[]"
                  prop="registerBank"
                >
                  <el-input
                    v-model="orderForm.registerBank"
                    placeholder="请填写开户银行"
                    clearable
                    type="text"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="银行账户:"
                  :rules="orderForm.invoiceType=='VAT'?[{ required: true, message: '请填写银行账户', trigger: 'change' }]:[]"
                  prop="registerAccount"
                >
                  <el-input
                    v-model="orderForm.registerAccount"
                    placeholder="请填写银行账户"
                    clearable
                    type="text"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          <!-- <el-row>
          <el-col :span="12">
            <el-form-item
              label="收票人:"
              :rules="[{ required: true, message: '请填写收票人姓名', trigger: 'change' }]"
              prop="receiverInvoice"
            >
              <el-input
                v-model="orderForm.receiverInvoice"
                placeholder="请填写收票人姓名"
                clearable
                type="text"
              />
            </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="收票人手机:"
                :rules="[{ required: true, message: '请填写收票人手机', trigger: 'change' }]"
                prop="receiveInvoicePhone"
              >
                <el-input
                  v-model="orderForm.receiveInvoicePhone"
                  placeholder="请填写收票人手机"
                  clearable
                  type="text"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="收票地址:"
                :rules="[{ required: true, message: '请填写收票地址', trigger: 'change' }]"
                prop="receiveInvoiceAddress"
              >
                <el-input
                  v-model="orderForm.receiveInvoiceAddress"
                  placeholder="请填写收票地址"
                  clearable
                  @blur="addressBlur2"
                  type="text"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="地区信息:"
                :rules="[{ required: true, message: '省市区', trigger: 'change' }]"
                prop="receiveInvoiceAddress2"
              >
                <el-cascader ref="address2" @change="addressChange2" v-model="orderForm.receiveInvoiceAddress2" :props="props" filterable :options="geoData" clearable></el-cascader>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>

      </el-tab-pane>
      <el-tab-pane label="操作日志" name="2">
        <el-table
          ref="logTable"
          border
          :data="operationLogList"
        >
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column
              label="操作步骤"
              min-width="140"
              align="left"
              prop="operationType"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.operationType=='COMMIT'?'提交审核':'' }}</span>
                <span>{{ scope.row.operationType=='APPROVED'?'审核通过':'' }}</span>
                <span>{{ scope.row.operationType=='REJECTION'?'审核打回':'' }}</span>
                <span>{{ scope.row.operationType=='PUSH_ERP'?'推送erp':'' }}</span>
                <span>{{ scope.row.operationType=='PUSH_JULIAN'?'推送Julian':'' }}</span>
                <span>{{ scope.row.operationType=='ERP_UPDATE'?'同步管易':'' }}</span>
                <span>{{ scope.row.operationType=='ADDRESS_UPDATE'?'修改地址':'' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作描述" min-width="140" align="left" prop="logMsg">
              <template slot-scope="scope">
                <span v-html="scope.row.operationContent"></span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作人"
              min-width="100"
              align="left"
              prop="operationMan"
            />
            <el-table-column
              label="操作时间"
              min-width="140"
              align="left"
              prop="operationTime"
            />
        </el-table>
      </el-tab-pane>
    </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope" :loading="submitLoading">提交审批</el-button>
        <el-button @click="open = fasle">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess2"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
          <div style="color:#E6A23C;">只能修改未配货订单的收货信息</div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </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>

    <el-dialog
      :title="importOrder.title"
      :visible.sync="importOrder.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="importOrder.headers"
        :action="importOrder.url"
        :disabled="importOrder.isUploading"
        :on-progress="handleImportOrderFileUploadProgress"
        :on-success="handleImportOrderFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importOrderTemplate"
          >下载模板
          </el-link
          >
        </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>

    <el-dialog
      title="推送聚链代发"
      :visible.sync="jlVisible"
      width="1000px"
      append-to-body
      :center="true"
    >
      <Jldetail :ids="ids" :jlVisible="jlVisible" @close="closeJl" />
    </el-dialog>

    <el-dialog
      title="修改收货信息"
      top="50px"
      :visible.sync="open3"
      width="500px"
      append-to-body
    >
      <el-form ref="exForm" :model="exForm" label-width="120px">
        <el-form-item
          label="收货人:"
          :rules="[{ required: true, message: '请填写收货人', trigger: 'change' }]"
          prop="userName"
        >
          <el-input
            v-model="exForm.userName"
            placeholder="请填写收货人"
            clearable
            style="width: 280px"
            type="text"
          />
        </el-form-item>
        <el-form-item
          label="收货人手机号:"
          :rules="[
            { required: true, message: '请填写收货人手机', trigger: 'change' },
            { validator: this.checkPhoneNum, trigger: 'blur' }]"
          prop="userMobile"
        >
          <el-input
            v-model="exForm.userMobile"
            placeholder="请填写收货人手机号"
            clearable
            style="width: 280px"
            type="text"
          />
        </el-form-item>
        <el-form-item
          label="收货地址:"
          :rules="[{ required: true, message: '请填写收货地址', trigger: 'change' }]"
          prop="userAddress"
        >
          <el-input
            v-model="exForm.userAddress"
            @blur="addressBlur3"
            placeholder="请填写收货地址"
            clearable
            type="text"
          />
          <el-alert type="warning" style="line-height: 1.2;" :closable="false" show-icon title='输入完整地址后，系统自动解析成省市区'/>
        </el-form-item>

        <el-form-item
          label="地区信息:"
          :rules="[{ required: true, message: '省市区', trigger: 'change' }]"
          prop="userAddress2"
        >
          <el-cascader ref="address3"  @change="addressChange3" v-model="exForm.userAddress2" :props="props" filterable :options="geoData" clearable></el-cascader>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button :loading="saveLoading" type="primary" @click="submitForm"
          >保存</el-button
        >
        <el-button @click="open3 = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="物流信息"
      width="600px"
      :visible.sync="showDeliveryExpressDialog"
      top="50px"
      :center="true"
      class="abdialog"
    >
      <span style="padding-left: 25px;font-size: 16px;color: #333;">{{ showDeliveryExpressName }}</span>
      <el-timeline style="margin-top: 16px;">
        <el-timeline-item
          placement="top"
          v-for="(express, index) in expressTimeLine"
          :key="index"
          type="success"
          :timestamp="express.time"
        >
          <el-card>
            <p style="margin: 0;">{{ express.context }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="showDeliveryExpressDialog = false">返回</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {getBrandNameList, getList, warehouseList} from "@/api/goods/index";
import {
  addBusinessFlag,
  cancelJulianSend,
  expressInfo,
  lbsGeo,
  operationLog,
  orderList,
  platformList,
  queryBusinessMan,
  queryCustomer,
  queryDistrict,
  queryOrderTabs,
  querySaleDept,
  queryTags,
  tradeOrdeCreate,
  tradeOrdeDetail,
  tradeOrdeUpdate,
  updateUserReceiveInfo
} from '@/api/order/index';
import {saleTargetChannelList,} from "@/api/saleConfig/saleTarget";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";
import Jldetail from "./Jldetail";
import {getToken} from "@/utils/auth";
import {newDownload2} from '@/utils/newRequest2';

var domain = window.location.hostname;

export default {
  name: "/order/index",
  components: {
    LoadMoreSelect,
    Jldetail,
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      saveLoading: false,

      // 选中数组
      ids: [],
      rows: [],
      channelList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      total2: 0,
      // 岗位表格数据
      postList: [],
      postList2: [],
      brandNameList2: [],
      goodsText: '',
      title: '新增订单',
      fileList: [],
      platformLists: [],
      tabNum:['(0)','(0)','(0)','(0)'],
      // 是否显示弹出层
      open: false,
      open2: false,
      open3: false,
      goodsVisible: false,
      saveGoodsLoading: false,
      submitLoading: false,
      jlVisible: false,
      detailVisible: false,
      activeName: '0',
      activeName2: '1',
      geoData: [],
      presentText: [],
      presentText2: '',
      presentText3: [],
      showForm: false,
      showDeliveryExpressDialog: false,
      showDeliveryExpressName: '',
      expressTimeLine: [],
      exForm: {
        userName: "",
        userMobile: "",
        userAddress: "",
        userAddress2: ''
      },
      orderTypeList:[
        {label:'全部',value:'0'},
        {label:'代发货',value:'1'},
        {label:'即将逾期发货',value:'2'},
        {label:'已逾期发货',value:'3'},
        {label:'已发货未收货',value:'4'}
      ],
      businessTypeList:[
        {label:'电商销售',value:'0'},
        {label:'抛货',value:'1'},
        {label:'内购',value:'2'},
        {label:'代发',value:'3'},
        {label:'内部交易',value:'4'}
      ],
      orderStatusList:[
        {label:'草稿',value:'-2'},
        {label:'待制单审核',value:'-1'},
        {label:'待平台风控审核',value:'10'},
        {label:'待审单',value:'0'},
        {label:'待配货',value:'4'},
        {label:'待发货',value:'1'},
        {label:'已发货',value:'2'},
        {label:'已签收',value:'5'},
        {label:'已取消',value:'3'},

        // {label:'飞书草稿',value:'6'},
        // {label:'飞书待审批',value:'7'},
        // {label:'飞书审批结束/待复核',value:'8'},
        // {label:'审核驳回',value:'9'},
      ],
      afterSaleTypeList:[
        {label:'极速退款',value:'1'},
        {label:'仅退款',value:'2'},
        {label:'退货退款',value:'3'}
      ],
      afterSaleStatusList:[
        {label:'售后处理中',value:'1'},
        {label:'已退款',value:'2'},
        {label:'已退款未退货',value:'3'},
        {label:'已退款已退货',value:'3'},
        {label:'已退货未退款',value:'3'},
      ],
      payStatusList:[
        {label:'未付款',value:'0'},
        {label:'已付款',value:'1'},
      ],
      invoiceStatusList:[
        {label:'等待中',value:'-1'},
        {label:'待开票',value:'0'},
        {label:'开票中',value:'1'},
        {label:'开票成功',value:'2'},
        {label:'开票失败',value:'3'},
      ],
      deliveryTypeList:[
        {label:'自有仓发货',value:'1'},
        {label:'聚链代发',value:'2'},
        {label:'由你代发',value:'3'},
        {label:'线下代发',value:'4'},
      ],
      dateTypeList:[
        {label:'下单时间',value:'1'},
        {label:'支付时间',value:'2'},
        {label:'接入管易时间',value:'3'},
        {label:'审单时间',value:'4'},
        {label:'配货时间',value:'5'},
        {label:'发货时间',value:'6'},
        {label:'揽件时间',value:'7'},
        {label:'签收时间',value:'8'},
      ],
      abnormalTagList:[
        {label:'超期未收款',value:'1'},
        {label:'电商平台发货同步失败',value:'2'},
        {label:'管易发货失败',value:'3'},
        {label:'退货未入仓',value:'4'},
      ],
      timeoutTagList:[
        {label:'审单逾期',value:'1'},
        {label:'配货逾期',value:'2'},
        {label:'仓库发货逾期',value:'3'},
        {label:'快递揽件逾期',value:'4'},
        {label:'退货入仓逾期',value:'5'},
        {label:'湘商整体发货逾期',value:'6'},
      ],
      bussinessFlagList:[
        {label:'标记聚链代发',value:'1'},
      ],
      pushOrderStatusList:[
        {label:'已推送聚链代发',value:'1'},
        {label:'撤销聚链代发',value:'1'},
      ],
      deliveryStatusList:[
        {label:'未发货',value:'0'},
        {label:'部分发货',value:'1'},
        {label:'全部发货',value:'2'},
      ],
      // 查询参数
      queryParams: {
        orderType: [],
        platformNo: [],
        shopCode: [],
        businessType: [],
        businessMan: [],
        platformCode: '',
        goodCode: '',
        goodName: '',
        uniqueCode: '',
        orderStatus: [],
        afterSaleType: [],
        afterSaleStatus: [],
        payStatus: [],
        invoiceStatus: [],
        deliveryType: [],
        warehouseName: [],
        vipName: [],
        userName: '',
        userMobile: '',
        dateType: '1',
        dateRange: [],
        abnormalTag: [],
        timeoutTag: [],
        expressNo: '',
        businessFlag: [],
        pushOrderStatus: [],
        departmentCode: [],
        pageNum: 1,
        pageSize: 10,
      },
      orderForm:{
        channel: 'TO_B',
        payType: 'FIRST_MONEY',
        businessType: 'JETTISON',
        invoiceType: 'NORMAL',
        invoiceCatalogue: 'ELECTRONIC',
        invoiceTitleType: 'PERSONAL',
        needInvoice: '0',
        "approveCode": "",
        "businessMan": "",
        "buyVip": "",
        "deptCode": "",
        "deptName": "",
        "invoiceTitle": "",
        "item": [],
        "orderTime": "",
        "perPayTime": "",
        "platformCode": "",
        "proofName": "",
        "proofPath": "",
        "ratepayerCode": "",
        "receiveInvoiceAddress": "",
        receiveInvoiceAddress2: "",
        "receiveInvoiceCity": "",
        "receiveInvoiceDistrict": "",
        "receiveInvoicePhone": "",
        "receiveInvoiceProvince": "",
        "receiverAddress": "",
        receiverAddress2: '',
        "receiverCity": "",
        "receiverDistrict": "",
        "receiverInvoice": "",
        "receiverName": "",
        "receiverPhone": "",
        "receiverProvince": "",
        "registerAccount": "",
        "registerAddress": "",
        "registerBank": "",
        "registerPhone": "",
        "salerRemark": "",
        "userRemark": "",
        "warehouseCode": "",
        "warehouseName": ""
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        "configMonth": "",
        "packageFee": '',
        "packageMaterialFeeList": [],
        "packageTreeFee": '',
        "warehouseFee": ''
      },
      skuItems: [],
      timer: null,
      attrOpen: false,
      title2: "",
      chartLading: true,
      loadDataStatus: true,
      tableHeight: "auto",
      tableTotal: 0,
      tableTotal2: 0,
      logTableList: [],
      attrLists: [],
      form2:{
        dateRange:[]
      },
      props:{
        value: 'adcode',
        label: 'name',
        children: 'districts'
      },
      fileAction: process.env.VUE_APP_BASE_API_NEW + "/activitie/upload/file",
      columns: [{
        key: 1,
        label: '订单/商品',
        width: '205',
        prop: 'erpCode',
        align: 'left',
        fixed: 'left',
        visible: true
      },{
        key: 2,
        label: '渠道/店铺',
        width: '120',
        prop: 'platformName',
        visible: true
      },{
        key: 3,
        label: '销售部门',
        width: '120',
        prop: 'departmentName',
        visible: true
      },{
        key: 4,
        label: '业务类型',
        width: '90',
        prop: 'businessTypeName',
        visible: true
      },{
        key: 5,
        label: '业务员',
        width: '90',
        prop: 'businessMan',
        visible: true
      },{
        key: 6,
        label: '购买用户',
        width: '120',
        prop: 'vipName',
        visible: true
      },{
        key: 7,
        label: '订单金额(元)',
        width: '120',
        prop: 'orderPrice',
        visible: true
      },{
        key: 8,
        label: '订单状态',
        width: '90',
        prop: 'orderStatusName',
        visible: true
      },{
        key: 9,
        label: '配货/发货状态',
        width: '110',
        prop: 'deliveryStatusName',
        visible: true
      },{
        key: 10,
        label: '代发信息',
        width: '90',
        prop: 'createdTime',
        visible: true
      },{
        key: 11,
        label: '业务标记',
        width: '100',
        prop: 'businessFlagName',
        visible: true
      },{
        key: 12,
        label: '发货信息',
        width: '160',
        prop: 'createdTime',
        visible: true
      },{
        key: 13,
        label: '管易订单标记',
        width: '130',
        prop: 'erpOrderTag',
        visible: true
      },{
        key: 14,
        label: '收货信息',
        width: '120',
        prop: 'userName',
        visible: true
      },{
        key: 15,
        label: '物流信息',
        width: '150',
        prop: 'deliveryStatusName',
        visible: true
      },
      // {
      //   key: 16,
      //   label: '售后状态',
      //   width: '90',
      //   prop: 'afterSaleTypeName',
      //   visible: true,
      //   hidden: true
      // },
      {
        key: 16,
        label: '付款状态',
        width: '90',
        prop: 'payStatusName',
        visible: true
      },{
        key: 17,
        label: '开票状态',
        width: '90',
        prop: 'invoiceStatusName',
        visible: true
      },{
        key: 18,
        label: '订单操作时间',
        width: '220',
        prop: 'createdTime',
        visible: true
      },{
        key: 19,
        label: '订单操作超时标记',
        width: '130',
        prop: 'createdTime',
        visible: true
      },{
        key: 20,
        label: '订单异常标记',
        width: '120',
        prop: 'createdTime',
        visible: true
      }],
      minpPofit: null,
      randomKey: Math.random(),
      pickerOptions: {
        shortcuts: [
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 用户导入参数
      importOrder: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API_NEW + "/tradeOrder/import",
      },

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: (domain=='oco.xsbuy.cn'?'https://m.xsbuy.cn/api':'http://test.xsbuy.cn/api') + "/outer/order/user-receive-info/upload",
      },
      brandNameList:[],
      businessManList: [],
      customerList: [],
      warehouseLists: [],
      operationLogList: [],
      deptList: [],
      tags1: [],
      tags2: [],
      orderId: ''
    };
  },
  created() {
    if (localStorage.getItem("orderIndex-query")) {
      this.queryParams = JSON.parse(localStorage.getItem("orderIndex-query"));
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
    }

    let startDate = "",
        endDate = "";

    const date = new Date();
    const year = date.getFullYear();
    const month =
      date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    endDate = year + "-" + month + "-" + day;

    date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
    const year2 = date.getFullYear();
    const month2 =
      date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    const day2 = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    startDate = year2 + "-" + month2 + "-" + day2;

    this.queryParams.dateRange = [startDate, endDate];

    this.getList(1);
    this.getDept();
  },
  mounted() {},
  methods: {
    zkForm(){
      this.showForm=!this.showForm;
      if(!this.showForm){
        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 260;
          this.tableHeight = height + "px";
        });
      }
    },
    showDetail(row){
      // this.detailVisible = true;
      this.$router.push('/orderDetail?orderId='+row.orderId);
    },
    getDetail(orderId){
      tradeOrdeDetail({orderId}).then(res=>{
        if(res.status==200){
          const skuItems = [];
          res.data.item.forEach(item=>{
            item.minpPofit = item.profit/item.cost || 0;
            skuItems.push(item);
          });

          this.skuItems = skuItems;
          this.orderForm = Object.assign(this.orderForm,res.data);
          this.orderForm.orderId = orderId;

          const receiverProvince = parseInt(this.orderForm.receiverProvince.split('/')[0]);
          this.presentText[0] = this.orderForm.receiverProvince.split('/')[1];
          const receiverCity = parseInt(this.orderForm.receiverCity.split('/')[0]);
          this.presentText[1] = this.orderForm.receiverCity.split('/')[1];
          const receiverDistrict = parseInt(this.orderForm.receiverDistrict.split('/')[0]);
          this.presentText[2] = this.orderForm.receiverDistrict.split('/')[1];

          this.orderForm.receiverAddress2 = [receiverProvince,receiverCity,receiverDistrict];
          this.fileList = [];
          if(res.data.proofName){
            this.fileList.push({ name: res.data.proofName, path: res.data.proofPath });
          }

          this.sellPriceChange('',this.skuItems[0]);

          this.open = true;
          this.title = '编辑订单';
        }
      });
      operationLog({orderId}).then(res=>{
        if(res.status==200){
          this.operationLogList = res.data;
        }
      });
    },
    getDept(){
      // gyDeptList({}).then((res) => {
      //   this.deptList = res.data;
      // });
      querySaleDept().then(res=>{
        if(res.status==200){
          this.brandNameList = res.data;
        }
      });
      queryBusinessMan().then(res=>{
        if(res.status==200){
          this.businessManList = res.data;
        }
      });
      queryCustomer().then(res=>{
        if(res.status==200){
          this.customerList = res.data;
        }
      });
      warehouseList().then(res=>{
        if(res.status==200){
          this.warehouseLists = res.data.list;
        }
      });
      queryDistrict({keywords:'中国',subDistrict:3}).then(res=>{
        if(res.status==200){
          this.geoData = res.data[0].districts;
          this.geoDataFilter(this.geoData);
        }
      });
      platformList().then(res=>{
        if(res.status==200){
          this.platformLists = res.data.platformListResDTOS;
        }
      });
      saleTargetChannelList().then((res) => {
        if(res.status==200){
          this.channelList = res.data || [];
        }
      });
      queryTags({tagType:0}).then(res=>{
        if(res.status==200){
          this.tags1 = res.data;
        }
      });
      queryTags({tagType:1}).then(res=>{
        if(res.status==200){
          this.tags2 = res.data;
        }
      });
      getBrandNameList().then((res) => {
        this.brandNameList2 = res.data;
      });
    },
    handleCommand(command){
      if(command=='a'){
        const ids = []
        for(let i=0;i<this.ids.length;i++){
          if((this.ids[i].orderStatusName=='待配货'||this.ids[i].assignStatusName=='部分配货')&&this.ids[i].isDecrypt==1){
            ids.push(this.ids[i]);
          }
        }
        if(ids.length==0){
          this.$message.warning('请选择需要推送聚链发货的订单(订单状态为待配货或部分配货，且收货信息已解密)');
          return false;
        }
        const Jldetailids = ids.map((item) => item.orderId);
        sessionStorage.setItem('Jldetail-ids',JSON.stringify(Jldetailids));
        // this.jlVisible = true;
        this.$router.push('/Jldetail')
      }else if(command=='b'){
        if(this.ids.length==0){
          this.$message.warning('请选择单据');
          return false;
        }
        cancelJulianSend(this.rows).then(res=>{
          if(res.status==200){
            this.$message.success('全部成功撤销聚链代发');
            this.getList();
            this.$refs.proTable.clearSelection();
          }
        })
      }else if(command=='c'){
        this.$router.push('/osOrder');
      }
    },
    handleCommand2(command){
      if(this.ids.length==0){
        this.$message.warning('请选择单据');
        return false;
      }
      const orderId = [],business_flag=[];
      this.rows.forEach(item=>{
        orderId.push(item.orderId);
        business_flag.push(1);
      });
      addBusinessFlag({
        orderId: orderId,
        business_flag: business_flag
      }).then(res=>{
        if(res.status==200){
          this.$message.success('标记成功');
          this.getList();
          this.$refs.proTable.clearSelection();
        }
      })
    },
    copySkus(value,row,type){
      // row = value.replace(/\s+/g, ',');
      // row = value.trim().split(/\s+/).join(',');
      if(type==2){
        this.goodsText = value.trim().split(/\s+/).join(',')
      }else{
        this.$set(this.queryParams,row,value.trim().split(/\s+/).join(','))
      }
    },
    closeJl(){
      this.jlVisible = false;
      this.getList();
      this.$refs.proTable.clearSelection();
    },
    closeDetail(){
      this.detailVisible = false;
    },
    geoDataFilter(value){
      for(let i=0;i<value.length;i++){
        if(value[i].districts.length<1){
          value[i].districts = undefined;
        }else{
          if(value[i]){
            this.geoDataFilter(value[i].districts)
          }
        }
      }
    },
    deptCodeChange(value){
      const data = this.brandNameList.find(item=>{
        return item.deptCode == value;
      })
      this.orderForm.deptName = data.deptName;
    },
    handleCheckedCitiesChange(value) {
      // let checkedCount = value.length;
      // this.checkAll = checkedCount === this.cities.length;
      // this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
      this.cities = value;
    },
    deleteRow(row,index){
      this.skuItems.splice(index, 1);
    },
    handleImport(){
      this.upload.title = "收货信息导入";
      this.upload.open = true;
    },
    handleImportOrder() {
      this.importOrder.title = "手工单批量导入";
      this.importOrder.open = true;
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;

      localStorage.setItem("orderIndex-query", JSON.stringify(this.queryParams));

      this.queryParams.orderType = this.activeName;
      if(this.activeName!='0'){
        this.queryParams.orderStatus = [];
      }
      orderList(this.queryParams).then((response) => {
        if(response.status==200){
          this.postList = response.data.orderListResDTOS;
          this.total = response.data.total;

          // response.data.orderTabs.forEach(item=>{
          //   this.$set(this.tabNum,item.order_type-1,'('+item.order_num+')')
          // })
        }

        this.loading = false;
        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 260;
          this.tableHeight = height + "px";
        });
      }).catch(err=>{
        this.loading = false;
      });

      queryOrderTabs(this.queryParams).then(res=>{
        if(res.status==200){
          res.data.forEach(item=>{
            this.$set(this.tabNum,item.order_type-1,'('+item.order_num+')')
          })
        }
      })
      // this.loading = true;
      // if(type==1){
      //   warehouseConfigList(this.queryParams).then((response) => {
      //     this.postList = response.data.warehouseFeeConfigConfigListResDTOS;
      //     this.total = response.data.total;
      //     this.loading = false;

      //     this.$nextTick(() => {
      //       const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 260;
      //       this.tableHeight = height + "px";
      //     });
      //   });
      // }else{
      //   billUploadList(this.queryParams2).then((response) => {
      //     this.postList2 = response.data.warehouseFeeBillListResDTOS;
      //     this.total2 = response.data.total;
      //     this.loading = false;

      //     this.$nextTick(() => {
      //       const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 260;
      //       this.tableHeight = height + "px";
      //     });
      //   });
      // }

    },
    dowaLoadBill(row){
      window.open('https://newfirst.oss-cn-shanghai.aliyuncs.com/'+row.filePath);
    },
    goProcure(url){
      // this.$router.push({
      //   path: url
      // });
      window.open(url)
    },
    sellPriceChange(value,row){
      if(row.sellPrice&&row.sellQty){
        row.profit = (parseFloat(row.sellPrice) - parseFloat(row.cost))*parseFloat(row.sellQty);
        row.profitRate2 = ((((parseFloat(row.sellPrice) - parseFloat(row.cost))/parseFloat(row.cost))*100).toFixed(2)!='Infinity' ? (((parseFloat(row.sellPrice) - parseFloat(row.cost))/parseFloat(row.cost))*100).toFixed(2) : 0 ) + '%';
        row.profitRate = (parseFloat(row.sellPrice) - parseFloat(row.cost))/parseFloat(row.cost) !='Infinity' ? (parseFloat(row.sellPrice) - parseFloat(row.cost))/parseFloat(row.cost) : 0;
        let tableTotal=0,tableTotal2=0;
        this.skuItems.forEach(item=>{
          tableTotal += parseFloat(item.sellPrice)*parseFloat(item.sellQty);
          tableTotal2 += (parseFloat(item.sellPrice) - parseFloat(item.cost))*parseFloat(item.sellQty);
        })
        this.tableTotal = tableTotal;
        this.tableTotal2 = tableTotal2;
      }
    },
    payTypeChange(){
      if(this.orderForm.payType=='FIRST_PRODUCT'){
        this.orderForm.proofPath = '';
        this.orderForm.proofName = '';
      }else{
        this.orderForm.perPayTime = '';
      }
    },
    invoiceTitleTypeChange(){
      if(this.orderForm.invoiceTitleType!='COMPANY'){
        this.orderForm.invoiceTitle = '';
        this.orderForm.ratepayerCode = '';
        this.orderForm.registerAddress = '';
        this.orderForm.registerPhone = '';
        this.orderForm.registerBank = '';
        this.orderForm.registerAccount = '';
      }
    },
    invoiceTypeChange(val){
      if(val=='VAT'){
        this.orderForm.invoiceTitleType = 'COMPANY';
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = [];
      this.rows = [];
      selection.forEach((item) => {
        // item.orderListDetailDTOList.forEach(i=>{
        //   this.ids.push(i.orderId);
        // })
        this.ids.push(item);
        this.rows.push({
          erpCode: item.erpCode,
          orderId: item.orderId,
          platformCode: item.platformCode
        });
      });
    },
    channelChange(val){
      if(val=='EMPLOYEE_IN_PURCHASE'){
        this.orderForm.businessType = 'IN_PURCHASE';
      }else if(val=='INTERNAL_TRANSACTION'){
        this.orderForm.businessType = 'INTERNAL_TRANSACTION';
      }else{
        this.orderForm.businessType = 'JETTISON';
      }
    },
    cellStyle(row){
      if(row.row.orderListTimeoutTagDTOList&&row.row.orderListTimeoutTagDTOList.length>0){
        return 'background: rgb(255,238,211);'
      }
      if(row.row.orderListAbnormalTagDTOList&&row.row.orderListAbnormalTagDTOList.length>0){
        return 'background: rgb(247,186,186);'
      }
    },
    submitForm(){
      const data = {};
      data.orderId = this.orderId;
      data.userName = this.exForm.userName;
      data.userMobile = this.exForm.userMobile;
      data.userAddress = this.exForm.userAddress;
      data.userProvince = this.exForm.userAddress2[0]+'/'+this.presentText3[0];
      data.userCity = this.exForm.userAddress2[1]+'/'+this.presentText3[1];
      data.userDistrict = this.exForm.userAddress2[2]+'/'+this.presentText3[2];


      this.saveLoading = true;
      updateUserReceiveInfo(data).then(res=>{
        if(res.status==200){
          this.$message.success('修改成功');
          this.open3 = false;
          this.getList();
        }
        this.saveLoading = false;
      }).catch(_=>{
        this.saveLoading = false;
      })
    },
    editEx(row){
      this.resetForm('exForm')
      this.exForm.userName = row.userName;
      this.exForm.userMobile = row.userMobile;
      this.exForm.userAddress = row.userAddress;
      this.addressBlur3()
      this.orderId = row.orderId;
      this.open3 = true;
    },
    showEx(row, item, items){
      this.showDeliveryExpressDialog = true;
      this.showDeliveryExpressName = items.expressName +'   '+ items.expressNo;
      expressInfo({
        expressNo: item,
        orderId: row.orderId
      }).then(res=>{
        if(res.status==200){
          if (res.data) {
            this.expressTimeLine = res.data;
          } else {
            this.expressTimeLine = [{ time: "", context: "暂无物流信息" }];
          }
        }
      })
    },
    copyText(text) {
      window.navigator.clipboard
        .writeText(text)
        .then(() => {
          // this.$message.success("复制成功");
          this.$message({
            message: "复制成功",
            type: "success",
            customClass: "phone-message",
            center: true,
          });
        })
        .catch((error) => {
          // this.$message.warning("复制失败");
          this.$message({
            message: "复制失败",
            type: "warning",
            customClass: "phone-message",
            center: true,
          });
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.$refs.proTable.clearSelection();
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        orderType: '',
        platformNo: [],
        shopCode: [],
        businessType: [],
        businessMan: [],
        platformCode: '',
        goodCode: '',
        goodName: '',
        uniqueCode: '',
        orderStatus: [],
        afterSaleType: [],
        afterSaleStatus: [],
        payStatus: [],
        invoiceStatus: [],
        deliveryType: [],
        warehouseName: [],
        vipName: [],
        userName: '',
        userMobile: '',
        dateType: '1',
        dateRange: [],
        abnormalTag: [],
        timeoutTag: [],
        expressNo: '',
        businessFlag: [],
        pushOrderStatus: [],
        departmentCode: [],
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.orderForm = {
        channel: 'TO_B',
        payType: 'FIRST_MONEY',
        businessType: 'JETTISON',
        invoiceType: 'NORMAL',
        invoiceCatalogue: 'ELECTRONIC',
        invoiceTitleType: 'PERSONAL',
        needInvoice: '0',
        "approveCode": "",
        "businessMan": "",
        "buyVip": "",
        "deptCode": "",
        "deptName": "",
        "invoiceTitle": "",
        "item": [],
        "orderTime": "",
        "perPayTime": "",
        "platformCode": "",
        "proofName": "",
        "proofPath": "",
        "ratepayerCode": "",
        "receiveInvoiceAddress": "",
        receiveInvoiceAddress2: "",
        "receiveInvoiceCity": "",
        "receiveInvoiceDistrict": "",
        "receiveInvoicePhone": "",
        "receiveInvoiceProvince": "",
        "receiverAddress": "",
        receiverAddress2: '',
        "receiverCity": "",
        "receiverDistrict": "",
        "receiverInvoice": "",
        "receiverName": "",
        "receiverPhone": "",
        "receiverProvince": "",
        "registerAccount": "",
        "registerAddress": "",
        "registerBank": "",
        "registerPhone": "",
        "salerRemark": "",
        "userRemark": "",
        "warehouseCode": "",
        "warehouseName": ""
      };
      this.fileList = [];
      this.tableTotal = 0;
      this.tableTotal2 = 0;
      this.goodsText = '';
      this.resetForm("addForm");
      this.skuItems = [];

      this.open = true;
      this.title = "新增订单";
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    submitDataScope() {
      this.$refs.addForm.validate((valid,obj) => {
        if(valid){
          let status = true;
          for(let i=0;i<this.skuItems.length;i++){
            if(this.skuItems[i].sellQty==0){
              this.$message.error('商品数量不能为0');
              status = false;
              break;
            }
            if(this.skuItems[i].sellPrice==0&&this.skuItems[i].cost!=0){
              this.$message.error('采购成本价不为0，商品价格不能为0');
              status = false;
              break;
            }
          }
          if(!status){
            return false;
          }

          let data = {};
          data = Object.assign(data,this.orderForm);
          if(data.receiverAddress2.length==2){
            data.receiverCity = data.receiverAddress2[0]+'/'+this.presentText[0];
            data.receiverDistrict = data.receiverAddress2[1]+'/'+this.presentText[1];
          }
          if(data.receiverAddress2.length==3){
            data.receiverProvince = data.receiverAddress2[0]+'/'+this.presentText[0];
            data.receiverCity = data.receiverAddress2[1]+'/'+this.presentText[1];
            data.receiverDistrict = data.receiverAddress2[2]+'/'+this.presentText[2];
          }

          if(data.receiveInvoiceAddress2.length==2){
            data.receiveInvoiceCity = data.receiveInvoiceAddress2[0]+'/'+this.presentText2[0];
            data.receiveInvoiceDistrict = data.receiveInvoiceAddress2[1]+'/'+this.presentText2[1];
          }
          if(data.receiveInvoiceAddress2.length==3){
            data.receiveInvoiceProvince = data.receiveInvoiceAddress2[0]+'/'+this.presentText2[0];
            data.receiveInvoiceCity = data.receiveInvoiceAddress2[1]+'/'+this.presentText2[1];
            data.receiveInvoiceDistrict = data.receiveInvoiceAddress2[2]+'/'+this.presentText2[2];
          }

          let totalAmount = 0,profit=0;
          this.skuItems.forEach(item=>{
            totalAmount += parseFloat(item.sellPrice);
            profit += parseFloat(item.profit);
          })
          data.totalAmount = totalAmount;
          data.profit = profit;
          data.item = this.skuItems;

          this.submitLoading = true;
          if (this.title == "新增订单") {
            tradeOrdeCreate(data).then(res=>{
              if(res.status==200){
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
              this.submitLoading = false;
            }).catch(res=>{
              this.submitLoading = false;
            })
          } else {
            // console.log(this.orderForm)
            tradeOrdeUpdate(data).then((res) => {
              if(res.status==200){
                this.$modal.msgSuccess("编辑成功");
                this.open = false;
                this.getList();
              }
              this.submitLoading = false;
            }).catch(res=>{
              this.submitLoading = false;
            })
          }

        }else{
          this.$message.error(obj[Object.keys(obj)[0]][0].message);
        }
      })
    },
    saveGoods() {
      if(!this.orderForm.warehouseCode){
        this.$message.warning('请先选择仓库')
        return false;
      }
      this.saveGoodsLoading = true;
      const items = this.warehouseLists.find(item=>{
        return item.warehouseCode == this.orderForm.warehouseCode;
      })
      this.orderForm.warehouseName = items.warehouseName;
      getList({ sku: this.goodsText, warehouseCode:this.orderForm.warehouseCode,warehouseName:items.warehouseName })
        .then((res) => {
          if (res.rows.length != 0) {
            res.rows.forEach((item) => {
              this.minpPofit = (item.minpPofit*100).toFixed(0);
              let status = true;
              this.skuItems.forEach((it) => {
                if (it.skuNo == item.sku) {
                  status = false;
                }
              });
              if (status) {
                this.skuItems.push({
                  "skuNo": item.sku,
                  "skuName": item.skuName,
                  "sellPrice": 0,
                  "sellQty": 1,
                  "cost": item.costPrice,
                  "profit": 0,
                  "profitRate": 0,
                  "profitRate2": 0,
                  "inStock": item.inStock,
                  "marketPrice": item.marketPrice
                });
              }
            });
          }

          this.goodsVisible = false;
          this.saveGoodsLoading = false;
        })
        .catch((err) => {
          this.saveGoodsLoading = false;
        });
    },
    addressChange(value){
        this.presentText = this.$refs.address.getCheckedNodes()[0].pathLabels;
    },
    addressChange2(value){
        this.presentText2 = this.$refs.address2.getCheckedNodes()[0].pathLabels;
    },
    addressChange3(value){
        this.presentText3 = this.$refs.address3.getCheckedNodes()[0].pathLabels;
    },
    addressBlur(){
      if(!this.orderForm.receiverAddress){return false}
      lbsGeo({address:this.orderForm.receiverAddress}).then(res=>{
        if(res.status==200&&res.data.length>0){
          this.orderForm.receiverAddress2 = this.getCascaderFullValue(this.geoData, parseInt(res.data[0].adcode));
          this.$nextTick(()=>{
            this.presentText = this.$refs.address.getCheckedNodes()[0].pathLabels;
          })

        }
      })
    },
    addressBlur2(){
      if(!this.orderForm.receiveInvoiceAddress){return false}
      lbsGeo({address:this.orderForm.receiveInvoiceAddress}).then(res=>{
        if(res.status==200&&res.data.length>0){
          this.orderForm.receiveInvoiceAddress2 = this.getCascaderFullValue(this.geoData, parseInt(res.data[0].adcode));
          this.$nextTick(()=>{
            this.presentText2 = this.$refs.address2.getCheckedNodes()[0].pathLabels;
          })
        }
      })
    },
    addressBlur3(){
      if(!this.exForm.userAddress){return false}
      lbsGeo({address:this.exForm.userAddress}).then(res=>{
        if(res.status==200&&res.data.length>0){
          this.exForm.userAddress2 = this.getCascaderFullValue(this.geoData, parseInt(res.data[0].adcode));
          this.$nextTick(()=>{
            this.presentText3 = this.$refs.address3.getCheckedNodes()[0].pathLabels;
          })
        }
      })
    },
    getCascaderFullValue(cascader, id) {
      let cascaderFullValue = [id];
      _getParentId(cascaderFullValue, cascader,cascader, id);

      return cascaderFullValue;

      /**
       *
       * @param {Array} cascaderFullValue value for return
       * @param {Array} cascader value for loop
       * @param {Array} _cascader value of original
       * @param {number} _id  value of bottom item
       */
      function _getParentId(cascaderFullValue, cascader, _cascader, _id) {
        if (!Array.isArray(cascader)) return;

        for (let cascaderItem of cascader) {
          if (!Array.isArray(cascaderItem.districts)) continue;

          let index = cascaderItem.districts.findIndex(item => item.adcode == _id);

          if (index >= 0) {
            cascaderFullValue.unshift(cascaderItem.adcode);

            if(_cascader.findIndex(item => item.adcode == cascaderItem.adcode) < 0) //is original item
              _getParentId(cascaderFullValue, _cascader, _cascader,cascaderItem.adcode);
          } else {

            _getParentId(cascaderFullValue, cascaderItem.districts, _cascader,_id);
          }
        }
      }
    },
    handlePreview(file) {
      // console.log(file);
      if (file.response && file.response.data) {
        window.open(
          "https://newfirst.oss-cn-shanghai.aliyuncs.com/" + file.response.data
        );
      } else {
        window.open("https://newfirst.oss-cn-shanghai.aliyuncs.com/" + file.path);
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${ file.name }？`).then(res=>{
      // console.log(3)
      // });
      return true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleImportOrderFileUploadProgress(event, file, fileList) {
      this.importOrder.isUploading = true;
    },
    /** 下载模板操作 */
    importOrderTemplate() {
      // this.newDownload(
      //   "spu/importTemplate",
      //   {},
      //   `spu_template_${new Date().getTime()}.xlsx`
      // );
      window.location.href =
        "https://newfirst.oss-cn-shanghai.aliyuncs.com/template/%E5%AF%BC%E5%85%A5%E6%89%B9%E9%87%8F%E6%89%8B%E5%B7%A5%E5%88%B6%E5%8D%95%E6%A8%A1%E7%89%88.xlsx";
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.orderForm.proofPath = response.data;
      this.orderForm.proofName = fileList[0].name;
    },
    // 文件上传成功处理
    handleImportOrderFileSuccess(response, file, fileList) {
      this.importOrder.open = false;
      this.importOrder.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        {dangerouslyUseHTMLString: true}
      );
      this.getList();
    },
    // 文件上传成功处理
    handleFileSuccess2(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    handleRemove(){
      this.orderForm.proofPath = '';
      this.orderForm.proofName = '';
    },
    beforeAvatarUpload(file) {
      return new Promise((resolve, reject) => {
        const isLt1M = file.size / 1024 / 1024 > 20;
        if (isLt1M) {
          this.$message.error("上传文件大小不能超过 20MB!");
          reject();
        }

        resolve();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.pageNum;
      delete data.pageSize;
      //delete data.orderType;
      // delete data.orderStatus;
      newDownload2(
        "/outer/order/export",
        data,
        `订单列表_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */
    importTemplate() {
      // this.newDownload(
      //   "spu/importTemplate",
      //   {},
      //   `spu_template_${new Date().getTime()}.xlsx`
      // );
      window.location.href = 'https://m.xsbuy.cn/templates/批量修改用户地址模板.xlsx';
    },
    checkPhoneNum(rule, value, callback) {
      const reg = /^1[3456789]\d{9}$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error('手机号码格式不正确'));
      }
    },
    sortCol(value){
      value.forEach(item=>{
        if(item.fixc){
          item.fixed = 'left';
        }else{
          item.fixed = '';
        }
      })
      this.columns = value;
      this.randomKey = Math.random();
    },
    getTimeDifference(start, end) {
      if(start==null||end==null){
        return '0h'
      }
      const timeDiff = new Date(end).getTime() - new Date(start).getTime();
      let hours=0,minutes=0;
      if(timeDiff<0){
        // 计算差值的小时、分钟和秒数
        hours = 0;
        minutes = 0;
      }else{
        // 计算差值的小时、分钟和秒数
        hours = Math.floor(timeDiff / (1000 * 60 * 60));
        minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
      }
      return (hours+(minutes/60)).toFixed(1)+'h';
    },
    timeOver(start, end, over){
      if(start==null||end==null){
        return false;
      }
      if(!over){
        return false;
      }
      const timeDiff = new Date(end).getTime() - new Date(start).getTime();
      let hours=0,minutes=0;
      if(timeDiff<0){
        return false;
      }else{
        // 计算差值的小时、分钟和秒数
        hours = Math.floor(timeDiff / (1000 * 60 * 60));
        minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
        return (hours+(minutes/60))>=over?true:false;
      }

    }
  },
};
</script>
<style lang="scss" scoped>
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 50px;
}
.input-box{
  text-align: left;
}
.disabled-text{
  em{
    color: #999;
  }

}
h3{
  font-weight: bold;
  display: flex;
  align-items: center;
  margin-top: 36px;
  span{
    display: block;
    width: 2px;
    height: 14px;
    background: #F56C6C;
    margin-right: 6px;
  }
}
.sku-table{
  display: flex;
  justify-content: space-between;
  .total-table{
    display: flex;
    align-items: center;
    span{
      margin: 0 8px;
      white-space: nowrap;
      color: #F56C6C;
    }
  }
}
.goProcure{
  color: #1890ff;
  cursor: pointer;
  font-size: 12px;
}
.fixed-pagination{
  position: fixed;
}
.good-box{
  display: flex;
}
.table-overflow{
  width: 85%;
}
.table-overflow2{
  width: 100%;
}
.color-r {
    color: #F56C6C ;
  }
  .color-y{
    color: #fbc576;
  }
</style>
<style lang="scss">
  .warehouse-dialog {
    .el-upload{
      width: 100%;
    }
    .el-upload-dragger{
      width: 100%;
    }
  }
  .order-dialog{
    .el-tabs__content{
      height: 65vh;
      overflow-x: hidden;
      overflow-y: scroll;
      padding: 0 8px;
    }
    .el-dialog__body{
      padding:0 16px 16px 16px;
    }
    .el-form-item__label{
      font-size: 12px;
    }
    .el-radio__label{
      font-size: 12px;
    }
    .el-table .el-table__cell > .cell{
      font-size: 12px;
    }
  }
  .ho-box{
    color: #1989fa;
  }

  .good-box{
    span{
      color: #666;
    }
  }

  .el-dropdown-link{
    cursor: pointer;
    color: #409EFF;
    margin-left: 10px;
  }
  .link-ex{
    cursor: pointer;
    color: #409EFF !important;
  }
  .abdialog{
    .el-dialog__body{
      max-height: 70vh;
      overflow-y: scroll;
    }
  }

</style>
