<template>
  <a-card :bordered="false" class="winRecord-table-page-search-wrapper">
    <div class="winRecord-searchForm">
      <a-form layout="inline" v-bind="formItemLayout" @keyup.enter.native="$refs.table.refresh(true)">
        <a-row :gutter="20">
          <a-col :span="5">
            <a-form-item label="中奖时间" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-range-picker
                id="winRecord-time"
                v-model="time"
                :format="dateFormat"
                :placeholder="['开始时间','结束时间']"
                :disabledDate="disabledDate"
                @change="onChange" />
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="奖品" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input id="winRecord-prizeDesc" allowClear v-model="queryParam.prizeDesc" placeholder="请输入奖品名称" />
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="用户" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input id="winRecord-customerMobile" allowClear v-model="queryParam.customerMobile" placeholder="请输入用户账号" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="状态" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select
                v-model="queryParam.state"
                ref="orderState"
                id="winRecord-state"
                code="PRIZE_WIN_STATE"
                placeholder="请选择状态"
                allowClear></v-select>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-button class="handle-btn serach-btn" id="winRecord-btn-serach" type="primary" @click="$refs.table.refresh(true)">查询</a-button>
            <a-button class="handle-btn serach-btn" type="" id="winRecord-btn-reset" @click="handleReset">重置</a-button>
            <a-button class="export-btn" id="winRecord-btn--export" :loading="loading" v-hasPermission="'B_winingRecord_export'" @click="handleExport">导出</a-button>
          </a-col>
        </a-row>
        <a-row :gutter="20">
          <a-col :span="5">
            <a-form-item label="活动名称" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input id="winRecord-activeName" allowClear v-model="queryParam.activeName" placeholder="请输入活动名称" />
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="奖品类型" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select
                v-model="queryParam.prizeType"
                ref="orderState"
                id="winRecord-prizeType"
                code="PRIZE_TYPE"
                placeholder="请选择奖品类型"
                allowClear></v-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      bordered>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <a-icon
          type="rocket"
          id="winRecord-sendGood"
          title="发货"
          v-if="record.prizeType=='GOODS'&&record.state=='WAIT_SEND_EXPRESS'&&$hasPermissions('B_winingRecord_sendGood')"
          class="actionBtn icon-blues"
          @click="sendGood(record)" />
        <a-icon
          type="eye"
          id="winRecord-handleView"
          title="详情"
          v-else-if="record.prizeType=='GOODS'&&record.state=='FINISH'&&$hasPermissions('B_winingRecord_view')"
          class="actionBtn icon-green"
          @click="handleView(record)" />
        <span v-else>--</span>
      </template>
      <template slot="prizeDesc" slot-scope="text, record">
        {{ record.prizeType == 'GOODS' ? text : (text+'乐豆') }}
      </template>
    </s-table>
    <!-- 发货 -->
    <GoodsLogistics :openModal="openModal" :itemId="itemId" @submit="handleSubmit" @close="openModal=false" />
    <!-- 发货详情 -->
    <GoodsLogisticsDetail :openModal="openDetailModal" :itemId="itemId" @close="openDetailModal=false" />
  </a-card>

</template>

<script>
import {
  STable,
  VSelect
} from '@/components'
import GoodsLogistics from './GoodsLogistics.vue'
import GoodsLogisticsDetail from './GoodsLogisticsDetail.vue'
import getDate from '@/libs/getDate.js'
import moment from 'moment'
import {
  getLuckyWinList,
  sendExpress,
  exportLuckyDrawWin
} from '@/api/luckyDraw.js'
export default {
  name: 'WinRecord',
  components: {
    STable,
    VSelect,
    GoodsLogistics,
    GoodsLogisticsDetail
  },
  data () {
    return {
      openModal: false, //  是否填写物流信息
      openDetailModal: false, //  是否查看物流信息
      formItemLayout: {
        labelCol: {
          span: 6
        },
        wrapperCol: {
          span: 18
        }
      },
      // 查询参数
      queryParam: {
        beginDate: null, // 开始时间
        endDate: null, // 结束时间
        prizeDesc: '', //  奖品
        customerMobile: '', // 用户
        state: '', // 状态
        activeName: '', // 活动名称
        prizeType: '' // 奖品类型
      },
      itemId: '', // 发货列id
      luckyDrawWinNo: '', // 中奖奖品编码
      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: 'prizeTypeDictValue',
        width: 200,
        align: 'center'
      },
      {
        title: '奖品',
        dataIndex: 'prizeDesc',
        scopedSlots: {
          customRender: 'prizeDesc'
        },
        width: 200,
        align: 'center'
      },
      {
        title: '中奖用户',
        dataIndex: 'customerMobile',
        width: 200,
        align: 'center'
      },
      {
        title: '状态',
        dataIndex: 'stateDictValue',
        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 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: [
        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]
      }
    },
    // 重置
    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.activeName = ''
      this.queryParam.prizeType = ''
      this.queryParam.prizeDesc = ''
      this.queryParam.state = ''
      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) > 1) {
        this.$message.error('单次最多只能导出1个月的数据，请缩小查询区间后再进行导出！')
        return
      }
      this.$confirm({
        title: '提示',
        content: '导出过程可能需要一段时间，且导出期间不可进行其他操作，确认要导出吗？',
        onOk: () => {
          this.loading = true
          exportLuckyDrawWin(params).then(res => {
            this.loading = false
            this.download(res)
          })
        },
        onCancel () {}
      })
      // this.loading = true
      // exportLuckyDrawWin(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('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()
    },
    //  查看物流详情
    handleView (row) {
      this.itemId = row.id
      this.openDetailModal = true
    },
    // 发货
    sendGood (row) {
      this.itemId = row.id
      this.luckyDrawWinNo = row.luckyDrawWinNo
      this.openModal = true
    },
    // 提交发货
    handleSubmit (data) {
      console.log(data, 'ppppppp')
      const params = data
      params.luckyDrawWinNo = this.luckyDrawWinNo
      sendExpress(params).then(res => {
        if (res.status == 200) {
          this.openModal = false
          this.$message.success(res.message)
          this.$refs.table.refresh(true)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
	.winRecord-table-page-search-wrapper {
		.winRecord-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>
