<template>
  <a-card :bordered="false" class="ledouCollectRecord-table-page-search-wrapper">
    <div class="ledouCollectRecord-searchForm">
      <a-form layout="inline" @keyup.enter.native="refresh">
        <a-row :gutter="48">
          <a-col :xs="24" :sm="12" :md="6" :lg="5">
            <a-form-item label="收取时间:" :label-col="{ span: 7 }" :wrapper-col="{ span: 17}">
              <a-range-picker
                style="width:100%"
                id="ledouCollectRecord-queryOrderDate"
                :disabledDate="disabledDate"
                v-model="queryOrderDate"
                :format="dateFormat"
                :placeholder="['开始时间', '结束时间']" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="6" :lg="5">
            <a-form-item label="用户手机" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-input id="ledouCollectRecord-customerMobile" allowClear :maxLength="11" v-model=" queryParam.customerMobile" placeholder="请输入用户手机" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="6" :lg="5">
            <a-form-item label="商户名称" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-select
                placeholder="请选择"
                allowClear
                v-model="queryParam.officialPartnerNo"
                :showSearch="true"
                option-filter-prop="children"
                :filter-option="filterOption"
              >
                <a-select-option v-for="item in optionData" :key="item.officialPartnerNo" :value="item.officialPartnerNo">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="6" :lg="5">
            <a-form-item label="是否撤销" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <v-select code="GOLD_LOG_CANCEL_FLAG" v-model="queryParam.cancelFlag" allowClear placeholder="请选择" id="ledouCollectRecord"></v-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="6" :lg="4">
            <a-button class="handle-btn serach-btn" id="ledouCollectRecord-serach" type="primary" @click="refresh">查询</a-button>
            <a-button class="handle-btn" id="ledouCollectRecord-reset" @click="handleReset">重置</a-button>
            <a-button class="handle-btn export-btn" id="ledouCollectRecord-export" :loading="loading" @click="handleExport" v-hasPermission="'B_ledouCollectRecord_export'">导出</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> {{ totalGold }} </span>个，其中 {{ cancelGold }} 个乐豆已撤销收取</div>
    </a-alert>
    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      bordered>
    </s-table>
  </a-card>

</template>

<script>
import { STable, VSelect } from '@/components'
import { offPartnerGoldLogList, getOffPartnerGoldLogTotal, sellerList, exportOffPartnerGoldLog } from '@/api/ledouCollectRecord.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 }
      },
      // 将默认近7天时间日期回显在时间选择框中
      queryOrderDate: [
        moment(getDate.getRecentday().starttime, this.dateFormat),
        moment(getDate.getRecentday().endtime, this.dateFormat)
      ],
      dateFormat: 'YYYY-MM-DD',
      // 查询参数
      queryParam: {
        beginDate: null, // 开始时间
        endDate: null, // 结束时间
        customerMobile: '', //  用户手机
        officialPartnerNo: undefined, // 商户名称
        cancelFlag: '' // 是否撤销
      },
      optionData: [],
      orderTotal: 0,	// 总单数
      totalGold: 0,	// 总金额
	  cancelGold: 0, // 撤销收取乐豆数
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '收取时间', dataIndex: 'createDate', align: 'center' },
        { title: '收取乐豆个数', dataIndex: 'changeNum', width: 200, customRender: (text) => { return text || 0 }, align: 'center' },
        { title: '用户手机', dataIndex: 'customerMobile', align: 'center' },
        { title: '商户名称', dataIndex: 'officialPartnerName', align: 'center' },
        { title: '是否撤销乐豆收取', dataIndex: 'cancelFlagDictValue', 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 offPartnerGoldLogList(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.orderTotal = res.data.count
            this.getTotal()
            return res.data
          }
        })
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
	  vm.queryOrderDate = [
	    moment(getDate.getRecentday().starttime, vm.dateFormat),
	    moment(getDate.getRecentday().endtime, vm.dateFormat)
	  ]
	  vm.queryParam.officialPartnerNo = undefined
	  vm.queryParam.customerMobile = ''
	  vm.queryParam.cancelFlag = ''
	  vm.getSellerList()
    })
  },
  methods: {
    moment,
    // 不可选日期
    disabledDate (date, dateStrings) {
      return date && date.valueOf() > Date.now()
    },
    filterOption (input, option) {
	  return (
	    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
	  )
    },
    // 获取合作商数据
    getSellerList () {
	  sellerList().then(res => {
		  if (res.status == 200) {
			  this.optionData = res.data || []
		  }
	  })
    },
    // 导出
    handleExport () {
      const params = this.queryParam
      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)
    },
    // 合计
    getTotal () {
      const params = this.queryParam
      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 = ''
      }
      getOffPartnerGoldLogTotal(params).then(res => {
        if (res.status == 200) {
          if (res.data) {
            this.totalGold = res.data.totalGold || 0
            this.cancelGold = res.data.totalCancelGold || 0
          } else {
            this.totalGold = 0
            this.cancelGold = 0
          }
        }
      })
    },
    // 重置
    handleReset () {
      this.queryOrderDate = [
        moment(getDate.getRecentday().starttime, this.dateFormat),
        moment(getDate.getRecentday().endtime, this.dateFormat)
      ]
	  this.queryParam.officialPartnerNo = undefined
	  this.queryParam.customerMobile = ''
	  this.queryParam.cancelFlag = ''
      this.$refs.table.refresh(true)
    }
  }
}
</script>
<style lang="less" scoped>
  .ledouCollectRecord-table-page-search-wrapper{
    .ledouCollectRecord-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>
