<template>
  <div id="order-check">
    <el-dialog title="查看图片" :visible.sync="dialogVisible" width="45%" center>
      <div style="text-align: center">
        <img style="width: 100%" :src="invoiceImg" alt="" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <div class="order-check-body" v-loading.fullscreen.lock="fullscreenLoading">
      <div class="order-management-body">
        <div class="order-management-inner">
          <span>发票类型：</span>
          <el-select @change="selectChange" v-model="search_value" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div class="base-info">
            <span>订单号：</span>
            <el-input
              ref="searchOrderNumber"
              v-model="orderSn"
              value=""
              placeholder="订单号"
            ></el-input>
            <span style="margin-left: 20px">关键字：</span>
            <el-input
              ref="searchPhone"
              v-model="key_input"
              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 != 1"
                    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
                > -->
                <el-button type="primary" @click="_exportExcelForInvoice" 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 type="index"> </el-table-column>
              <el-table-column
                v-for="(item, i) in tableHeader"
                :key="i"
                :prop="item.name"
                :label="item.label"
              >
                <template slot-scope="scope">
                  <span
                    v-if="item.name == 'orderSn' && scope.row.responseDownloadOrder"
                    >{{ scope.row.responseDownloadOrder.orderSn || "-" }}</span
                  >
                  <span v-else-if="item.name == 'shipAddress' && scope.row.type == 2">{{
                    "-"
                  }}</span>
                  <span v-else-if="item.name == 'shipMobile' && scope.row.type == 2">{{
                    "-"
                  }}</span>
                  <span v-else-if="item.name == 'money' && scope.row.consumeType == 2">{{
                    scope.row.responseIncrementOrder.amount || "-"
                  }}</span>
                  <span v-else-if="item.name == 'money' && scope.row.consumeType == 3">{{
                    scope.row.responseDownloadOrder.amount || "-"
                  }}</span>
                  <span v-else>{{ scope.row[item.name] || "-" }}</span>
                </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>
                      <el-table
                        @expand-change="_getOrderDetail"
                        class="e-table"
                        :data="scope.row.orderItems"
                        style="width: 100%"
                      >
                        <el-table-column
                          v-for="(item, i) in itemHeader"
                          :key="i"
                          :prop="item.name"
                          :label="item.label"
                        >
                          <template slot-scope="scope">
                            <span>{{ scope.row[item.name] || "-" }}</span>
                          </template>
                        </el-table-column>
                      </el-table>
                      <div class="total">总价：{{ scope.row.money }}</div>
                    </div>
                    <div class="order_info">
                      <div class="order_info_title">下单信息</div>
                      <div class="order_info_body">
                        <div class="order_info_body_info">
                          <div class="order_info_body_info_item">
                            <span class="order_info_body_info_item_title">顾客姓名</span>
                            <span
                              v-if="scope.row.type == 2"
                              class="order_info_body_info_item_content"
                              >{{ "-" }}</span
                            >
                            <span v-else class="order_info_body_info_item_content">{{
                              scope.row.shipName || "-"
                            }}</span>
                          </div>
                          <div class="order_info_body_info_item">
                            <span class="order_info_body_info_item_title">电话</span>
                            <span
                              v-if="scope.row.type == 2"
                              class="order_info_body_info_item_content"
                              >{{ "-" }}</span
                            >
                            <span v-else class="order_info_body_info_item_content">{{
                              scope.row.shipMobile || "-"
                            }}</span>
                          </div>
                          <div class="order_info_body_info_item">
                            <span class="order_info_body_info_item_title">收货地址</span>
                            <span
                              v-if="scope.row.type == 2"
                              class="order_info_body_info_item_content"
                              >{{ "-" }}</span
                            >
                            <span v-else class="order_info_body_info_item_content">{{
                              scope.row.shipAddress || "-"
                            }}</span>
                          </div>

                          <template v-if="scope.row.type === 2">
                            <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.emailAddress || "-"
                              }}</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"
                                style="position: relative"
                              >
                                <div style="display: inline-block">
                                  <el-upload
                                    class="upload-demo"
                                    :headers="{ token: token }"
                                    :on-change="handleChange"
                                    :file-list="fileList"
                                    :on-success="upload_success"
                                    :on-error="upload_fail"
                                    :action="`/api/manager/invoice/uploadEInvoice`"
                                    :limit="1"
                                  >
                                    <el-button size="small" type="primary">{{
                                      scope.row.einvoice ? "更改发票" : "上传发票"
                                    }}</el-button>
                                  </el-upload>
                                </div>

                                <span
                                  style="
                                    color: #1fe4dc;
                                    margin-left: 10px;
                                    cursor: pointer;
                                  "
                                  @click="lookInvoice"
                                  >查看电子发票</span
                                >
                              </span>
                            </div>
                          </template>

                          <template v-if="scope.row.type === 3">
                            <div class="order_info_body_info_item">
                              <span class="order_info_body_info_item_title"
                                >快递单号：</span
                              >
                              <span class="order_info_body_info_item_content">
                                <el-input
                                  v-model="scope.row.expressNumber"
                                  maxlength="15"
                                  placeholder="请输入15位顺丰快单号"
                                  type="text"
                                >
                                </el-input>
                              </span>
                            </div>
                          </template>
                          <div class="order_info_body_info_item">
                            <span class="order_info_body_info_item_title"
                              >开票备注：</span
                            >
                            <span class="order_info_body_info_item_content">
                              <div style="width: 220px; display: inline-block">
                                <el-input
                                  type="textarea"
                                  v-model="scope.row.remarks"
                                ></el-input>
                              </div>
                            </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">
                              <el-button :loading="editLoading" type="primary" @click="saveRow(scope.row)">{{
                                scope.row.type === 2 ? "发送" : "保存"
                              }}</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>
