<template>
  <a-card :bordered="false" class="leduQuery-table-page-search-wrapper">
    <div class="leduQuery-searchForm">
      <a-form layout="inline" @keyup.enter.native="refresh">
        <a-row :gutter="20">
          <a-col :span="6">
            <a-form-item label="交易时间:" :label-col="{ span: 7 }" :wrapper-col="{ span: 17}">
              <a-range-picker
                style="width:100%"
                id="releaseRecordList-queryOrderDate"
                :disabledDate="disabledDate"
                v-model="queryOrderDate"
                :format="dateFormat"
                :placeholder="['开始时间', '结束时间']" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="商户名称" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-input id="releaseRecordList-officialPartnerName" allowClear :maxLength="11" v-model=" queryParam.officialPartnerName" placeholder="请输入商户名称" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-button class="handle-btn serach-btn" id="releaseRecordList-serach" type="primary" @click="refresh">查询</a-button>
            <a-button class="handle-btn" id="releaseRecordList-reset" @click="handleReset">重置</a-button>
            <a-button class="handle-btn export-btn" id="releaseRecordList-export" v-hasPermission="'B_ledouTjExport'" :loading="loading" @click="handleExport">导出</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 合计 -->
    <a-alert type="info" showIcon style="margin-bottom:15px">
      <div class="ftext" slot="message">总计<span> {{ orderTotal }} </span>条记录，收取乐豆<span> {{ amountTotal }} </span>个</div>
    </a-alert>
    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      bordered>
      <template slot="changeNum" slot-scope="text, record">
        {{ text||'0' }}
      </template>
    </s-table>
  </a-card>

</template>

<script>
import { STable, VSelect } from '@/components'
import { getOffPartnerGoldLog, exportOffPartnerGoldLog, getQueryStatistic } from '@/api/offPartnerGoldLog.js'
import moment from 'moment'
import getDate from '@/libs/getDate.js'
export default {
  components: { STable, VSelect },
  data () {
    return {
      loading: false,
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 }
      },
      // 将默认当天时间日期回显在时间选择框中
      queryOrderDate: [
        moment(getDate.getRecentday().starttime, this.dateFormat),
        moment(getDate.getRecentday().endtime, this.dateFormat)
      ],
      dateFormat: 'YYYY-MM-DD',
      // 查询参数
      queryParam: {
        beginDate: null, // 开始时间
        endDate: null, // 结束时间
        officialPartnerName: '' //  用户手机
      },
      optionData: [],
      orderTotal: 0,	// 总单数
      amountTotal: 0,	// 总金额
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '商户名称', dataIndex: 'officialPartnerName', align: 'center' },
        { title: '收取乐豆个数', scopedSlots: { customRender: 'changeNum' }, dataIndex: 'changeNum', width: 200, align: 'center' }
        // { title: '交易时间', dataIndex: 'createDate', width: 200, align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const searchData = Object.assign(parameter, this.queryParam)
        if (this.queryOrderDate && this.queryOrderDate.length) {
          searchData.beginDate = moment(this.queryOrderDate[0]).format('YYYY-MM-DD')
          searchData.endDate = moment(this.queryOrderDate[1]).format('YYYY-MM-DD')
        } else {
          searchData.beginDate = ''
          searchData.endDate = ''
        }
        return getOffPartnerGoldLog(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
            }
            this.getListTotal()
            return res.data
          }
        })
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.handleReset()
    })
  },
  methods: {
    moment,
    // 不可选日期
    disabledDate (date, dateStrings) {
      return date && date.valueOf() > Date.now()
    },
    // 导出
    handleExport () {
      const params = {
        officialPartnerName: this.queryParam.officialPartnerName
      }
      if (this.queryOrderDate && this.queryOrderDate.length) {
        params.beginDate = moment(this.queryOrderDate[0]).format('YYYY-MM-DD')
        params.endDate = moment(this.queryOrderDate[1]).format('YYYY-MM-DD')
      } else {
        params.beginDate = ''
        params.endDate = ''
      }
      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
      exportOffPartnerGoldLog(params).then(res => {
        this.loading = false
        this.download(res)
      })
    },
    download (data) {
      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 = '商户乐豆统计-' + a
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    },
    // 查询
    refresh () {
      this.$refs.table.refresh(true)
    },
    // 合计
    getListTotal () {
      const params = {
        officialPartnerName: this.queryParam.officialPartnerName,
        beginDate: this.queryParam.beginDate,
        endDate: this.queryParam.endDate
      }
      if (this.queryOrderDate && this.queryOrderDate.length) {
        params.beginDate = moment(this.queryOrderDate[0]).format('YYYY-MM-DD')
        params.endDate = moment(this.queryOrderDate[1]).format('YYYY-MM-DD')
      } else {
        params.beginDate = ''
        params.endDate = ''
      }
      getQueryStatistic(params).then(res => {
        if (res.status == 200) {
          if (res.data) {
            this.orderTotal = res.data.dataCount || 0
            this.amountTotal = res.data.dataSum || 0
          } else {
            this.orderTotal = 0
            this.amountTotal = 0
          }
        }
      })
    },
    // 重置
    handleReset () {
      this.queryOrderDate = [
        moment(getDate.getRecentday().starttime, this.dateFormat),
        moment(getDate.getRecentday().endtime, this.dateFormat)
      ]
      this.queryParam.officialPartnerName = ''
      this.$refs.table.refresh(true)
    }
  }
}
</script>
<style lang="less" scoped>
  .leduQuery-table-page-search-wrapper{
    .leduQuery-searchForm{
      .ant-form-inline .ant-form-item{
        width: 100%;
      }
      // 搜索框的下间距
      .ant-form-item {
      	margin-bottom: 10px;
      }
      .handle-btn{
        margin-top: 4px;
      }
      .serach-btn{
        margin-right: 10px;
      }
    }
    .export-btn{
      background-color: #ff9900;
      border-color: #ff9900;
      color: #fff;
      margin-left: 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;
    }
  }
</style>
