<template>
  <div class="app-container">
    <el-card class="box-card box-cardone">
      <div style="position: relative;" class="clearfixall">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane name="first">
            <!--<div slot="label">待发货{{activeName == 'first' ? '（' + total1 + '）' : '（0）'}}</div>-->
            <div slot="label">待发货{{'（' + total1 + '）' }}</div>
          </el-tab-pane>
          <el-tab-pane name="second">
            <div slot="label">已发货{{'（' + total2 + '）' }}</div>
          </el-tab-pane>
          <el-tab-pane label="已完成" name="third"></el-tab-pane>
          <el-tab-pane label="全部订单" name="fourth" ></el-tab-pane>
        </el-tabs>
        <div v-show="activeName == 'first' " style="position: absolute; top: -2px; right: 0;">
          <el-tooltip v-if="channel_id == 0" class="item" effect="dark" content="查看2021年10月8日23:00之前的订单" placement="bottom-end">
            <el-button size="small" @click="gotoOldShop">查看老订单</el-button>
          </el-tooltip>
          <el-button size="mini" type="primary" icon="el-icon-position" @click="handleExportDeliveryOrder">批量发货</el-button>
        </div>
        <div v-show="activeName == 'fourth' " style="position: absolute; top: -2px; right: 0;">
          <el-tooltip v-if="channel_id == 0" class="item" effect="dark" content="查看2021年10月8日23:00之前的订单" placement="bottom-end">
            <el-button size="small" @click="gotoOldShop">查看老订单</el-button>
          </el-tooltip>
          <el-button size="mini" type="primary" icon="el-icon-download" @click="handleAllOrderExport">导出订单</el-button>
        </div>
        <div v-show="activeName == 'second' || activeName == 'third'" style="position: absolute; top: -2px; right: 0;">
          <el-tooltip v-if="channel_id == 0" class="item" effect="dark" content="查看2021年10月8日23:00之前的订单" placement="bottom-end">
            <el-button size="small" @click="gotoOldShop">查看老订单</el-button>
          </el-tooltip>
        </div>
      </div>
      <div class="form-box">
        <el-form class="form-params" ref="form" :model="form" label-width="120px" :inline="true" size="small">
          <el-form-item label="总订单号：">
            <el-input style="width:220px;" v-model="form.order_sn" placeholder="请输入总订单号"/>
          </el-form-item>

          <el-form-item label="商品名称：">
            <el-input v-model="form.goods_name" placeholder="请输入商品名称"/>
          </el-form-item>

          <el-form-item label="收货人：">
            <el-input v-model="form.real_name" placeholder="请输入收货人"/>
          </el-form-item>

          <el-form-item label="联系电话：">
            <el-input v-model="form.Tel" placeholder="请输入联系电话"/>
          </el-form-item>

          <el-form-item label="结算状态:" prop="settlement_status" v-show="activeName == 'fourth' ">
            <el-select v-model="form.settlement_status" placeholder="请选择结算状态" style="width:150px;">
              <el-option label="全部" value="-1"></el-option>
              <el-option label="已结算" value="1"></el-option>
              <el-option label="未结算" value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="是否售后：" prop="is_after_sale" v-show="activeName == 'fourth' ">
            <el-select v-model="form.is_after_sale" placeholder="请选择售后状态" style="width:150px;">
              <el-option label="全部" value="-1"></el-option>
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="下单时间：" v-show="activeName == 'first' || activeName == 'fourth' ">
            <el-date-picker
              style="width:280px;"
              v-model="form.dateTime"
              type="daterange"
              align="left"
              unaLink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="发货时间："  v-show="activeName == 'second' ">
            <el-date-picker
              v-model="form.sendTime"
              type="daterange"
              align="left"
              unaLink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="完成时间：" v-show="activeName == 'third' ">
            <el-date-picker
              v-model="form.finishTime"
              type="daterange"
              align="left"
              unaLink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button size="mini" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            <el-button size="mini" icon="el-icon-refresh" @click="resetBtn(true)">重置</el-button>
          </el-form-item>

        </el-form>
      </div>
      <!-- 表头 -->
      <div class="table-header-spe">
        <el-table class="title_table hxz-el-table" align="center">
