<template>
  <div id="order-check">
    <div class="order-check-body" v-loading.fullscreen.lock="fullscreenLoading">
      <div class="order-management-body">
        <div class="order-management-inner">
          <span>下单时间：</span>
          <el-date-picker size="large" v-model="searchDate" type="daterange" unlink-panels range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions2" value-format="yyyy-MM-dd" align="center">
          </el-date-picker>
          <!-- <span>支付平台交易号：</span>
            <el-input @keyup.enter.native="_searchOrderData(1)" ref="searchTradeNum" v-model="searchTradeNum" value="" placeholder="交易号"></el-input> -->
          <div class="base-info">
            <span>订单号：</span>
            <el-input @keyup.enter.native="_searchOrderData(1)" ref="searchOrderNumber" v-model="searchOrderNumber" value="" placeholder="订单号"></el-input>
            <span>手机号：</span>
            <el-input @keyup.enter.native="_searchOrderData(1)" ref="searchPhone" v-model="searchPhone" value="" placeholder="手机号"></el-input>
            <span>支付平台交易号：</span>
            <el-input @keyup.enter.native="_searchOrderData(1)" ref="searchTradeNum" v-model="searchTradeNum" value="" placeholder="支付平台交易号："></el-input>
            <el-button type="primary" @click="_searchOrderData(1)" color='red'>筛选</el-button>
          </div>
        </div>
        <div class="order-check_bottom">
          <div class="order-management-table">
            <div class="order-check_tab">
              <ul>
                <!-- <li v-for="(item,index) in tabs" :key="index" :class="{'order-check_tab_li_active':item.idx==tabIndex}" @click="clickTabItem(item.idx)">{{item.name}}<span v-if="item.idx != 3" style="margin:0 10px;color: #999;font-weight: normal;">/</span></li> -->
              </ul>
              <div style="float: right;vertical-align: middle;">
                <!-- <el-select v-model="selectValue" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select> -->
                <el-button type="primary" @click="_exportExcelForOrder" color='red'>导出</el-button>
              </div>
            </div>
            <el-table ref="order_table" @expand-change="_getOrderDetail" class='e-table' :data="orders" style="width: 100%">
              <el-table-column label="下单时间">
                <template slot-scope="scope">
                  <div>{{new Date(scope.row.orderTime).format('yyyy-MM-dd hh:mm:ss')}}</div>
                </template>
              </el-table-column>
              <el-table-column prop="orderSn" label="订单号">
              </el-table-column>
              <el-table-column prop="userName" label="手机号/用户名">
              </el-table-column>
              <el-table-column v-if="routeName == '下载订单'" prop="snCode" label="相机SN">
              </el-table-column>
              <el-table-column v-if="routeName == '下载订单'" prop="sceneName" label="场景下载">
                <template slot-scope="scope">
                  <div>{{scope.row.sceneName}}({{scope.row.sceneNum}})</div>
                </template>
              </el-table-column>
              <el-table-column v-if="routeName == '权益订单'" prop="goodsNum" label="数量">
              </el-table-column>
              <el-table-column prop="totalAmount" label="订单金额(元)">
              </el-table-column>
              <el-table-column prop="paymentTypeName" label="支付方式">
                <template slot-scope="scope">
                  <div>{{payMap[scope.row.paymentTypeName]}}</div>
                </template>
              </el-table-column>
              <el-table-column prop="tradeNum" label="支付平台交易号">
              </el-table-column>
              <el-table-column prop="orderStatus" label="订单状态">
                <template slot-scope="scope">
                  <div>{{paymentStatusMap[scope.row.paymentStatus]}}</div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="order-management-pagination">
            <el-pagination  @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="10" layout="total, prev, pager, next, jumper" :total="total">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

