<template>
  <a-card :bordered="false">
    <!-- 搜索条件 -->
    <div class="orderCenter-searchForm">
      <a-form ref="searchForm" @keyup.enter.native="handleSearch">
        <a-row :gutter="48">
          <a-col :span="6">
            <a-form-item label="核销时间" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-range-picker
                v-model="time"
                id="VerificationRecords-time"
                :format="dateFormat"
                :placeholder="['开始时间','结束时间']"
                :disabledDate="disabledDate"
                @change="onChange" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="核销门店" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-select placeholder="请选择" allowClear v-model="searchForm.usedStoreId" id="VerificationRecords-usedStoreId">
                <a-select-option v-for="item in storeOptionData" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="客户信息" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-input v-model.trim="searchForm.queryWord" placeholder="请输入手机号" allowClear id="VerificationRecords-queryWord"/>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="套餐名称" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-input v-model.trim="searchForm.bundName" placeholder="请输入" allowClear id="VerificationRecords-bundName"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="48">
          <a-col :span="6">
            <a-form-item label="关联订单号" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-input v-model.trim="searchForm.orderNo" placeholder="请输入" allowClear id="VerificationRecords-orderNo"/>
            </a-form-item>
          </a-col>
          <a-col :span="18">
            <a-button style="margin-right: 10px;" type="primary" @click="handleSearch" id="VerificationRecords-handleSearch">查询</a-button>
            <a-button type="" @click="handleRest" id="VerificationRecords-handleRest">重置</a-button>
            <a-button type="" :loading="loading" class="export-btn" @click="handleExport" id="VerificationRecords-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 || 0 }}</span>单,结算金额:<span>¥{{ paymentAmountTotal || 0 }}</span>元</div>
    </a-alert>
    <!-- 列表 -->
    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      bordered>
      <!-- 订单编号 -->
      <template slot="num" slot-scope="text, record">
        <p>{{ record.bizNum }}</p>
        <p>{{ record.orderNo }}</p>
      </template>
      <!-- 客户信息 -->
      <template slot="userInfo" slot-scope="text, record">
        <!-- <p>{{ text }}<br>{{ record.vehicleNumber ? record.vehicleNumber : '--' }}</p> -->
        <div>
          <span v-if="record.custMobile">{{ record.custMobile }}</span>
          <span v-if="record.vehicleNum">{{ record.vehicleNum }}</span>
        </div>
        <span v-if="!record.custMobile && !record.vehicleNum">--</span>
      </template>
    </s-table>
  </a-card>