<!--          <el-table-column align="center" width="55" v-if="activeName == 'fourth' ">-->
<!--            <template slot="header" slot-scope="scope">-->
<!--              <el-checkbox v-model="allTablesChecked" ></el-checkbox>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="订单号" align="center" width="220" ></el-table-column>-->
          <el-table-column label="商品名称" align="center"></el-table-column>
          <el-table-column label="规格/数量/金额" align="center" ></el-table-column>
          <el-table-column label="下单/发货/完成时间" align="center" width="180" ></el-table-column>
          <el-table-column label="运费" align="center" width="100" ></el-table-column>
          <el-table-column label="收货人" align="center" width="120" ></el-table-column>
          <el-table-column label="联系电话" align="center" width="120"></el-table-column>
          <el-table-column label="售后状态" align="center" width="180"></el-table-column>
          <el-table-column label="物流信息" align="center" width="120"></el-table-column>
          <el-table-column label="操作" align="center" width="120"></el-table-column>
        </el-table>
      </div>

      <div class="table-all-con box-card">
        <el-card v-for="(item, index) in tableDataList" :key="index" class="order-card">
          <div slot="header" class="el-card-header-spe">
            <div  style="float:left;">
              <span>订单状态：</span>
              <span>{{ orderStatusFormatter(item.order.status) }}</span>
              <span style="margin: 0 0 0 30px;">总订单号：</span>
              <span>{{ item.order.order_sn }}</span>
            </div>
            <div style="float:right;">
              <span>结算状态：</span>
              <span>{{ settlementFormat(item.order.settlement_status) }}</span>
            </div>
          </div>
          <div class="item-table">
            <el-table
              border
              :show-header="false"
              :span-method="arraySpanMethod"
              :data="item.order_goods">
