<template>
  <div class="app-container">
    <el-card class="box-card">
      <div style="position: relative;">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane name="first">
            <div slot="label">待发货{{activeName == 'first' ? '（' + total1 + '）' : ''}}</div>
          </el-tab-pane>
          <el-tab-pane name="second">
            <div slot="label">已发货{{activeName == 'second' ? '（' + 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 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="scollbox">
      <div class="form-box">
        <el-form 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"
                  unlink-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>
      <el-table :data="tableData" max-height="1080">
        <el-table-column type="selection" width="55" />
        <el-table-column label="订单号" align="center" prop="order_sn" width="255"/>
        <el-table-column label="下单时间" align="center" prop="Updatetime"  width="155">
          <template slot-scope="scope">
            {{formatter(scope.row.Updatetime)}}
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="goods_total"/>
        <el-table-column label="订单金额" align="center" prop="goods_price">
          <template slot-scope="scope">
            {{scope.row.goods_price/100}}
          </template>
        </el-table-column>
        <el-table-column label="收货人" align="center" prop="real_name"/>
        <el-table-column label="联系电话" align="center" prop="mobile"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleInfo(scope.row)"
            >
            详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      </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" :express-lists="expressLists"/>
      </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} from '@/api/module/order'
  import {dateFormat} from '@/utils'
  import OrderDetail from './components/orderDetail.vue'
  import XLSX from "xlsx"
  export default {
    components: {
      OrderDetail
    },
    data() {
      return {
        currentPage: 1,
        pageSize: 20,
        total: 0,
        total1:'',//待发货
        total2:'',//已发货
        activeName: 'first',
        form: {
          order_sn: '',
          GoodsName: '',
          shipname: '',
          Tel: '',
          dateTime: [],
        },
        goodsStatus: 1,
        tableData: [],
        detailDialog: false,
        isDeliveryOpen: false,
        excelList: [],
        order_detail: null,
        expressLists: []
      }
    },
    mounted() {
      this.getListOrder()
      this.getExpressList()
    },
    methods: {
      formatter(time) {
        return dateFormat(time, 'Y-m-d H:i:s')
      },
      // 重置
      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()
      },
      // 获取订单列表
      getListOrder() {
        this.tableData = []
          
        let params = {
          page: this.currentPage,
          limit: this.pageSize,
          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.total = res.data.count || 0
            if( this.goodsStatus == 1){
              this.total1 = res.data.count || 0
            }
             if( this.goodsStatus == 2){
              this.total2 = res.data.count || 0
            }
            this.tableData = res.data.data
          }
        })
      },
      // 订单导出
      handleExport(row) {
        let query = {page: 1, limit: 100}
        exportOrder(query).then(res => {
          if(res.code === 1) {
            const link = document.createElement('a');
            link.href = res.data;
            //link.download = '订单.xls'; //下载的文件名
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        });
      },
      // 上传批量发货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.tableData = 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_sn = '20200318e095e2d09354'
        let order_sn = row.parent_order_sn

        orderInfo({order_sn: order_sn}).then(res => {
          if (res.code == 1) {
            this.order_detail = res.data
          }
        })
      },
      // 获取物流信息
      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: scroll;
}
.form-box {
  background-color: #F7F8FA;
  margin-bottom: 20px;
  padding-top: 22px;
}
.footer_pagination {
  text-align: right;
  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;
}
</style>