<template>
  <a-card :bordered="false" class="shopOrder-table-page-search-wrapper">
    <div class="shopOrder-searchForm">
      <a-form layout="inline" v-bind="formItemLayout" @keyup.enter.native="$refs.table.refresh(true)">
        <a-row :gutter="20">
          <a-col :span="6">
            <a-form-item label="下单时间" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-range-picker
                id="shopOrder-time"
                v-model="time"
                :format="dateFormat"
                :placeholder="['开始时间','结束时间']"
                :disabledDate="disabledDate"
                @change="onChange" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="用户手机" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input id="shopOrder-customerMobile" allowClear :maxLength="11" v-model="queryParam.customerMobile" placeholder="请输入用户手机" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="订单状态" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select
                v-model="queryParam.orderState"
                ref="orderState"
                id="shopOrder-status"
                code="ORDER_STATE"
                placeholder="请选择订单状态"
                allowClear></v-select>
            </a-form-item>
          </a-col>

        </a-row>
        <a-row :gutter="20">
          <a-col :span="6">
            <a-form-item label="订单编号" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input id="shopOrder-orderSn" allowClear :maxLength="30" v-model="queryParam.orderSn" placeholder="请输入订单编号" />
            </a-form-item>
          </a-col>
          <a-col :span="18">
            <a-button class="handle-btn btn-right" id="shopOrder-btn-serach" type="primary" @click="$refs.table.refresh(true)">查询</a-button>
            <a-button class="handle-btn btn-right" type="" id="shopOrder-btn-reset" @click="handleReset">重置</a-button>
            <a-button
              v-if="$hasPermissions('B_orderManage_export')"
              class="export-btn"
              id="shopOrder-btn-export"
              :loading="loading"
              @click="handleExport">导出订单</a-button>
            <a-button
              class="export-btn"
              id="shopOrder-btn-exportDetail"
              v-if="$hasPermissions('B_orderManage_exportOrder')"
              :loading="loadingDetail"
              @click="handleOrderExport">导出订单明细</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      bordered>
      <!-- 订单总额 -->
      <template slot="originalGold" slot-scope="text, record">
        <span>{{ record.originalGold || 0 }}乐豆</span>
      </template>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <a-button v-if="$hasPermissions('B_orderManage_detail')" id="shopOrder-handleView" type="link" @click="handleView(record)">详情</a-button>
        <span v-else>--</span>
      </template>
    </s-table>
  </a-card>

</template>

