<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="searchOrderNumber" v-model="searchOrderNumber" value="" placeholder="留言内容、备注"></el-input>
          <el-button type="primary" @click="_searchOrderData(1)" color='red'>筛选</el-button>

          <el-button type="success" @click="active = {file: ''}" color='red' style="float: right">上传</el-button>
        </div>
        <div class="order-check_bottom">
          <div class="order-management-table">
            <el-table ref="order_table" @expand-change="_getOrderDetail" class='e-table' :data="orders" style="width: 100%">
              <el-table-column prop="id" label="序号">
              </el-table-column>
              <!-- <el-table-column prop="name" label="名称">
              </el-table-column> -->
              <el-table-column prop="description" label="描述">
              </el-table-column>
              <el-table-column prop="version" label="版本">
              </el-table-column>
              <el-table-column prop="fileUrl" label="文件地址">
              </el-table-column>
              <el-table-column prop="state" label="状态">
                <template slot-scope="scope">
                  <el-switch @change="updateAduitStatus(scope.row.id,scope.row.status)" :value="scope.row.status === 'A'" active-color="#13ce66" inactive-color="#ff4949">
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="发布日期">
                <template slot-scope="scope">
                  <div>{{new Date(scope.row.createTime).format('yyyy-MM-dd hh:mm:ss')}}</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>

    <el-dialog width="750px" title="添加版本" :visible.sync="active">
      <el-form v-if="active" label-width="80px">
        <el-form-item label="版本" width="100%">
          <el-input v-model="active.version"></el-input>
        </el-form-item>
        <el-form-item label="描述" width="100%">
          <el-input type="textarea" v-model="active.description" :rows="5"></el-input>
        </el-form-item>
        <el-form-item label="文件" width="100%">
          <div class="upload-file">
            <el-button type="primary">文件上传</el-button>
            <input type="file" @change="active.file = $event.target.value" ref="file">
            <p>{{active.file}}</p>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="active = null">取 消</el-button>
        <el-button type="primary" @click="updateMaker">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'order-check',

  data () {
    return {
      type: 10,
      active: null,
      colors: [
        '#08e2c0', '#39bafe', '#fce439', '#fda000', '#f96d6c'
      ],
      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: {
    makerClick (item) {
      this.active = item
    },
    async updateAduitStatus (id, status) {
      let m = status === 'A' ? 'I' : 'A'
      let data = (await this.$http.get('/manager/goods/version/update/' + id + '/' + m + '/' + this.type))
      this._searchOrderData(this.currentPage)
    },
    async updateMaker () {
      var formData = new FormData()
      formData.append('version', this.active.version)
      formData.append('type', this.type)
      formData.append('description', this.active.description)
      formData.append('file', this.$refs.file.files[0])

      await this.$http({
        url: '/manager/goods/version/upload',
        method: 'post',
        data: formData,
        processData: false,
        contentType: false
      })
      alert('添加成功')

      this.active = null
      this._searchOrderData(this.currentPage)
    },
    handleClick (row) {
      console.log(this.status)

      console.log(this.selectValue)
    },
    async saveRow (row, item) {
      let expressNum = item.receive.expressNum
      var pattern = /^[\u4E00-\u9FA5]{1,5}$/

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

          }
        })
      }

      let data = await this.$http.post('/manager/order/confirmDelivery', {
        orderId: row.id,
        orderItemIds: item.id,
        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, 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 = this.searchPhone || null
      this.expressNum = this.searchExpressNum || null
      this.orderNum = this.searchOrderNumber || null

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

      let para = {
        pageNum: page - 1,
        // type: status,
        type: this.type,
        startDate: date1,
        endDate: date2,
        itemName: orderNum || '',
        // phoneNum: userName,
        pageSize: 10
      }

      let url = '/manager/goods/version/list'
      let method = 'get'
      let data
      if (para.startDate || para.endDate || para.itemName) {
        url = '/manager/goods/version/search'
        method = 'post'
      }

      console.log(method, para)
      if (method === 'get') {
        let paras = []
        Object.keys(para).forEach(k => {
          if (para[k] || typeof para[k] === 'number') {
            paras.push(`${k}=${para[k]}`)
          } else {
            paras.push(`${k}=''`)
          }
        })

        para = paras.join('&')
        data = (await this.$http[method](url + '?' + para)).data
      } else {
        data = (await this.$http[method](url, para)).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");
</style>

<style type="text/css">
.el-table__expand-icon > i {
  display: none !important;
}
</style>
