<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>
          <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="searchExpressNum" v-model="searchExpressNum" 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 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="orderStatus" label="订单状态">
                <template slot-scope="scope">
                  <div>{{paymentStatusMap[scope.row.paymentStatus]}}</div>
                </template>
              </el-table-column>
              <el-table-column type="expand" prop="operation" label="操作" width="150">
                <template slot-scope="scope">

                  <div class="order_check_row">
                    <div class="product_info">
                      <div class="product_info_title">
                        商品信息
                      </div>
                      <div class="product_info_body" v-for="(item, i) in scope.row.items" :key="i">
                        <div class="product_info_body_img">
                          <img :src="item.product.url" class="product_img">
                        </div>
                        <div class="product_info_body_info">
                          <div class="product_info_body_info_item">
                            <span class="product_info_body_info_item_title">商品名称</span>
                            <span class="product_info_body_info_item_content">{{item.product.name}}</span>
                          </div>
                          <div class="product_info_body_info_item">
                            <span class="product_info_body_info_item_title">套餐</span>
                            <span class="product_info_body_info_item_content" v-html="item.product.packageName"></span>
                          </div>
                          <div class="product_info_body_info_item">
                            <span class="product_info_body_info_item_title">数量</span>
                            <span class="product_info_body_info_item_content">{{item.product.count}}</span>
                          </div>
                          <div class="product_info_body_info_item">
                            <span class="product_info_body_info_item_title">商品单价</span>
                            <span class="product_info_body_info_item_content">{{item.product.amount}}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="order_info">
                      <div class="order_info_title">
                        下单信息
                      </div>
                      <div class="order_info_body" v-if="scope.row.items.length">
                        <div class="order_info_body_info">
                          <div class="order_info_body_info_item">
                            <span class="order_info_body_info_item_title">顾客姓名</span>
                            <span class="order_info_body_info_item_content">{{scope.row.items[0].receive.name}}</span>
                          </div>
                          <div class="order_info_body_info_item">
                            <span class="order_info_body_info_item_title">电话</span>
                            <span class="order_info_body_info_item_content">{{scope.row.items[0].receive.phone}}</span>
                          </div>
                          <div class="order_info_body_info_item">
                            <span class="order_info_body_info_item_title">收货地址</span>
                            <span class="order_info_body_info_item_content">{{scope.row.shipAreaPath}}{{scope.row.items[0].receive.address}}</span>
                          </div>
                          <div class="order_info_body_info_item">
                            <span class="order_info_body_info_item_title">发票</span>
                            <span class="order_info_body_info_item_content fix-order_info_body_info_item_content">{{scope.row.items[0].receive.invoice ? '需要发票' : '不需要发票'}}</span>
                          </div>
                          <div class="order_info_body_info_item" v-if="scope.row.paymentStatus != 'unpaid'">
                            <span class="order_info_body_info_item_title">快递类别</span>
                            <span class="order_info_body_info_item_content">
                              <el-input
                                v-model="scope.row.items[0].receive.expressName" maxlength="15" placeholder="请输入快递类别"
                                type="text" v-if="scope.row.items[0].shippingStatus != 'shipped'" disabled>
                              </el-input>
                              {{scope.row.items[0].shippingStatus == 'shipped'?scope.row.items[0].receive.expressName:""}}
                            </span>
                          </div>
                          <div class="order_info_body_info_item" v-if="scope.row.paymentStatus != 'unpaid'">
                            <span class="order_info_body_info_item_title">快递单号</span>
                            <span class="order_info_body_info_item_content">
                              <el-input
                                v-model="scope.row.items[0].receive.expressNum" maxlength="15" placeholder="请输入15位顺丰快单号"
                                type="text" v-if="scope.row.items[0].shippingStatus != 'shipped'">
                              </el-input>
                              {{scope.row.items[0].shippingStatus == 'shipped'?scope.row.items[0].receive.expressNum:""}}
                            </span>
                          </div>

                          <div class="order_info_body_info_item" v-if="scope.row.paymentStatus != 'unpaid'&& scope.row.items[0].shippingStatus != 'shipped'">
                            <span class="order_info_body_info_item_title"></span>
                            <span class="order_info_body_info_item_content"><el-button @click="saveRow(scope.row, scope.row.items)" type="primary">保存</el-button><el-button @click="hideRow(scope.row)">取消</el-button></span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- <div v-if="">暂无数据</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 {
      statusMap: {
        unprocessed: '未处理',
        processed: '已确认',
        completed: '已完成',
        invalid: '已取消'
      },
      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: '',
      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])
          }
        }]
      }
    }
  },
  methods: {
    handleClick (row) {
      console.log(this.status)

      console.log(this.selectValue)
    },
    async saveRow (row, items) {
      let item = items[0]
      let orderItemIds = items.map(item => item.id).join(',')
      let expressNum = item.receive.expressNum
      var pattern = /^[\u4E00-\u9FA5]{1,5}$/
      console.log(item.receive.expressNum)

      if (!expressNum) {
        return this.$alert('请输入快递单号', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
      } else if (pattern.test(expressNum)) {
        return this.$alert('快递单号不能为中文', '提示', {
          confirmButtonText: '确定',
          callback: action => {

          }
        })
      }

      let data = await this.$http.post('/manager/order/confirmDelivery', {
        orderId: row.id,
        orderItemIds: orderItemIds,
        expressName: item.receive.expressName,
        expressNum: expressNum
      })

      if (data.code === 0) {
        this.$message({
          message: '发货成功！',
          type: 'success'
        })
      } else {
        this.$alert('保存失败', '提示', {
          confirmButtonText: '确定',
          callback: action => {}
        })
      }

      // request['saveExpressNum']({
      //   orderId,
      //   expressNum
      // }, 'get').then(res => {
      //   if (res === 1) {
      //     // this.$refs.order_table.toggleRowExpansion(row, false)
      //     row.status = '已发货'
      //     this.$message({
      //       message: '发货成功！',
      //       type: 'success'
      //     })
      //   } else {
      //     this.$alert('保存失败', '提示', {
      //       confirmButtonText: '确定',
      //       callback: action => {

      //       }
      //     })
      //   }
      // })
    },
    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
      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

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

      let data = (await this.$http.post('/manager/order/list', {
        pageNum: page,
        type: status,
        startDate: date1,
        endDate: date2,
        orderSn: orderNum,
        phoneNum: userName,
        expressNum,
        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
      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

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

      console.error(data)
      this.$confirm('确定当前标签下的订单记录?', '导出订单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let exec = await this.$http({
          methods: 'get',
          params: data,
          url: '/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
      })
    },
    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._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>
