<template>
  <a-card :bordered="false" class="purchasedSetmeal-wrap">
    <!-- 搜索条件 -->
    <div class="purchasedSetmeal-searchForm">
      <a-form ref="searchForm" @keyup.enter.native="$refs.table.refresh(true)">
        <a-row :gutter="48">
          <a-col :span="6">
            <a-form-item label="下单时间" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-range-picker
                id="purchasedSetmeal-time"
                v-model="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-input v-model.trim="searchForm.number" id="purchasedSetmeal-number" placeholder="请输入订单号" allowClear />
            </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" id="purchasedSetmeal-queryWord" placeholder="请输入手机号/车牌号" allowClear />
            </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.bundleName" id="purchasedSetmeal-bundleName" placeholder="请输入套餐名称" allowClear />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="单据状态" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <v-select
                v-model="searchForm.orderFlag"
                ref="orderFlag"
                id="purchasedSetmeal-status"
                code="PAY_STATUS"
                placeholder="请选择单据状态"
                allowClear></v-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="结算状态" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <v-select
                v-model="searchForm.salesChannelSettleStatus"
                ref="salesChannelSettleStatus"
                id="purchasedSetmeal-status"
                code="SETTLE_STATUS_ALL"
                placeholder="请选择结算状态"
                allowClear></v-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-button class="handle-btn serach-btn" id="purchasedSetmeal-serach" type="primary" @click="handleSearch">查询</a-button>
            <a-button class="handle-btn" type="" id="purchasedSetmeal-reset" @click="handleReset">重置</a-button>
            <a-button class="handle-btn export-btn" id="purchasedSetmeal-export" type="" :loading="loading" @click="handleExport">导出</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 新建 -->
    <div class="table-operator"><a-button type="primary" id="purchasedSetmeal-buy" icon="plus" @click="goBuy()">购买套餐</a-button></div>
    <!-- 合计 -->
    <div class="total">
      <a-icon type="info-circle" class="iconImg" />
      <strong>总计：</strong><span v-model="orderTotal">{{ orderTotal || 0 }} 单</span>
      <strong style="margin-left: 15px;">收款金额：</strong><span v-model="totalAmounts">{{ totalAmounts || 0 }} 元</span>
    </div>
    <!-- 列表 -->
    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      bordered>
      <!-- 客户信息 -->
      <p slot="custInfo" slot-scope="text, record">
        <span v-if="record.custMobile || record.vehicleNumber">{{ record.custMobile }} / {{ record.vehicleNumber }}</span>
        <span v-else>--</span>
      </p>
      <!-- 单据状态 -->
      <span slot="orderFlag" slot-scope="text, record">{{ $refs.orderFlag.getNameByCode(record.orderFlag) }}</span>
      <!-- 结算状态 -->
      <span slot="salesChannelSettleStatus" slot-scope="text, record">{{ $refs.salesChannelSettleStatus.getNameByCode(record.salesChannelSettleStatus) }}</span>
      <!-- 操作 -->
      <span slot="action" slot-scope="text, record">
        <a-button type="primary" id="purchasedSetmeal-look" @click="seeDetail(record)">详情</a-button>
      </span>
    </s-table>
    <!-- 查看详情弹窗 -->
    <setmeal-detail-modal :openModal="openDetailModal" :setmealId="detailId" @close="openDetailModal=false" />
  </a-card>
</template>

