<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="this.activeName == 'first' " style="position: absolute; top: -5px; right: 0;">
          <el-button size="mini" type="primary" icon="el-icon-download" @click="handleExport">导出订单</el-button>
          <el-button size="mini" icon="el-icon-position" @click="isDeliveryOpen = true">批量发货</el-button>
        </div>
      </div>
      <div class="form-box">
        <el-form class="form-params" ref="form" :model="form" label-width="85px">
          <el-row type="flex" class="row-bg" justify="space-around">
            <el-col :span="6">
              <el-form-item label="订单号：">
                <el-input size="mini" v-model="form.order_sn" placeholder="请输入订单号"/>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="商品名称：">
                <el-input size="mini" v-model="form.GoodsName" placeholder="请输入商品名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收货人：">
                <el-input size="mini" v-model="form.shipname" placeholder="请输入收货人"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" class="row-bg" justify="space-around">
            <el-col :span="6">
              <el-form-item label="联系电话：">
                <el-input size="mini" v-model="form.Tel" placeholder="请输入联系电话"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="下单时间：">
                <el-date-picker
                  size="mini"
                  v-model="form.dateTime"
                  type="daterange"
                  align="left"
                  unaLink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button size="mini" type="primary" icon="el-icon-search" style="margin-left: 20px;"
                         @click="getListOrder">搜索
              </el-button>
              <el-button size="mini" icon="el-icon-refresh" @click="resetBtn(true)">重置</el-button>
            </el-col>
          </el-row>
        </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">
            <template slot="header" slot-scope="scope">
              <el-checkbox v-model="allTablesChecked" ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="订单号" align="center" width="180" ></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="180" ></el-table-column>
          <el-table-column label="收货人" align="center" width="180" ></el-table-column>
          <el-table-column label="联系电话" align="center" width="180"></el-table-column>
          <el-table-column label="操作" align="center" width="140" ></el-table-column>
        </el-table>
        <div class="hxz-el-table-check"></div>
      </div>

      <div class="table-all-con box-card">
        <el-card v-for="(item, index) in tableDataList" :key="index" class="card1 text item">
          <div slot="header" class="el-card-header-spe">
            <div><span>订单状态：</span><span>{{ orderStatusFormatter(item.order.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"></el-table-column>
              <el-table-column prop="goods_order_sn" label="订单号" width="180" align="center"></el-table-column>
              <el-table-column prop="goods_option_title" label="商品名称" align="center">
                <template slot-scope="scope">
                  <img style="width:60px;height:60px;" :src="scope.row.thumb"/>
                  <div>{{ scope.row.goods_option_title }}</div>
                </template>
              </el-table-column>
              <el-table-column label="规格/数量/金额" width="180" align="center">
                <template slot-scope="scope">
                  {{ scope.row.goods_option_title }}<br/>
                  {{ scope.row.total }}<br/>
                  {{ 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">
                  {{ formatter(scope.row.created_time) }}
                </template>
              </el-table-column>
              <el-table-column prop="phone" width="180" label="收货人" align="center"></el-table-column>
              <el-table-column prop="real_name" label="联系电话" width="180" align="center"></el-table-column>
              <el-table-column label="操作" width="140" align="center">
                <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>
      <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">
        <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 class="delivery-tips-con">
        <p style="text-align: center">常见问题</p>
        <p>1、批量发货规则</p>
        <p>必须正确填写了“快递公司 快递单号”才会导入并更改订单状态为已发货!</p>
        <p>2、如何获取一个批量发货的excel文件？</p>
        <p>在商户后台左侧菜单的 “订单中心” 》“订单列表”里面可以将订单导出为Excel格式的文件，您可以在这里自由导出订单</p>
        <p>3、导出excel文件后，批量发货需要输入什么信息？</p>
        <p>在我们的导出的excel文件中，打开里面有“快递单号 快递公司”。 您可以在将正确的快递发货单号，快递公司填入对应的列里面，和对应的订单号一对应。然后保存提交，就可以用于批量发货了</p>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isDeliveryOpen = false">取 消</el-button>
        <el-button type="primary" @click="subDelivery">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {listOrder, exportOrder, orderInfo, deliveryOrder, expressList, getOrderTabData} 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 {
        sellerId: 0,
        currentPage: 1,
        pageSize: 20,
        total: 0,
        total1: '',//待发货
        total2: '',//已发货
        activeName: 'first',
        form: {
          order_sn: '',
          GoodsName: '',
          shipname: '',
          Tel: '',
          dateTime: [],
        },
        goodsStatus: 1,
        tableDataList: [],  // 后台返回所有数据
        detailDialog: false,
        isDeliveryOpen: false,
        excelList: [],
        order_detail: {
          remark: []
        }, // 订单信息
        order_goods_detail: [], // 订单商品信息
        expressLists: [],
        fullHeight:'',
        tableHeight: null,
        allTablesChecked: false,
        // 订单导出 入参
        exportParams: {
          order_sn: '',
          goods_name: '',
          real_name: '',
          tel: 0,
          created_start_time: 0,
          created_end_time: 0,
        }
      }
    },
    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;
      // 获取 订单 状态对应数量
      //this.getOrderTab()
      // 订单列表 搜索
      this.getListOrder()
      //
      this.getExpressList()
    },
    methods: {
      checkSelectable( row,index) {

      },
      // 表格合并 列单元格
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex > 5) { // 用于设置要合并开始的列号
          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')
      },
      /** 订单状态 */
      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 '' // 保险，返回空
        }
      },
      // 重置
      resetBtn(iscall) {
        this.form = {
          order_sn: '',
          GoodsName: '',
          shipname: '',
          Tel: '',
          dateTime: [],
        }
        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 = -2
            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;
        //       }
        //     }
        //   }
        // });
      },
      // 获取订单列表
      getListOrder() {
        this.tableDataList = []
        let params = {
          page: this.currentPage,
          limit: this.pageSize,
          seller_id: this.sellerId,
          status: this.goodsStatus,
          start_time: new Date(this.form.dateTime[0]).getTime() / 1000 || '',
          end_time: new Date(this.form.dateTime[1]).getTime() / 1000 || '',
          order_sn: this.form.order_sn,
          goods_name: this.form.GoodsName,
          real_name: this.form.shipname,
          mobile: this.form.Tel,
        }
        listOrder(params).then(res => {
          if (res.code == 1) {
            // 每次订单 查询成功，保存查询参数，供商品导出接口使用（入参）
            this.exportParams.order_sn = params.order_sn;
            this.exportParams.goods_name = params.goods_name;
            this.exportParams.real_name = params.real_name;
            this.exportParams.tel = params.tel;
            this.exportParams.created_start_time = params.created_start_time;
            this.exportParams.created_end_time = params.created_end_time;

            this.total = res.data.count || 0
            this.tableDataList = res.data.data

            if(this.goodsStatus == 1) {
              this.taotal1 = res.data.count;
            }else if(this.goodsStatus == 2) {
              this.taotal2 = res.data.count;
            }

          }
        })
      },
      // 合并数据
      // listSpanMethod() {
      //
      // },
      // 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
            };
          }
        }
      },
      // 订单导出
      handleExport() {
        exportOrder(this.exportParams).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({
                  id: item['编号ID'],
                  express_name: item['物流公司'],
                  express_sn: item['物流单号']
                })
              })
            }
          }
        })
      },
      /**
       * 解析文件
       * @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 = [];
      },
      // 提交导入数据
      subDelivery() {
        if (this.excelList.length === 0) {
          this.$message({type: 'warning', message: '请先上传填写好的表格数据'});
          return
        }
        if (this.excelList.length > 0 && this.excelList[0].id && this.excelList[0].express_name && this.excelList[0].express_sn) {
          deliveryOrder(this.excelList).then(res => {
            if (res.code === 1) {
              this.isDeliveryOpen = false;
              this.$message({type: 'success', message: '批量发货成功'});
              this.getList();
            } else {
              let msg = res.message || '批量发货失败'
              this.$message({type: 'error', message: msg});
            }
          });
        } else {
          this.$message({type: 'error', message: '导入表格数据有误'});
        }
      },
      // 订单详情
      handleInfo(row) {
        this.detailDialog = true
        let order_id = row.order_id
        orderInfo({order_id: order_id}).then(res => {
          if (res.code == 1 && res.data) {
            // 留言备注，需要单独处理
            let remarkList = []
            // res.data.order.remark 返回数据格式比较多，不判断了
            try {
              remarkList = JSON.parse(res.data.order.remark)
            } catch (e) {
              remarkList = []
              console.log(99,e);
            }

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

            // let isArray = Array.isArray(remarkList)
            //
            // if(isArray) {
            //   res.data.order.remark = remarkList
            //   this.order_detail = res.data.order;
            // }else {
            //
            // }

            this.order_goods_detail = res.data.order_goods_detail ? res.data.order_goods_detail : [];

            //console.log('备注留言返回原始数据',res.data.order.remark);
            // this.$router.push({path: '/system/goods/management'});
          }
        })
      },
      /** 更新 订单备注 */
      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()
      }
    }
  };
</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 {
    background-color: #F7F8FA;
    /*margin-bottom: 20px;*/
    padding-top: 20px;
  }

  .form-params {

  }

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

  .delivery-tips-con, .delivery-data-con {
    width: 80%;
    margin: 5px auto;
    font-weight: bold;
  }

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

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

  /* 订单卡片 样式 */
  .card1 {
    margin-bottom: 20px;
  }

  .table-header-spe {
    background-color: #F7F8FA;
    margin:10px 0 10px;
  }

  /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% - 250px);
    overflow-y: auto;
    padding: 0 20px;
  }
</style>