</template>
<script>
import {
  STable,
  VSelect
} from '@/components'
import getDate from '@/libs/getDate.js'
import { completeDate } from '@/libs/tools.js'
import {
  getVerificationRecordsList, getVerificationRecordsListTotal, settlementRecordsExport, getStoreList
} from '@/api/SetmealSales.js'
import moment from 'moment'
export default {
  name: 'OrderCenter',
  components: {
    STable,
    VSelect
  },
  data () {
    return {
      // 查询参数
      searchForm: {
        beginDate: null, // 创建的开始时间
        endDate: null, // 创建的结束时间
        usedStoreId: undefined, // 核销门店
        orderNo: '', // 单号
        queryWord: '', // 客户信息
        bundName: '' // 套餐名称
      },
      loading: false, // 导出loading
      orderTotal: '', // 合计开单数量
      paymentAmountTotal: '', // 合计实收金额
      storeOptionData: [], // 门店数据
      // 将默认当天时间日期回显在时间选择框中
      time: [
        moment(getDate.getToday().starttime, this.dateFormat),
        moment(getDate.getToday().endtime, this.dateFormat)
      ],
      dateFormat: 'YYYY-MM-DD',
      nowBeginDate: '',
      columns: [{
        title: '序号',
        dataIndex: 'no',
        width: 60,
        align: 'center'
      },
      {
        title: '核销时间',
        dataIndex: 'usedTime',
        width: 100,
        align: 'center'
      },
      {
        title: '核销单号/关联订单号',
        scopedSlots: { customRender: 'num' },
        width: 150,
        align: 'center'
      },
      {
        title: '核销服务名称',
        dataIndex: 'bundItemName',
        width: 150,
        align: 'center'
      },
      {
        title: '客户信息',
        scopedSlots: { customRender: 'userInfo' },
        width: 150,
        align: 'center'
      },
      {
        title: '套餐名称',
        dataIndex: 'bundName',
        width: 150,
        align: 'center'
      },
      {
        title: '结算金额(¥)',
        dataIndex: 'salesChannelSettleAmount',
        width: 100,
        align: 'center',
        customRender: function (text) {
		  return (text || 0) + '元'
        }
      }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
		  const _this = this
        _this.searchForm.beginDate == null ? this.searchForm.beginDate = getDate.getToday().starttime : null
        _this.searchForm.endDate == null ? this.searchForm.endDate = getDate.getToday().endtime : null
        return getVerificationRecordsList(Object.assign(parameter, _this.searchForm)).then(res => {
          if (res.status == 200) {
            _this.orderTotal = res.data.count
            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
            }
            return res.data
          }
        })
      }
    }
  },
  methods: {
    moment,
    // 不可选日期
    disabledDate (date, dateStrings) {
      return date && date.valueOf() > Date.now()
    },
    // 创建时间change
    onChange (dates, dateStrings) {
      if ((dates, dateStrings)) {
        this.searchForm.beginDate = dateStrings[0]
        this.searchForm.endDate = dateStrings[1]
      }
    },
    // 获取门店数据
    getStoreListData () {
      getStoreList({
        pageNo: 1,
        pageSize: 1000
      }).then(res => {
        if (res.status == 200) {
          this.storeOptionData = res.data.list || []
        }
      })
    },
    // 合计
    getTotal () {
      const params = {
        beginDate: this.searchForm.beginDate,
        endDate: this.searchForm.endDate,
        usedStoreId: this.searchForm.usedStoreId,
        orderNo: this.searchForm.orderNo,
        queryWord: this.searchForm.queryWord,
        bundName: this.searchForm.bundName
      }
      params.beginDate == null ? params.beginDate = getDate.getToday().starttime : null
      params.endDate == null ? params.endDate = getDate.getToday().endtime : null
      getVerificationRecordsListTotal(params).then(res => {
        console.log(res, '--------')
        if (res.status == 200) {
          this.paymentAmountTotal = res.data || 0
        }
      })
    },
    // 查询
    handleSearch () {
      this.$refs.table.refresh(true)
      this.getTotal()
    },
    // 重置
    handleRest () {
      this.nowBeginDate = getDate.getToday().starttime
      this.searchForm.beginDate = getDate.getToday().starttime
      this.searchForm.endDate = getDate.getToday().endtime
      this.time = [
        moment(getDate.getToday().starttime, this.dateFormat),
        moment(getDate.getToday().endtime, this.dateFormat)
      ]
      this.searchForm.usedStoreId = undefined
      this.searchForm.orderNo = ''
      this.$refs.table.refresh()
      this.getTotal()
    },
    // 导出
    handleExport () {
      const params = {
        beginDate: this.searchForm.beginDate == null ? getDate.getToday().starttime : this.searchForm.beginDate,
        endDate: this.searchForm.endDate == null ? getDate.getToday().endtime : this.searchForm.endDate,
        usedStoreId: this.searchForm.usedStoreId,
        orderNo: this.searchForm.orderNo,
        queryWord: this.searchForm.queryWord,
        bundName: this.searchForm.bundName
      }
	  if (!params.beginDate && !params.endDate) {
		 this.$message.error('请先选择需要导出的核销时间段再进行导出!')
		  return
	  }
      if (!completeDate(params.beginDate, params.endDate, 3)) {
        this.$message.error('单次最多只能导出3个月的数据,请缩小查询区间后再进行导出!')
        return
      }
	  this.loading = true
      settlementRecordsExport(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
      console.log(fname, '111111')
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.handleRest()
      vm.getStoreListData()
    })
  }
}
</script>
<style lang="less">
	.orderCenter-searchForm {

		// 搜索框的下间距
		.ant-form-item {
			margin-bottom: 10px;
		}
	}
  .export-btn{
    background-color: #ff9900;
    border-color: #ff9900;
    color: #fff;
    margin-left: 10px;
  }
	// 合计
	.ftext span {
		color: #fa8c16;
		font-weight: bold;
	}
</style>