<script>
import { STable, VSelect } from '@/components'
import getDate from '@/libs/getDate.js'
import moment from 'moment'
import { orderList, orderExport, orderDetailExport } from '@/api/order'
export default {
  name: 'ShopOrder',
  components: { STable, VSelect },
  data () {
    return {
      formItemLayout: {
        labelCol: { span: 7 },
        wrapperCol: { span: 17 }
      },
      // 查询参数
      queryParam: {
        beginDate: null, // 开始时间
        endDate: null, // 结束时间
        customerMobile: '', //  用户手机
        orderSn: '', //  订单编号
        orderState: null // 订单状态
      },
      loading: false, // 导出loading
	  loadingDetail: false, // 导出订单明细loading
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '下单时间', dataIndex: 'orderTime', width: 200, align: 'center' },
        { title: '用户手机', dataIndex: 'customerMobile', width: 200, align: 'center' },
        { title: '订单编号', dataIndex: 'orderSn', width: 200, align: 'center' },
        { title: '订单状态', dataIndex: 'orderStateDictValue', width: 200, align: 'center' },
        { title: '订单总额', scopedSlots: { customRender: 'originalGold' }, width: 200, align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 150, align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const searchData = Object.assign(parameter, this.queryParam)
        if (this.time && this.time.length) {
          searchData.beginDate = moment(this.time[0]).format('YYYY-MM-DD')
          searchData.endDate = moment(this.time[1]).format('YYYY-MM-DD')
        } else {
          searchData.beginDate = ''
          searchData.endDate = ''
        }
        return orderList(searchData).then(res => {
          if (res.status == 200) {
            const no = (res.data.pageNo - 1) * res.data.pageSize
            for (let i = 0; i < res.data.list.length; i++) {
              const _item = res.data.list[i]
              _item.no = no + i + 1
              _item.status = _item.status + '' === '1'
            }
            return res.data
          }
        })
      },
      // 将默认当天时间日期回显在时间选择框中
      time: [
        moment(getDate.getToday().starttime, this.dateFormat),
        moment(getDate.getToday().endtime, this.dateFormat)
      ],
      dateFormat: 'YYYY-MM-DD'
    }
  },
  methods: {
    moment,
    // 不可选日期
    disabledDate (date, dateStrings) {
      return date && date.valueOf() > Date.now()
    },
    // 创建时间change
    onChange (dates, dateStrings) {
      if ((dates, dateStrings)) {
        this.queryParam.beginDate = dateStrings[0]
        this.queryParam.endDate = dateStrings[1]
      }
    },
    //  查看详情
    handleView (row) {
      this.$router.push({ path: `/order/orderManage/detail/${row.id}` })
    },
    // 重置
    handleReset () {
      this.queryParam.beginDate = getDate.getToday().starttime
      this.queryParam.endDate = getDate.getToday().endtime
      this.time = [
        moment(getDate.getToday().starttime, this.dateFormat),
        moment(getDate.getToday().endtime, this.dateFormat)
      ]
      this.queryParam.customerMobile = ''
      this.queryParam.orderSn = ''
      this.queryParam.orderState = null
      this.$refs.table.refresh(true)
    },
    // 导出
    handleExport () {
      const params = {
        beginDate: this.queryParam.beginDate == null ? getDate.getToday().starttime : this.queryParam.beginDate,
        endDate: this.queryParam.endDate == null ? getDate.getToday().endtime : this.queryParam.endDate,
        customerMobile: this.queryParam.customerMobile,
        orderSn: this.queryParam.orderSn,
        orderState: this.queryParam.orderState
      }
      if (!params.beginDate && !params.endDate) {
        this.$message.error('请先选择需要导出的下单时间区间再进行导出！')
        return
      }
      // 判断两个时间段是否相差m个月  第二个参数指相差单位，第三个参数指是否返回浮点形式（小数）
      if (moment(params.endDate).diff(moment(params.beginDate), 'months', true) > 3) {
        this.$message.error('单次最多只能导出3个月的数据，请缩小查询区间后再进行导出！')
        return
      }
      this.loading = true
      orderExport(params).then(res => {
        this.loading = false
        const frname = '订单记录-'
        this.download(res, frname)
      })
    },
    // 导出订单明细
    handleOrderExport () {
      const params = { order: {
        beginDate: this.queryParam.beginDate == null ? getDate.getToday().starttime : this.queryParam.beginDate,
        endDate: this.queryParam.endDate == null ? getDate.getToday().endtime : this.queryParam.endDate,
        customerMobile: this.queryParam.customerMobile,
        orderSn: this.queryParam.orderSn,
        orderState: this.queryParam.orderState
      } }
      if (!params.order.beginDate && !params.order.endDate) {
        this.$message.error('请先选择下单时间后查询并导出！')
        return
      }
      // 判断两个时间段是否相差m个月  第二个参数指相差单位，第三个参数指是否返回浮点形式（小数）
      if (moment(params.order.endDate).diff(moment(params.order.beginDate), 'months', true) > 3) {
        this.$message.error('仅支持导出最多3个月数据，请先修改下单时间再进行导出！')
        return
      }
      this.loadingDetail = true
      orderDetailExport(params).then(res => {
        this.loadingDetail = false
        const frname = '订单商品明细-'
        this.download(res, frname)
      })
    },
    download (data, frname) {
      if (!data) { return }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      const a = moment().format('YYYYMMDDhhmmss')
      const fname = frname + a
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    }
  }
}
</script>
<style lang="less" scoped>
  .shopOrder-table-page-search-wrapper{
    .shopOrder-searchForm{
      .ant-form-inline .ant-form-item{
        width: 100%;
      }
      // 搜索框的下间距
      .ant-form-item {
      	margin-bottom: 10px;
      }
      .handle-btn{
        margin-top: 4px;
      }
      .btn-right{
        margin-right: 10px;
      }
    }
    .export-btn{
      background-color: #ff9900;
      border-color: #ff9900;
      color: #fff;
      margin-right: 10px;
    }
    .export-btn.ant-btn:focus:not(.ant-btn-primary):not(.ant-btn-danger), .export-btn.ant-btn:hover:not(.ant-btn-primary):not(.ant-btn-danger){
      color: #fff;
      border-color: #ff9900;
    }
    .blue {
    	color: #1890FF;
    }
    .green {
    	color: #16b50e;
    }
    .red {
    	color: red;
    }
  }
</style>