<!--              <el-table-column type="selection" width="55" align="center" v-if="activeName == 'fourth' "></el-table-column>-->
<!--              <el-table-column prop="goods_order_sn" label="订单号" width="220" align="center"></el-table-column>-->
              <el-table-column prop="title" label="商品名称" align="center">
                <template slot-scope="scope">
                  <div class="img-title-table">
                    <img v-if="scope.row.thumb" style="width:60px;height:60px;" :src="scope.row.thumb"/>
                    <div class="ml10">{{ scope.row.title }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="规格/数量/金额" align="center">
                <template slot-scope="scope">
                  {{ scope.row.goods_option_title ? scope.row.goods_option_title : '--' }}<br/>
                  x {{ scope.row.total ? scope.row.total : '--' }}<br/>
                  {{ scope.row.goods_price / 100 ? scope.row.goods_price / 100 : '--' }} 元<br/>
                </template>
              </el-table-column>
              <el-table-column prop="created_time" label="下单时间" width="180" align="center">
                <template slot-scope="scope">
                  <span>{{ timeFormatter(scope.row.created_time) }}</span><br/>
                  <span :class="{ 'red-text' : sendTimeFormatter(scope.row.send_time) == '未发货' }">{{ sendTimeFormatter(scope.row.send_time) }}</span><br/>
                  <span :class="{ 'red-text' : updatedTimeFormatter(scope.row.updated_time) == '未完成' }">{{ updatedTimeFormatter(scope.row.updated_time, scope.row.goods_status) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="dispatch_price" width="100" label="运费" align="center">
                <template slot-scope="scope">
                  {{ item.order.dispatch_price / 100 }}
                </template>
              </el-table-column>
              <el-table-column prop="phone" width="120" label="收货人" align="center">
                <template slot-scope="scope">
                  {{ item.order.real_name }}
                </template>
              </el-table-column>
              <el-table-column prop="mobile" label="联系电话" width="120" align="center">
                <template slot-scope="scope">
                  {{ item.order.mobile }}
                </template>
              </el-table-column>
              <el-table-column prop="refund_status" label="售后状态" width="180" align="center" :formatter="refundStatusFormatter"></el-table-column>
              <el-table-column prop="物流信息" label="物流信息" width="120" align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleExpressInfo(scope.row)">查看物流</el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleInfo(scope.row)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>

      </div>
      <!-- 分页 -->
      <div class="footer_pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 40, 60, 80, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    <!-- 订单详情 对话框 -->
    <el-dialog title="订单详情" width="85%" :close-on-click-modal="false" :destroy-on-close="true"
               :visible.sync="detailDialog" center :before-close="handleClose">
      <div style="height:100%;">
        <order-detail :order-detail="order_detail" :order-goods-detail="order_goods_detail" :express-lists="expressLists" @updateOrder="updateOrder"/>
      </div>
    </el-dialog>
    <!--  批量发货  -->
    <el-dialog title="批量发货流程" :visible.sync="isDeliveryOpen" width="60%" center :before-close="cancelExport" :close-on-click-modal="false" :destroy-on-close="true">
      <el-steps :active="3" align-center style="width:95%;margin: 0 auto;">
        <el-step title="导出发货Excel表单" description="">
          <template slot="icon">
            <img style="width: 30px;" src="../../../assets/image/dev1.png">
          </template>
        </el-step>
        <el-step title="按模板填写快递信息" description="">
          <template slot="icon">
            <img style="width: 30px;" src="../../../assets/image/dev2.png">
          </template>
        </el-step>
        <el-step title="上传发货单模板并提交" description="">
          <template slot="icon">
            <img style="width: 30px;" src="../../../assets/image/dev3.png">
          </template>
        </el-step>
      </el-steps>
      <div class="delivery-data-con">
        <div>
          <el-button size="mini" type="primary" icon="el-icon-download" @click="handleExportUnSendOrder">导出订单</el-button>
        </div>
        <div>
          <el-upload
            action=""
            class="upload-demo"
            :auto-upload="false"
            :limit="1"
            accept="*/*"
            :on-change="importExcel"
            :on-remove="removeDevExcel"
            ref="upload"
          >
            <el-button size="small" type="primary">上传批量发货Excel表单</el-button>
          </el-upload>
        </div>
      </div>
      <div class="delivery-tips-con">
        <p style="text-align: center">常见问题</p>
        <p>1、批量发货流程</p>
        <p>【导出订单数据】按钮，获取待发货订单数据表</p>
        <p>打开导出的待发货订单数据表，填写【快递公司】和【快递单号】信息</p>
        <p>点击【上传批量发货Excel表单】按钮，选择填写完成的待发货订单数据表并上传，点击【确定】按钮即可完成批量发货</p>
        <p>2、注意事项</p>
        <p>请注意，必须正确填写【快递公司】名称和【快递单号】才会导入并发货成功</p>
        <p>表格的其它信息请勿做修改，否则会导致批量发货不成功</p>
        <p>常用快递公司名称（按此名称填写）</p>
        <p>【顺丰快递】【天天快递】【韵达快递】【圆通快递】【中通快递】【中国邮政】</p>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelExport">取 消</el-button>
        <el-button type="primary" @click="subDelivery">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看物流 -->
    <el-dialog  title="物流信息" width="50%" class="cutclass" :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="dialogExpress" append-to-body>
      <div class="logistics">
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in activities"
            :key="index"
            :icon="activity.icon"
            :type="activity.type"
            color="#0bbd87"
            :size="activity.size"
            :timestamp="activity.msg_time">
            {{activity.content}}
          </el-timeline-item>
        </el-timeline>
        <div v-if="activities.length == 0">暂无物流信息</div>
      </div>
    </el-dialog>
    <!-- 批量发货 展示失败数据-->
    <el-dialog title="批量发货提醒" center width="60%" class="delivery-fail-data-dialog" :visible.sync="dialogDeliveryInfor"
               :close-on-click-modal="false" append-to-body :before-close="closeDeliverFailDialog">
      <div class="delivery-fail-table-con">
        <p class="delivery-table-tip">部分订单发货失败，失败订单信息如下表所示</p>
        <el-table border :data="failDeliveryList">
          <el-table-column prop="goods_order_sn" label="商品订单号" align="center"></el-table-column>
          <el-table-column prop="order_sn" label="总订单号" align="center"></el-table-column>
          <el-table-column prop="goods_status" label="状态" align="center"></el-table-column>
          <el-table-column prop="reason" label="原因" align="center"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelDeliveryInfor">取 消</el-button>
        <el-button size="small" type="primary" @click="exportFailDeliveryExcel">导出失败订单</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import { indexInfo } from '@/api/webSite'
  import { listOrder, exportOrder, orderInfo, expressInfoNew, deliveryOrder, expressList, getOrderTabData ,
    exportUnSendOrderGoodsData,deliveryOrderExport } from '@/api/module/order'
  import {dateFormat} from '@/utils'
  import OrderDetail from './components/orderDetail.vue'
  import XLSX from "xlsx"
  import {isArray} from "../../../utils/validate";

  export default {
    components: {
      OrderDetail
    },
    data() {
      return {
        // channel_id
        channel_id: '',
        //
        sellerId: 0,
        currentPage: 1,
        pageSize: 20,
        total: 0,
        total1: '',//待发货
        total2: '',//已发货
        activeName: 'first',
        form: {
          order_sn: '',
          goods_name: '',
          real_name: '',
          Tel: '',
          settlement_status: '',
          dateTime: [],
          finishTime: [],
          sendTime: [],
          is_after_sale: ''
        },
        goodsStatus: 1,
        tableDataList: [],  // 后台返回所有数据
        detailDialog: false,
        isDeliveryOpen: false,
        excelList: [],
        order_detail: {
          remark: []
        }, // 订单信息
        order_goods_detail: [], // 订单商品信息
        expressLists: [],
        fullHeight:'',
        tableHeight: null,
        allTablesChecked: false,
        // 订单导出 入参
        exportParams: {},
        // 查看物流窗口
        dialogExpress: false,
        activities: [],
        // 批量发货 失败数据展示 窗口
        dialogDeliveryInfor: false,
        failDeliveryList: [], // 批量发货 失败table数据
      }
    },
    watch: {
      // fullHeight(val, oldval) {
      //   const contheight = document.getElementsByClassName('box-cardone')[0].clientHeight
      //   this.tableHeight = contheight - val - 250;
      //   // const heights = contheight
      //   // document.getElementsByClassName('cardHeight')[0].style.height = heights + 'px'
      // }
    },
    created() {
      // this.$nextTick(() => {
      //   this.fullHeight = document.getElementsByClassName('clearfixall')[0].clientHeight
      // })
    },
    mounted() {
      /** 获取 seller_id*/
      this.sellerId = this.$store.state.user.sellerid;
      /** 获取渠道id */
      this.getChannelId()
      // 订单列表 搜索
      this.getListOrder()
      //
      this.getExpressList()
    },
    methods: {
      /** 判断渠道 值=0才显示 查看历史数据 链接 */
      getChannelId() {
        let ssa = window.location.host
        const data = {
          domain: ssa,
        }
        indexInfo(data).then(res=> {
          if (res.code == 1) {
            this.channel_id = res.data.channel_id
          }
        });
      },

      /** 查看老订单 */
      gotoOldShop() {
        window.location.href = 'http://oldpop.jxhh.com/'
      },
      checkSelectable( row,index) {

      },
      /** 表格合并 列单元格 */
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex > 2 && columnIndex != 6 && columnIndex != 7) { // 用于设置要合并开始的列号
          if (rowIndex === 0) { // 用于设置合并开始的行号
            return {
              rowspan: 100,　　　　　// 合并的行数
              colspan: 1 // 合并的列数，设为０则直接不显示
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0
            }
          }
        }
      },
      formatter(time) {
        return dateFormat(time *1000, 'Y-m-d H:i:s')
      },
      /** 一般时间 格式化 */
      timeFormatter(time) {
        if(time) {
          return dateFormat(time *1000, 'Y-m-d H:i:s')
        } else {
          return '--'
        }
      },
      /** 发货时间 格式化 */
      sendTimeFormatter(time) {
        if(time) {
          return dateFormat(time *1000, 'Y-m-d H:i:s')
        } else {
          return '未发货'
        }
      },

      /** 发货时间 格式化 */
      updatedTimeFormatter(time, status) {
        if(time && status == 2) {
          return dateFormat(time *1000, 'Y-m-d H:i:s')
        } else {
          return '未完成'
        }
      },

      /** 订单状态 */
      orderStatusFormatter(status) {
        if(status === -1) {
          return '订单取消'
        }else if (status === 0) {
          return '待付款'
        }else if (status === 1) {
          return '待发货'
        }else if (status === 2) {
          return '待收货'
        }else if (status === 3) {
          return '已完成'
        }else if (status === 4) {
          return '已结算'
        }else {
          return '' // 保险，返回空
        }
      },
      /** 结算状态 */
      settlementFormat(status) {
        let res = '';
        if(status == 0) {
          res = '未结算'
        }else if (status == 1) {
          res = '已结算'
        } else {
          res = ''
        }
        return res
      },
      /** 售后状态 */
      refundStatusFormatter(row, column, cellValue, index) {
        let statusText = '--'
        if (cellValue == 1) {
          statusText = '申请仅退款'
        }else if (cellValue == 2) {
          statusText = '同意仅退款，退款完成'
        }else if (cellValue == 3) {
          statusText = '卖家拒绝退款，售后关闭'
        }else if (cellValue == 4) {
          statusText = '申请退货退款'
        }else if (cellValue == 5) {
          statusText = '同意退货退款，等待买家退货'
        }else if (cellValue == 6) {
          statusText = '拒绝退货退款，售后关闭'
        }else if (cellValue == 7) {
          statusText = '买家退货，等待卖家收货'
        }else if (cellValue == 8) {
          statusText = '同意退货退款，退款完成'
        }else if (cellValue == 9) {
          statusText = '拒绝收货，售后关闭'
        }else if (cellValue == 10) {
          statusText = '买家取消售后，售后关闭'
        }
        return statusText
      },
      // 重置
      resetBtn(iscall) {
        this.form = {
          order_sn: '',
          goods_name: '',
          real_name: '',
          Tel: '',
          dateTime: [],
          finishTime: [],
          sendTime: [],
          settlement_status: '',
          is_after_sale: ''
        }
        this.currentPage = 1
        this.pageSize = 20
        if (iscall) {
          this.getListOrder()
        }
      },
      // tab切换
      handleClick(tab, event) {
        this.total = 0

        switch (this.activeName) {
          case 'first':
            this.goodsStatus = 1
            break
          case 'second':
            this.goodsStatus = 2
            break
          case 'third':
            this.goodsStatus = 3
            break
          case 'fourth':
            this.goodsStatus = 0
            break
          // case 'oldVersion':
          //   window.open('http://oldpop.jxhh.com/')
          //   break
          default:
            break
        }

        this.resetBtn(false)
        this.getListOrder()
      },
      handleClose() {
        this.detailDialog = false
        this.getListOrder()
      },
      /** 获取 订单 状态对应数量 */
      getOrderTab() {
        getOrderTabData().then(res => {
          //console.log("获取订单状态和对应订单数量",res);
          if (res.code === 1 && res.data.length > 0) {
            // 1 表示 代发货；2 表示 已发货
            for (let i = 0; i < res.data.length; i++) {
              if (res.data[i].Status === 1) {
                this.total1 = res.data[i].Count > 999 ? '999+' : res.data[i].Count;
              } else if (res.data[i].Status === 2) {
                this.total2 = res.data[i].Count > 999 ? '999+' : res.data[i].Count;
              }
            }
          }
        });
      },
      // 搜索 操作
      search() {
        this.currentPage = 1;
        this.getListOrder();
      },
      // 获取订单列表
      getListOrder() {
        this.tableDataList = []
        let params = {
          page: this.currentPage,
          limit: this.pageSize,
          seller_id: this.sellerId,
          status: this.goodsStatus,
        }
        // if(this.$route.query.timeout==24){
        //   params.is_time_out=true
        // }
        if(this.form.order_sn != '') {
          params['order_sn'] = this.form.order_sn
        }
        if(this.form.goods_name != '') {
          params['goods_name'] = this.form.goods_name
        }
        if(this.form.real_name != '') {
          params['real_name'] = this.form.real_name
        }
        if(this.form.Tel != '') {
          params['mobile'] = this.form.Tel
        }
        if(this.form.is_after_sale == '0' || this.form.is_after_sale == '1') {
          params['is_after_sale'] = this.form.is_after_sale
        }

        if (this.form.settlement_status == '0' || this.form.settlement_status == '1') {
          params['settlement_status'] = this.form.settlement_status
        }

        if( this.form.dateTime && this.form.dateTime.length == 2) {
          params['created_start_time'] = new Date(this.form.dateTime[0]).getTime() / 1000;
          params['created_end_time'] = new Date(this.form.dateTime[1]).getTime() / 1000;
        }

        if(this.form.finishTime && this.form.finishTime.length == 2) {
          params['finish_start_time'] = new Date(this.form.finishTime[0]).getTime() / 1000;
          params['finish_end_time'] = new Date(this.form.finishTime[1]).getTime() / 1000;
        }

        if(this.form.sendTime && this.form.sendTime.length == 2) {
          params['send_start_time'] = new Date(this.form.sendTime[0]).getTime() / 1000;
          params['send_end_time'] = new Date(this.form.sendTime[1]).getTime() / 1000;
        }
        listOrder(params).then(res => {
          if (res.code == 1) {
            // 获取 订单 状态对应数量
            this.getOrderTab()
            // 每次订单 查询成功，保存查询参数，供商品导出接口使用（入参）
            this.exportParams = params;
            //console.log("初始赋值：",this.exportParams);
            this.total = res.data.count || 0
            this.tableDataList = res.data.data
          } else {
            this.$message({type: "error",message: res.message ? res.message : "查询订单失败"});
          }
        })
      },
      // row 当前行  column 当前列  rowIndex 当前行号， columnIndex 当前列号
      listSpanMethod({row, column, rowIndex, columnIndex}) {
        if (columnIndex === 1) {
          if (rowIndex % 2 === 0) {
            return {
              rowspan: 2,
              colspan: 1
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
      },
      /**
       * [待发货] 页签 导出订单 操作
       * 导出逻辑，根据 当前 搜索条件，导出所有订单
       * */
      handleExportUnSendOrder() {
        let params = this.exportParams;
        delete params.page;
        delete params.limit;
        delete params.seller_id;
        delete params.status;
        exportUnSendOrderGoodsData(params).then(res=> {
          if (res.code === 1) {
            const aLink = document.createElement('a');
            aLink.href = res.data.file_url;
            aLink.download = '待发货订单.xls'; //下载的文件名
            aLink.style.display = 'none';
            document.body.appendChild(aLink);
            aLink.click();
            document.body.removeChild(aLink);
            this.$message({type:'success',message: '导出成功，注意下载表格'});
          }else {
            this.$message({type:'error',message: res.message ? res.message: '导出失败'});
          }
        });
      },
      /**
       * [全部订单] 页签 订单导出
       * 导出逻辑，根据 当前 搜索条件，导出所有订单
       * */
      handleAllOrderExport() {
        let params = this.exportParams;
        delete params.page;
        delete params.limit;
        delete params.seller_id;
        delete params.status;
        delete params.settlement_status;

        //console.log("导出全部订单,入参：",params);
        exportOrder(params).then(res => {
          if (res.code === 1) {
            const aLink = document.createElement('a');
            aLink.href = res.data.file_url;
            //aLink.download = '订单.xls'; //下载的文件名
            aLink.style.display = 'none';
            document.body.appendChild(aLink);
            aLink.click();
            document.body.removeChild(aLink);
          }else {
            this.$message({type:'error',message: res.message ? res.message: '导出失败'});
          }
        });
      },
      // 上传批量发货Excel表单前
      importExcel(file, fileList) {
        this.excelList = [];
        let _this = this;
        _this.file2Xce(file).then(item => {
          if (item && item.length > 0) {
            // xlsxJson就是解析出来的json数据,数据格式如下
            // [{sheetName: sheet1, sheet: sheetData }]
            if (item[0] && item[0].sheet && item[0].sheet.length) {
              //_this.tableDataList = item[0].sheet  //把数据塞到表格预览
              // this.excelList = item[0].sheet
              item[0].sheet.map((item, index) => {
                this.excelList.push({
                  goods_order_sn: item['商品订单号'].toString().trim(),
                  express_name: item['快递公司'].toString().trim(),
                  express_sn: item['快递单号'].toString().trim()
                })
              })
            }
          }
        })
      },
      /**
       * 解析文件
       * @param {Object} file
       */
      file2Xce(file) {
        return new Promise(function (resolve, reject) {
          const reader = new FileReader();
          reader.onload = function (e) {
            const data = e.target.result;
            this.wb = XLSX.read(data, {
              type: "binary"
            });
            const result = [];
            this.wb.SheetNames.forEach(sheetName => {
              result.push({
                sheetName: sheetName,
                sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
              });
            });
            resolve(result);
          };
          reader.readAsBinaryString(file.raw);
        });
      },
      removeDevExcel(file, fileList) {
        this.excelList = [];
      },
      /** 批量发货 - 导入表格 */
      handleExportDeliveryOrder() {
        this.isDeliveryOpen = true;
        this.excelList = [];
      },
      /** 取消 批量上传发货 */
      cancelExport() {
        this.$refs.upload.clearFiles();
        this.isDeliveryOpen = false;
        this.excelList = [];
        //console.log(88,this.excelList);
      },
      /** 提交导入数据 */
      subDelivery() {
        this.failDeliveryList = [];

        if (this.excelList.length === 0) {
          this.$message({type: 'warning', message: '请先上传填写好的表格数据'});
          return
        }

        if (this.excelList.length > 0 && this.excelList[0].goods_order_sn && this.excelList[0].express_name && this.excelList[0].express_sn) {
          deliveryOrderExport(this.excelList).then(res => {
            if (res.code == 1) {
              if (res.data && res.data.fail_list && res.data.fail_list.length > 0) {
                this.failDeliveryList = res.data.fail_list;
                this.failDeliveryList.forEach((item)=> {
                  item['goods_status'] = '发货失败'
                })
                this.dialogDeliveryInfor = true;
                this.$message({type: 'warning', message: '部分订单发货成功，失败订单可以导出'});
              } else {
                this.isDeliveryOpen = false;
                this.excelList = [];
                this.$refs.upload.clearFiles();
                this.$message({type: 'success', message: '批量发货成功'});
              }
            } else {
              this.$message({type: 'error', message: res.message ? res.message : '批量发货失败'});
            }

            this.getListOrder();
          });
        } else {
          this.$message({type: 'error', message: '部分订单未填写物流公司或物流单号，请完善后再上传'});
        }
      },
      /** 导出 table数据 */
      exportFailDeliveryExcel(){
        let list = [];
        list = this.failDeliveryList;
        let exportList = [];
        this.failDeliveryList.forEach(item=> {
          let obj = {};
          obj['goods_order_sn'] = item.goods_order_sn
          obj['order_sn'] = item.order_sn
          obj['goods_status'] = item.goods_status
          obj['reason'] = item.reason
          exportList.push(obj);
        });
        // 列标题，逗号隔开，每一个逗号就是隔开一个单元格
        let title = `商品订单号,总订单号,发货状态,失败原因\n`;
        //增加\t为了不让表格显示科学计数法或者其他格式
        for(let i = 0 ; i < exportList.length ; i++ ){
          for(let item in exportList[i]){
            title += `${exportList[i][item] + '\t'},`;
          }
          title += '\n';
        }
        //encodeURIComponent解决中文乱码
        let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(title);
        //通过创建a标签实现
        var link = document.createElement("a");
        link.href = uri;
        //对下载的文件命名
        link.download =  "发货失败订单汇总表.csv";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } ,
      /** 关闭 发货失败 数据展示 */
      cancelDeliveryInfor() {
        this.isDeliveryOpen = false;
        this.dialogDeliveryInfor = false;
      },
      /** 关闭 发货失败窗口 前 */
      closeDeliverFailDialog() {
        this.cancelDeliveryInfor();
        this.failDeliveryList = [];
      },
      /** 导出 发货失败的数据 */
      exportFailDeliverList() {
        this.failDeliveryList = [];
      },
      /** 查看物流信息 */
      handleExpressInfo(row) {
        // 如果 商品订单没有发货，则不用请求了
        if(row.goods_status == 0) {
          this.$message({type:'warning',message:'您还未发货，暂无物流信息'});
          return
        }

        let params = {
          goods_order_sn: row.goods_order_sn,
          sku_id: row.goods_option_id
        }
        expressInfoNew(params).then(res => {
          if (res.code == 1 && res.data) {
            this.dialogExpress = true
            this.activities = res.data.order_track ? res.data.order_track : [];
          }else {
            this.$message({type:'error',message: res.message ? res.message : '获取数据失败' });
          }
        })
      },
      // 订单详情
      handleInfo(row) {
        let order_id = row.order_id
        orderInfo({order_id: order_id}).then(res => {
          if (res.code == 1 && res.data) {
            this.detailDialog = true
            // 留言备注，需要单独处理
            let remarkList = []
            // res.data.order.remark 返回数据格式比较多，不判断了
            try {
              remarkList = JSON.parse(res.data.order.seller_remark)
            } catch (e) {
              remarkList = []
            }

            res.data.order.remark = remarkList
            this.order_detail = res.data.order;

            // 商品订单数据 array
            this.order_goods_detail = res.data.order_goods_detail ? res.data.order_goods_detail : [];

            // 能否修改买家信息 字段动态添加
            // 1,商品订单，只要要发货的，就不能再修改，2，修改过一次的，不能再修改
            let isEditBuyerInfo = false;
            if(this.order_detail.is_update_address == 1) {
              isEditBuyerInfo = true
            }else {
              if(this.order_goods_detail.length > 0) {
                for(let i = 0; i < this.order_goods_detail.length; i++) {
                  if(this.order_goods_detail[i].goods_status > 0) {
                    isEditBuyerInfo = true
                    break;
                  }
                }
              }
            }

            this.order_detail['isEditBuyerInfo'] = isEditBuyerInfo;

            //console.log('备注留言返回原始数据',res.data.order.remark);
            // this.$router.push({path: '/system/goods/management'});
          } else if(res.code == 0) {
            let msg = res.message ? res.message : '暂无数据'
            this.$message({type: 'error',message: msg});
          }
        })
      },
      /** 更新 订单备注 */
      updateOrder(id) {
        let row = {order_id: id}
        this.handleInfo(row);
      },
      // 获取物流信息
      getExpressList() {
        expressList().then(res => {
          if (res.code == 1) {
            this.expressLists = res.data.expressLists
          }
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.getListOrder()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.getListOrder()
      },
      /** 时间格式处理 */
      // dateTimeChange(val) {
      //   if( !Array.isArray(val) ) {
      //     this.form.dateTime = [];
      //   }
      //
      // },
    },
  };
</script>

<style scoped>
  /deep/ .el-range-editor.el-input__inner {
    width: 100%;
  }

  /deep/ .el-card__body {
    height: calc(100% - 50px);
  }

  .scollbox {
    height: calc(100% - 50px);
    overflow-y: hidden;
  }

  .form-box {
    /*margin-bottom: 20px;*/
    /*padding-top: 10px;*/
  }

  .form-params {
    /*background-color: #F7F8FA;*/
  }

  /deep/.form-params .el-form-item {
    margin: 5px 0 5px 0;
  }
  .img-title-table {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .footer_pagination {
    text-align: center;
    margin-top: 15px;
  }

  .delivery-data-con {
    width: 80%;
    margin: 10px auto;
    font-weight: bold;
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-direction: row;
  }

  .delivery-tips-con {
    width: 80%;
    margin: 60px auto 0;
    font-weight: bold;
  }

  /*.delivery-data-con {*/
  /*  height: 100px;*/
  /*  margin: 20px auto;*/
  /*}*/

  .upload-demo {
    text-align: center;
  }

  /* 订单卡片 样式 */
  .order-card {
    margin: 10px 0 12px;
  }
  .order-card /deep/ .el-card__header {
    padding: 0;
    min-height: fit-content;
  }

  .el-card-header-spe {
    overflow: hidden; /* 此为父元素，子元素都浮动了，所以，这样处理，撑开自己的高度 */
    font-size: 14px;
    padding: 10px 12px;
    background-color: #f0f0f5;
    /*background-color: #909399;*/
  }

  .table-header-spe {
    background-color: #F7F8FA;
    padding:0 34px 0 22px;
    margin: 5px 0;
  }

  /deep/ .title_table{
    /*width: calc(100% - 94px) !important;*/
    /*margin: 0 40px;*/
  }
  /deep/ .title_table .el-table__body-wrapper{
    display: none !important;
    height:0 !important;
  }
  /deep/ .title_table tr th {
    border-bottom: 0 !important;
  }
  /deep/  .title_table::before{
    height:0;
  }

  .table-all-con {
    height: calc(100% - 190px);
    overflow: auto;
  }

  .el-card-header-spe {
    overflow: hidden;
  }

  .ml10 {
    margin-left: 10px;
  }

  .red-text {
    font-size: 12px;
    color: red!important;
  }
  /* 批量发货 对话框 */
  .delivery-fail-data-dialog {
    height: 100%;
    overflow: hidden;
  }

  .delivery-fail-data-dialog /deep/ .el-dialog {
    height: 80%;
    overflow: hidden;
  }

  .delivery-fail-data-dialog /deep/ .el-dialog .el-dialog__body {
    height: calc(100% - 120px);
    overflow: auto;
    padding: 15px 20px;
  }

  .delivery-table-tip {
    padding: 0;
    margin: 0 0 15px;
    text-align: center;
  }
</style>
