<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: -5px; right: 0;">
          <el-button size="mini" type="primary" icon="el-icon-download" @click="handleExportUnSendOrder">导出订单</el-button>
          <el-button size="mini" icon="el-icon-position" @click="handleExportDeliveryOrder">批量发货</el-button>
        </div>
        <div v-show="activeName == 'fourth' " style="position: absolute; top: -5px; right: 0;">
          <el-button size="mini" type="primary" icon="el-icon-download" @click="handleAllOrderExport">导出订单</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.goods_name" placeholder="请输入商品名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收货人：">
                <el-input size="mini" v-model="form.real_name" 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" v-show="activeName == 'first' || activeName == 'fourth' ">
              <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" v-show="activeName == 'second' ">
              <el-form-item label="发货时间：">
                <el-date-picker
                  size="mini"
                  v-model="form.sendTime"
                  type="daterange"
                  align="left"
                  unaLink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-show="activeName == 'third' ">
              <el-form-item label="完成时间：">
                <el-date-picker
                  size="mini"
                  v-model="form.finishTime"
                  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" 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="180" ></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>
      </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><span style="margin: 0 0 0 30px;">总订单号：</span><span>{{ item.order.order_sn }}</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 }}<br/>
                  {{ scope.row.goods_price / 100 }} 元<br/>
                  x {{ scope.row.total }}<br/>
                </template>
              </el-table-column>
              <el-table-column prop="created_time" label="下单时间" width="180" align="center">
                <template slot-scope="scope">
                  {{ speTiemFormatter(scope.row.created_time) }}<br/>
                  {{ speTiemFormatter(scope.row.send_time) }}<br/>
                  {{ speTiemFormatter(scope.row.updated_time) }}
                </template>
              </el-table-column>
              <el-table-column prop="phone" width="180" label="收货人" align="center">
                <template slot-scope="scope">
                  {{ item.order.real_name }}
                </template>
              </el-table-column>
              <el-table-column prop="mobile" label="联系电话" width="180" align="center">
                <template slot-scope="scope">
                  {{ item.order.mobile }}
                </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">
      <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="cancelExport">取 消</el-button>
        <el-button type="primary" @click="subDelivery">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {listOrder, exportOrder, orderInfo, 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 {
        sellerId: 0,
        currentPage: 1,
        pageSize: 20,
        total: 0,
        total1: '',//待发货
        total2: '',//已发货
        activeName: 'first',
        form: {
          order_sn: '',
          goods_name: '',
          real_name: '',
          Tel: '',
          dateTime: [],
          finishTime: [],
          sendTime: [],
        },
        goodsStatus: 1,
        tableDataList: [],  // 后台返回所有数据
        detailDialog: false,
        isDeliveryOpen: false,
        excelList: [],
        order_detail: {
          remark: []
        }, // 订单信息
        order_goods_detail: [], // 订单商品信息
        expressLists: [],
        fullHeight:'',
        tableHeight: null,
        allTablesChecked: false,
        // 订单导出 入参
        exportParams: {}
      }
    },
    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.getListOrder()
      //
      this.getExpressList()
    },
    methods: {
      checkSelectable( row,index) {

      },
      // 表格合并 列单元格
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex > 3) { // 用于设置要合并开始的列号
          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')
      },
      speTiemFormatter(time) {
        if (time) {
          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 '' // 保险，返回空
        }
      },
      // 重置
      resetBtn(iscall) {
        this.form = {
          order_sn: '',
          goods_name: '',
          real_name: '',
          Tel: '',
          dateTime: [],
          finishTime: [],
          sendTime: [],
        }
        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
          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,
        }

        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.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
          }
        })
      },
      // 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;
        //console.log("导出待发货订单,入参：",params);

        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);
          }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;

        //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({
                  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 = [];
      },
      /** 批量发货 - 导入表格 */
      handleExportDeliveryOrder() {
        this.isDeliveryOpen = true;
        this.excelList = [];
      },
      /** 取消 批量上传发货 */
      cancelExport() {
        this.$refs.upload.clearFiles();
        this.isDeliveryOpen = false;
        this.excelList = [];
        //console.log(88,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) {
          deliveryOrderExport(this.excelList).then(res => {
            if (res.code === 1) {
              this.isDeliveryOpen = false;
              this.excelList = [];
              this.$message({type: 'success', message: '批量发货成功'});
              this.getListOrder();
            } else {
              let msg = res.message || '批量发货失败'
              this.$message({type: 'error', message: msg});
            }
          });
        } else {
          this.$message({type: 'error', 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 {
    background-color: #F7F8FA;
    /*margin-bottom: 20px;*/
    padding-top: 20px;
  }

  .form-params {

  }
  .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;
  }

  .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;
  }

  /* 订单卡片 样式 */
  .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: auto;
  }

  .ml10 {
    margin-left: 10px;
  }
</style>