const tableHeader = [
  {
    name: 'orderSn',
    label: '订单编号'
  },
  {
    name: 'typeStr',
    label: '发票类型'
  },
  {
    name: 'money',
    label: '开票金额'
  },
  {
    name: 'title',
    label: '发票抬头'
  },
  {
    name: 'code',
    label: '18位税号'
  },
  {
    name: 'organizedAddress',
    label: '注册地址'
  },
  {
    name: 'registerPhone',
    label: '注册电话'
  },
  {
    name: 'bankAccount',
    label: '银行账号'
  },
  {
    name: 'shipAddress',
    label: '收件地址'
  },
  {
    name: 'emailAddress',
    label: '电子邮箱'
  },
  {
    name: 'shipMobile',
    label: '手机号码'
  }
]

const itemHeader = [
  {
    name: 'goodsName',
    label: '商品名称'
  },
  {
    name: 'goodsCount',
    label: '数量'
  },
  {
    name: 'goodsPrice',
    label: '价格'
  },
  {
    name: 'abroad',
    label: '币种'
  }
]

const TypeArr = {
  2: '增值税普通发票',
  3: '增值税专用发票'
}

export default {
  name: 'order-check',

  data () {
    return {
      editLoading: false,
      status: 0,
      dialogVisible: false,
      fileVal: '',
      tableHeader,
      itemHeader,
      statusMap: {
        unprocessed: '未处理',
        processed: '已确认',
        completed: '已完成',
        invalid: '已取消'
      },
      payMap: {
        0: '微信',
        1: '支付宝',
        2: 'paypal',
        3: '其他',
        4: '货到付款'
      },
      paymentStatusMap: {
        unpaid: '未付款',
        paid: '已付款',
        cancel: '已取消',
        partPayment: '部分支付',
        partRefund: '部分退款',
        refunded: '全额退款'
      },
      tabs: [
        { name: '未开票', idx: 0 },
        { name: '已开票', idx: 1 }
      ],
      expandedArr: [],
      orders: [],
      currentPage: 1,
      key_input: '',
      orderSn: '',
      fullscreenLoading: false,
      product: {
        name: '',
        packageName: '',
        count: '',
        amount: '',
        url: ''
      },
      receive: {
        name: '',
        phone: '',
        address: '',
        invoice: '',
        expressNum: ''
      },
      total: 0,
      options: [
        {
          value: '',
          label: '全部'
        },
        {
          value: 2,
          label: '增值税普通发票'
        },
        {
          value: 3,
          label: '增值税专用发票'
        }
      ],
      selectValue: '',
      // expressNum_input: "",
      searchDate: [],
      searchOrderNumber: '',
      searchPhone: '',
      searchExpressNum: '',
      hasClickSearch: false,
      tabIndex: 0,
      search_value: '',
      invoiceImg: '',
      token: sessionStorage.token,
      fileList: []
    }
  },
  watch: {},
  methods: {
    handleChange (file, fileList) {
      // console.log('file', file)
      // console.log('fileList', fileList)

      if (fileList.length > 1) {
        this.fileList = fileList.slice(-1)
      }
    },
    upload_success (data) {
      if (data.code === 0) {
        this.invoiceImg = data.msg
      }
    },
    lookInvoice () {
      if (this.invoiceImg) {
        window.open(this.invoiceImg, '_blank')
      }
    },
    upload_fail (data) {
      this.$notify.error({
        title: '上传失败',
        message: data.message
      })
    },
    selectChange (e) {
      this.search_value = e
    },
    async saveRow (row) {
      let { type, id, remarks, expressNumber } = row
      let params = {
        invoiceId: id,
        remarks,
        filePath: this.invoiceImg,
        expressNumber,
        expressCompany: '顺丰'
      }
      var pattern = /^[\u4E00-\u9FA5]{1,5}$/

      let url =
        type === 2 ? '/manager/invoice/sendEInvoice' : '/manager/invoice/sendExpress'

      if (!this.invoiceImg && type === 2) {
        return this.$alert('请上传电子发票', '提示', {
          confirmButtonText: '确定',
          callback: (action) => {}
        })
      }

      if (!expressNumber && type === 3) {
        return this.$alert('请输入快递单号', '提示', {
          confirmButtonText: '确定',
          callback: (action) => {}
        })
      } else if (pattern.test(expressNumber) && type === 3) {
        return this.$alert('快递单号不能为中文', '提示', {
          confirmButtonText: '确定',
          callback: (action) => {}
        })
      }
      this.editLoading = true
      let data = await this.$http.post(url, params)
      if (data.code === 0) {
        this.editLoading = false
        this.$message({
          message: type === 3 ? '保存成功' : '发送成功',
          type: 'success'
        })
        this.hideRow(row)
      } else {
        this.editLoading = false
        this.$alert(type === 3 ? '保存失败' : '发送失败', '提示', {
          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

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

      let data = (
        await this.$http.post('/manager/invoice/invoiceList', {
          pageNum: page,
          pageSize: 10,
          type: this.search_value,
          finish: this.tabIndex,
          orderSn: this.orderSn,
          searchKey: this.key_input
        })
      ).data

      this.fullscreenLoading = false
      let temp = data.list
      for (var i = 0; i < temp.length; i++) {
        // temp[i]['expressNum_input'] = "";
        temp[i].items = []
        temp[i]['typeStr'] = TypeArr[temp[i]['type']]
        temp[i].orderItems = temp[i]['orderDetail']
          ? temp[i]['orderDetail']['orderItems']
          : temp[i]['responseVirtualOrder']
            ? [
              {
                goodsName: temp[i]['responseVirtualOrder'].body,
                goodsCount: temp[i]['responseVirtualOrder'].orderCount,
                goodsPrice: temp[i]['responseVirtualOrder'].amount,
                abroad: temp[i]['responseVirtualOrder'].abroad
              }
            ]
            : temp[i]['responseIncrementOrder']
              ? [
                {
                  goodsName: '会员权益',
                  goodsCount: temp[i]['responseIncrementOrder'].count,
                  goodsPrice: temp[i]['responseIncrementOrder'].amount,
                  abroad: temp[i]['responseIncrementOrder'].abroad
                }
              ]
              : ''

        temp[i]['orderSn'] = temp[i]['orderDetail']
          ? temp[i]['orderDetail']['orderSn']
          : temp[i]['responseIncrementOrder']
            ? temp[i]['responseIncrementOrder']['orderSn']
            : temp[i]['responseVirtualOrder']
              ? temp[i]['responseVirtualOrder']['orderSn']
              : ''
      }
      this.orders = temp
      this.currentPage = page
      this.total = data.total
    },
    _exportExcelForInvoice () {
      this.$confirm('确定当前标签下的订单记录?', '导出订单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // let exec = await this.$http.post('/manager/invoice/exportInvoiceList', {
          //   // pageNum: page,
          //   // pageSize: 10,
          //   type: this.search_value,
          //   finish: this.tabIndex,
          //   orderSn: this.orderSn,
          //   searchKey: this.key_input
          // })
          let data = {
            // pageNum: page,
            // pageSize: 10,
            type: '',
            finish: this.tabIndex,
            orderSn: '',
            searchKey: ''
          }
          let exec = await this.$http({
            method: 'post',
            url: `/manager/invoice/exportInvoiceList`,
            data: data,
            responseType: 'arraybuffer'
          })
          try {
            let blob = new Blob([exec], { type: 'application/vnd.ms-excel' })
            let href = URL.createObjectURL(blob)
            console.log(href)
            // location.href = url

            // 谷歌浏览器 创建a标签 添加download属性下载
            const downloadElement = document.createElement('a')
            downloadElement.href = href
            downloadElement.target = '_blank'
            downloadElement.download = new Date().getTime() + '.xls'
            document.body.appendChild(downloadElement)
            downloadElement.click() // 点击下载
            document.body.removeChild(downloadElement) // 下载完成移除元素
            window.URL.revokeObjectURL(href) // 释放掉blob对象
          } catch (e) {
            console.error(e)
          }
          this.fullscreenLoading = false
        })
        .catch((err) => {
          console.log(err.message)
          this.$message({
            type: 'info',
            message: '导出失败'
          })
          this.fullscreenLoading = false
        })
    },

    _exportExcelForOrder () {
      let date1, date2, userName, expressNum, orderNum
      this.date1 = this.searchDate ? this.searchDate[0] : ''
      this.date2 = this.searchDate ? this.searchDate[1] : ''
      date1 = this.date1 ? this.date1 + ' 00:00:00' : ''
      date2 = this.date2 ? this.date2 + ' 23:59:59' : ''

      this.userName = userName = this.searchPhone || ''
      this.expressNum = expressNum = this.searchExpressNum || ''
      this.orderNum = orderNum = this.searchOrderNumber || ''

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

      this.$confirm('确定当前标签下的订单记录?', '导出订单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let exec = await this.$http({
            methods: 'get',
            url: `/manager/order/export?type=${this.status}&startDate=${date1}&endDate=${date2}&orderSn=${orderNum}&phoneNum=${this.userName}&expressNum=${expressNum}`,
            // url: `/manager/order/export?type=${this.tabIndex}`,
            // url: `/manager/invoice/exportInvoiceList?type=${this.tabIndex}`,
            responseType: 'arraybuffer'
          })

          try {
            let blob = new Blob([exec], { type: 'application/vnd.ms-excel' })
            let href = URL.createObjectURL(blob)
            console.log(href)
            // location.href = url

            // 谷歌浏览器 创建a标签 添加download属性下载
            const downloadElement = document.createElement('a')
            downloadElement.href = href
            downloadElement.target = '_blank'
            downloadElement.download = new Date().getTime() + '.xls'
            document.body.appendChild(downloadElement)
            downloadElement.click() // 点击下载
            document.body.removeChild(downloadElement) // 下载完成移除元素
            window.URL.revokeObjectURL(href) // 释放掉blob对象
          } catch (e) {
            console.error(e)
          }
          this.fullscreenLoading = false
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消导出'
          })
          this.fullscreenLoading = false
        })
    },
    async _getOrderDetail (row) {
      console.log('row---------', row)
      this.invoiceImg = row.einvoice

      // 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>