export default {

  name: 'order-check',

  data () {
    return {
      routeName:'',
      payMap: {
        '0': '微信',
        '1': '支付宝',
        '2': 'paypal',
        '3': '其他',
        '4': '货到付款'
      },
      paymentStatusMap: {
        unpaid: '未付款',
        paid: '已付款',
        cancel: '已取消',
        partPayment: '部分支付',
        partRefund: '部分退款',
        refunded: '全额退款'
      },
      tabs: [{ name: '全部', idx: -1 }, { name: '未支付', idx: 0 }, { name: '待发货', idx: 1 }, { name: '已发货', idx: 2 }, { name: '已完成', idx: 3 }],
      expandedArr: [],
      orders: [],
      currentPage: 1,
      key_input: '',
      fullscreenLoading: false,
      product: {
        'name': '',
        'packageName': '',
        'count': '',
        'amount': '',
        'url': ''
      },
      receive: {
        'name': '',
        'phone': '',
        'address': '',
        'invoice': '',
        'expressNum': ''
      },
      total: 0,
      options: [{
        value: undefined,
        label: '全部筛选订单'
      }, {
        value: 0,
        label: '未支付筛选订单'
      }, {
        value: 1,
        label: '待发货筛选订单'
      }, {
        value: 2,
        label: '已发货筛选订单'
      }, {
        value: 3,
        label: '已完成筛选订单'
      }],
      selectValue: '',
      // expressNum_input: "",
      searchDate: [],
      searchOrderNumber: '',
      searchTradeNum:'',
      searchPhone: '',
      searchExpressNum: '',
      hasClickSearch: false,
      tabIndex: -1,
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  watch: {
    '$route' (to, from) {
    this.routeName = this.$route.meta.text
    //to.path即为将要进入的路由
    this.selectValue = ''
    this.searchDate = []
    this.searchOrderNumber = ''
    this.searchTradeNum = ''
    this.searchPhone = ''
    this.searchExpressNum = ''
    this.currentPage = 1
    this._searchOrderData(1)
    }
  },
  methods: {
    handleClick (row) {
      console.log(this.status)

      console.log(this.selectValue)
    },
    hideRow (row) {
      this.$refs.order_table.toggleRowExpansion(row, false)
    },
    handleCurrentChange (val) {
      let page = val
      if (this.total > 0 && !this.hasClickSearch) {
        this._searchOrderData(page)
      } else {
        this._searchOrderData(page)
      }
    },
    clickTabItem (idx) {
      this.tabIndex = idx
      this.hasClickSearch = false
      this.total = 0
      this.currentPage = 1
      this.status = this.tabIndex === -1 ? null : this.tabIndex

      if (!this.searchDate || this.expressNum || !this.userName || !this.orderNum) {
        this._searchOrderData()
      }
    },

    async _searchOrderData (page) {
      this.hasClickSearch = true
      let date1, date2, userName, expressNum, orderNum,tradeNum
      this.date1 = this.searchDate ? this.searchDate[0] : null
      this.date2 = this.searchDate ? this.searchDate[1] : null
      date1 = this.date1 ? (this.date1 + ' 00:00:00') : null
      date2 = this.date2 ? (this.date2 + ' 23:59:59') : null

      this.userName = userName = this.searchPhone || null
      this.expressNum = expressNum = this.searchExpressNum || null
      this.orderNum = orderNum = this.searchOrderNumber || null
      this.tradeNum = tradeNum = this.searchTradeNum || null

      // console.log(searchDate,searchPhone,searchExpressNum,searchOrderNumber)
      this.fullscreenLoading = true
      let status = this.status

      let data = (await this.$http.post(this.geturl('list'), {
        pageNum: page,
        type: status,
        startDate: date1,
        endDate: date2,
        orderSn: orderNum,
        phoneNum: userName,
        expressNum,
        tradeNum,
        pageSize: 10
      })).data

      this.fullscreenLoading = false
      let temp = data.list
      for (var i = 0; i < temp.length; i++) {
        // temp[i]['expressNum_input'] = "";
        temp[i].items = []
      }
      this.orders = temp
      this.currentPage = page
      this.total = data.total
    },
    _exportExcelForOrder () {
      let date1, date2, userName, expressNum, orderNum,tradeNum
      this.date1 = this.searchDate ? this.searchDate[0] : null
      this.date2 = this.searchDate ? this.searchDate[1] : null
      date1 = this.date1 ? (this.date1 + ' 00:00:00') : null
      date2 = this.date2 ? (this.date2 + ' 23:59:59') : null

      this.userName = userName = this.searchPhone || null
      this.expressNum = expressNum = this.searchExpressNum || null
      this.orderNum = orderNum = this.searchOrderNumber || null
      this.tradeNum = tradeNum = this.searchTradeNum || null

      let data = {
        'type': this.status,
        'startDate': date1,
        'endDate': date2,
        'orderSn': orderNum,
        'phoneNum': userName,
        'expressNum': expressNum,
        'tradeNum':tradeNum
      }
      this.fullscreenLoading = true

      console.error(data)
      this.$confirm('确定当前标签下的订单记录?', '导出订单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let exec = await this.$http({
          methods: 'get',
          params: data,
          url: this.geturl('export'),//'/manager/order/export',
          responseType: 'arraybuffer'
        })
        try {
          let blob = new Blob([exec], {type: 'application/vnd.ms-excel'})
          let url = URL.createObjectURL(blob)
          location.href = url
        } catch (e) {
          console.error(e)
        }
        this.fullscreenLoading = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出'
        })
        this.fullscreenLoading = false
      })
    },
    geturl(name){
      let urlname = this.$route.name == 'qyOrder'?'incrementOrder':'downloadOrder'
      let download = {
        list:`/manager/${urlname}/list`,
        export:`/manager/${urlname}/export`,
      }
      return download[name]
    },
    async _getOrderDetail (row) {
      this.fullscreenLoading = true
      let data = (await this.$http.post('/manager/order/detail', {orderId: row.id})).data
      let temp = this.orders.find(item => item.id === row.id)

      temp.items = data.orderItems.map(item => {
        return {
          ...item,
          product: {
            url: item.pic,
            name: item.goodsName,
            packageName: item.description,
            count: item.goodsCount,
            amount: item.goodsPrice
          },
          receive: {
            name: data.shipName,
            phone: data.shipMobile,
            address: data.shipAddress,
            invoice: data.invoice,
            expressNum: item.expressNum,
            expressName: item.expressName
          }
        }
      })
      console.log(temp)
      this.fullscreenLoading = false
    }
  },
  mounted () {
    // console.log(window.location.origin)
    // window.open(window.location.origin+'/main')
    this.routeName = this.$route.meta.text
    this._searchOrderData(1)
  }
}
</script>

<style scoped>
@import url('./style.css');
.el-icon-s-flag {
  cursor: pointer;
}

</style>

<style type="text/css">
.el-table__expand-icon--expanded {
  transform: rotate(0) !important;
}
.el-table__expand-icon>i {
  display: none !important;
}

.el-table__expand-icon:after {
  content: "\8BE6\7EC6";
  color: #09e1c0;
  cursor: pointer;
}
</style>
