<template>
  <a-card :bordered="false" class="luckDrawRecord-table-page-search-wrapper">
    <div class="luckDrawRecord-searchForm">
      <a-form layout="inline" v-bind="formItemLayout" @keyup.enter.native="$refs.table.refresh(true)">
        <a-row :gutter="24">
          <a-col :xs="24" :sm="12" :md="6" :lg="5">
            <a-form-item label="抽奖时间" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-range-picker
                id="luckDrawRecord-time"
                v-model="time"
                :format="dateFormat"
                :placeholder="['开始时间','结束时间']"
                :disabledDate="disabledDate"
                @change="onChange" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="6" :lg="5">
            <a-form-item label="用户账号" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input id="luckDrawRecord-customerMobile" allowClear 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="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input id="luckDrawRecord-activeName" allowClear v-model="queryParam.activeName" placeholder="请输入活动名称" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="6" :lg="5">
            <a-form-item label="是否中奖" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select
                v-model="queryParam.state"
                ref="orderState"
                id="luckDrawRecord-state"
                code="PRIZE_WIN_STATE"
                placeholder="请选择"
                allowClear></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="luckDrawRecord-btn-serach" type="primary" @click="$refs.table.refresh(true)">查询</a-button>
            <a-button class="handle-btn serach-btn" type="" id="luckDrawRecord-btn-reset" @click="handleReset">重置</a-button>
            <a-button class="export-btn" id="luckDrawRecord-btn--export" :loading="loading" v-hasPermission="'B_winingRecord_export'" @click="handleExport">导出</a-button>
          </a-col>
        </a-row>
        <a-row :gutter="20">
        </a-row>
      </a-form>
    </div>
    <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 {
  getLuckyWinList
} from '@/api/luckyDraw.js'
import moment from 'moment'
export default {
  name: 'LuckDrawRecord',
  components: {
    STable,
    VSelect
  },
  data () {
    return {
      formItemLayout: {
        labelCol: {
          span: 6
        },
        wrapperCol: {
          span: 18
        }
      },
      // 查询参数
      queryParam: {
        beginDate: null, // 开始时间
        endDate: null, // 结束时间
        customerMobile: '', // 用户
        activeName: '' // 活动名称
      },
      loading: false, // 导出loading
      // 表头
      columns: [{
        title: '序号',
        dataIndex: 'no',
        width: 80,
        align: 'center'
      },
      {
        title: '参与抽奖时间',
        dataIndex: 'winTime',
        width: 200,
        align: 'center'
      },
      {
        title: '活动名称',
        dataIndex: 'activeName',
        width: 200,
        align: 'center'
      },
      {
        title: '用户账号',
        dataIndex: 'customerMobile',
        width: 200,
        align: 'center'
      },
      {
        title: '是否中奖',
        dataIndex: 'stateDictValue',
        width: 200,
        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 00:00:00')
          searchData.endDate = moment(this.time[1]).format('YYYY-MM-DD 23:59:59')
        } else {
          searchData.beginDate = ''
          searchData.endDate = ''
        }
        return getLuckyWinList(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: [],
      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]
      }
    },
    // 重置
    handleReset () {
      this.queryParam.beginDate = null
      this.queryParam.endDate = null
      this.time = []
      this.queryParam.customerMobile = ''
      this.queryParam.activeName = ''
      this.$refs.table.refresh(true)
    },
    // 导出
    handleExport () {
      const params = this.queryParam
      if (this.time && this.time.length) {
        params.beginDate = moment(this.time[0]).format('YYYY-MM-DD 00:00:00')
        params.endDate = moment(this.time[1]).format('YYYY-MM-DD 23:59:59')
      } 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.$confirm({
        title: '提示',
        content: '导出过程可能需要一段时间，且导出期间不可进行其他操作，确认要导出吗？',
        onOk: () => {
          this.loading = true
          // exportLuckyDrawWin(params).then(res => {
          //   this.loading = false
          //   this.download(res)
          // })
        },
        onCancel () {}
      })
    },
    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('YYYY-MM-DD')
      const a = moment(this.queryParam.beginDate).format('LL') + '-' + moment(this.queryParam.endDate).format('LL')
      console.log(a)
      const fname = a + '抽奖记录表'
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    }
  }
}
</script>
<style lang="less" scoped>
	.luckDrawRecord-table-page-search-wrapper {
		.luckDrawRecord-searchForm {
			.ant-form-inline .ant-form-item {
				width: 100%;
			}

			// 搜索框的下间距
			.ant-form-item {
				margin-bottom: 10px;
			}

			.handle-btn {
				margin-top: 4px;
				margin-bottom: 20px;
			}

			.serach-btn {
				margin-right: 10px;
			}
		}

		.export-btn {
			background-color: #ff9900;
			border-color: #ff9900;
			color: #fff;
		}

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