<script>
import { STable, VSelect } from '@/components'
import getDate from '@/libs/getDate.js'
import { completeDate } from '@/libs/tools.js'
import moment from 'moment'
import SetmealDetailModal from './SetmealDetailModal.vue'
import { listCustomerBundle, exportBundle, countListBundle } from '@/api/customerBundle.js'
export default {
  name: 'PurchasedSetmeal',
  components: { STable, VSelect, SetmealDetailModal },
  data () {
    return {
      // 查询参数
      searchForm: {
        beginDate: null, // 开始时间
        endDate: null, // 结束时间
        bundleName: '', // 套餐名称
        number: '', // 订单号
        queryWord: '', // 客户信息
        orderFlag: '', // 单据状态
        salesChannelSettleStatus: '' // 结算状态
      },
      loading: false, // 导出loading
      orderTotal: '', // 合计开单数量
      totalAmounts: '', // 合计收款金额
      openDetailModal: false, // 查看详情弹窗 默认关闭
      detailId: null, // 初始化id
      // 将默认当天时间日期回显在时间选择框中
      time: [
        moment(getDate.getToday().starttime, this.dateFormat),
        moment(getDate.getToday().endtime, this.dateFormat)
      ],
      dateFormat: 'YYYY-MM-DD',
      columns: [
        { title: '序号', dataIndex: 'no', width: 60, align: 'center' },
        { title: '订单号', dataIndex: 'number', width: 100, align: 'center' },
        { title: '下单时间', dataIndex: 'orderDate', width: 100, align: 'center' },
        { title: '套餐名称', dataIndex: 'bundleName', width: 100, align: 'center' },
        { title: '客户信息', scopedSlots: { customRender: 'custInfo' }, width: 100, align: 'center' },
        { title: '收款金额(￥)', dataIndex: 'payedAmount', width: 80, align: 'center' },
        { title: '单据状态', scopedSlots: { customRender: 'orderFlag' }, width: 80, align: 'center' },
        { title: '结算状态', scopedSlots: { customRender: 'salesChannelSettleStatus' }, width: 80, align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 100, align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.searchForm.beginDate == null ? this.searchForm.beginDate = getDate.getToday().starttime : null
        this.searchForm.endDate == null ? this.searchForm.endDate = getDate.getToday().endtime : null
        return listCustomerBundle(Object.assign(parameter, this.searchForm)).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.getTotal()
            return res.data
          }
        })
      }
    }
  },
  methods: {
    moment,
    // 不可选日期
    disabledDate (date, dateStrings) {
      return date && date.valueOf() > Date.now()
    },
    //  购买套餐
    goBuy () {
      this.$router.push({ path: '/SetmealSales/BuySetmeal' })
    },
    // 创建时间change
    onChange (dates, dateStrings) {
      if ((dates, dateStrings)) {
        this.searchForm.beginDate = dateStrings[0]
        this.searchForm.endDate = dateStrings[1]
      }
    },
    // 合计
    getTotal () {
      const params = {
        beginDate: this.searchForm.beginDate,
        endDate: this.searchForm.endDate,
        bundleName: this.searchForm.bundleName,
        number: this.searchForm.number,
        queryWord: this.searchForm.queryWord,
        orderFlag: this.searchForm.orderFlag,
        salesChannelSettleStatus: this.searchForm.salesChannelSettleStatus
      }
      params.beginDate == null ? params.beginDate = getDate.getToday().starttime : null
      params.endDate == null ? params.endDate = getDate.getToday().endtime : null
      countListBundle(params).then(res => {
        if (res.status == 200) {
          if (res.data) {
            this.orderTotal = res.data.cnt || 0
            this.totalAmounts = res.data.totalAmounts || 0
          } else {
            this.orderTotal = 0
            this.totalAmounts = 0
          }
        } else {
          this.orderTotal = 0
          this.totalAmounts = 0
        }
      })
    },
    // 查看详情--跳转到对应的详情页
    seeDetail (record) {
      // 将当前行的id传递给详情页
      this.detailId = String(record.id)
      this.openDetailModal = true
    },
    // 查询
    handleSearch () {
      this.$refs.table.refresh()
    },
    // 重置
    handleReset () {
      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.bundleName = ''
      this.searchForm.number = ''
      this.searchForm.queryWord = ''
      this.searchForm.orderFlag = null
      this.searchForm.salesChannelSettleStatus = null
      this.$refs.table.refresh(true)
    },
    // 导出
    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,
        bundleName: this.searchForm.bundleName,
        number: this.searchForm.number,
        queryWord: this.searchForm.queryWord,
        orderFlag: this.searchForm.orderFlag,
        salesChannelSettleStatus: this.searchForm.salesChannelSettleStatus
      }
      if (!params.beginDate && !params.endDate) {
        this.$message.error('请先选择需要导出的下单时间区间再进行导出！')
        return
      }
      // 判断两个时间段是否相差m个月
      if (!completeDate(params.beginDate, params.endDate, 3)) {
        this.$message.error('单次最多只能导出3个月的数据，请缩小查询区间后再进行导出！')
        return
      }
      this.loading = true
      exportBundle(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()
    }
  }
}
</script>
<style lang="less">
  .purchasedSetmeal-wrap{
    .purchasedSetmeal-searchForm {
    	// 搜索框的下间距
    	.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;
      }
    }
    .table-operator{
      margin: 18px 0 30px;
    }
    // 合计
    .total {
    	margin: 15px 0 25px;
    	width: 100%;
    	background-color: #e6f7ff;
    	border: 1px solid #91d5ff;
    	padding: 8px 15px 8px 27px;
    	border-radius: 4px;
    	.iconImg {
    		color: #1890FF;
    		margin-right: 10px;
    	}
    }
  }
</style>
