<template>
  <a-card :bordered="false">
    <v-select v-show="false" ref="orderFlag" code="PAY_STATUS" placeholder="请选择订单状态" allowClear></v-select>
    <div class="table-page-search-wrapper">
      <a-form layout="inline" :form="form" @keyup.enter.native="refresh">
        <a-row :gutter="48">
          <a-col :lg="6" :sm="12">
            <a-form-item label="订单编号:" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-input class="full-width" id="PurchasedServiceList-number" v-model.trim="queryParam.number" placeholder="订单编号" allowClear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :sm="12">
            <a-form-item label="下单时间:" :label-col="{ span: 7 }" :wrapper-col="{ span: 17}">
              <a-range-picker
                style="width:100%"
                id="PurchasedServiceList-queryOrderDate"
                :disabledDate="disabledDate"
                v-model="queryOrderDate"
                :format="dateFormat"
                :placeholder="['开始时间', '结束时间']" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :sm="12">
            <a-form-item label="结算状态:" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <v-select
                code="SETTLE_STATUS_ALL"
                id="PurchasedServiceList-salesChannelSettleStatus"
                ref="salesChannelSettleStatus"
                v-model="queryParam.salesChannelSettleStatus"
                allowClear></v-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :sm="12">
            <a-form-item label="销售合作商" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-select
                id="PurchasedServiceList-dataSourceNo"
                allowClear
                option-filter-prop="children"
                placeholder="请选择销售合作商"
                v-model="queryParam.dataSourceNo">
                <a-select-option v-for="(item,index) in dataSourceNoList" :key="index" :value="item.salesChannelNo">{{ item.salesChannelName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="48">
          <a-col :lg="6" :sm="12">
            <a-form-item label="客户信息" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-input
                class="full-width"
                id="PurchasedServiceList-custMobile"
                v-model.trim="queryParam.custMobile"
                :maxLength="11"
                placeholder="客户信息"
                allowClear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :sm="12">
            <a-form-item label="服务名称" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
              <a-input class="full-width" id="PurchasedServiceList-bundleName" v-model.trim="queryParam.bundleName" placeholder="服务名称" allowClear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :sm="12">
            <a-button type="primary" @click="refresh" :disabled="disabled" id="PurchasedServiceList-search">查询</a-button>
            <a-button style="margin-left: 8px" :disabled="disabled" @click="resetSearchForm" id="PurchasedServiceList-resetSearchForm">重置</a-button>
            <a-button style="margin-left: 8px" class="export-btn" @click="handleExport" id="PurchasedServiceList-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>￥{{ totalAmounts || 0 }}</span>元</div>
    </a-alert>
    <div class="card-container">
      <s-table
        ref="table"
        size="default"
        rowKey="id"
        bordered
        :columns="columns"
        :data="loadData">
        <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" style="margin: 5px;" @click="handleDetail(record)" id="PurchasedServiceList-handleDetail">详情</a-button>
          </a-button>
        </span>
        <template slot="userInfo" slot-scope="text, record">
          <p>{{ text }}<br>{{ record.vehicleNumber ? record.vehicleNumber : '--' }}</p>
        </template>
      </s-table>
    </div>
  </a-card>
</template>
<script>
import moment from 'moment'
import getDate from '@/libs/getDate.js'
import {
  STable,
  VSelect
} from '@/components'
import {
  salesChannelList
} from '@/api/FinancialManagement'
import {
  listCustomerBundle,
  queryBankPayStatus,
  countListBundle,
  exportBundle
} from '@/api/customerBundle'
export default {
  name: 'OrderList',
  components: {
    VSelect,
    STable
  },
  data () {
    return {
      disabled: false,
      loadData: parameter => {
        const searchData = Object.assign(parameter, this.queryParam, {
          freeChoiceFlag: 1
        })
        console.log(this.queryOrderDate, 'this.queryOrderDate')
        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 = ''
        }
        this.disabled = true
        return listCustomerBundle(searchData).then(res => {
          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.disabled = false
          return res.data
        })
      },
      form: this.$form.createForm(this, {
        name: 'CustomerBundleList'
      }),
      // 将默认时间日期回显在时间选择框中
      queryOrderDate: [
        moment(getDate.getRecentday().starttime, this.dateFormat),
        moment(getDate.getRecentday().endtime, this.dateFormat)
      ],
      dateFormat: 'YYYY-MM-DD',
      queryParam: {
        number: '', // 订单编号
        bundleName: '', // 服务名称
        beginDate: null,
        endDate: null,
        custMobile: '', // 用户信息
        dataSourceNo: undefined, // 合作商
        salesChannelSettleStatus: '' // 结算状态
      },
      dataSourceNoList: [],
      orderTotal: '', // 订单总数
      totalAmounts: '',
      columns: [{
        title: '序号',
        dataIndex: 'no',
        width: 60,
        align: 'center'
      },
      {
        title: '订单编号',
        dataIndex: 'number',
        width: 150,
        align: 'center'
      },
      {
        title: '销售合作商',
        dataIndex: 'salesChannelName',
        width: 150,
        align: 'center',
        customRender: function (text) {
          return (text || '--')
        }
      },
      {
        title: '下单时间',
        dataIndex: 'orderDate',
        width: 150,
        align: 'center'
      },
      {
        title: '客户信息',
        dataIndex: 'custMobile',
        width: 150,
        align: 'center',
        scopedSlots: {
          customRender: 'userInfo'
        }
      },
      {
        title: '服务名称',
        dataIndex: 'bundleName',
        align: 'center',
        width: 100,
        customRender: function (text) {
          return (text || '--')
        }
      },
      {
        title: '购买数量',
        dataIndex: 'cnt',
        align: 'center',
        width: 100,
        customRender: function (text) {
          return (text || '--')
        }
      },
      {
        title: '收款金额',
        dataIndex: 'payedAmount',
        width: 100,
        align: 'center'
      },
      {
        title: '订单状态',
        dataIndex: 'orderFlag',
        width: 100,
        align: 'center',
        scopedSlots: {
          customRender: 'orderFlag'
        }
      },
      {
        title: '结算状态',
        dataIndex: '',
        width: 100,
        align: 'center',
        scopedSlots: {
          customRender: 'salesChannelSettleStatus'
        }
      },
      {
        title: '操作',
        width: 100,
        align: 'center',
        scopedSlots: {
          customRender: 'action'
        }
      }
      ]
    }
  },
  methods: {
    // 禁止不可选日期
    disabledDate (current) {
      return current && current > moment().endOf('day')
    },
    // 创建时间change
    onChange (dates, dateStrings) {
      if ((dates, dateStrings)) {
        this.queryParam.beginDate = dateStrings[0]
        this.queryParam.endDate = dateStrings[1]
      }
    },
    //  获取渠道商下的合作商信息
    getSalesChannel () {
      salesChannelList().then(res => {
        if (res.status == 200) {
          this.dataSourceNoList = res.data
        } else {
          this.dataSourceNoList = []
        }
      })
    },
    handleChange (value) {
      console.log(`selected ${value}`)
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 合计
    getTotal () {
      const params = {
        beginDate: this.queryParam.beginDate,
        endDate: this.queryParam.endDate,
        bundleName: this.queryParam.bundleName,
        number: this.queryParam.number,
        custMobile: this.queryParam.custMobile,
        dataSourceNo: this.queryParam.dataSourceNo,
        salesChannelSettleStatus: this.queryParam.salesChannelSettleStatus,
        freeChoiceFlag: 1
      }
      params.beginDate == null ? params.beginDate = getDate.getRecentday().starttime : null
      params.endDate == null ? params.endDate = getDate.getRecentday().endtime : null
      countListBundle(params).then(res => {
        if (res.status == 200) {
          if (res.data) {
            this.orderTotal = res.data.cnt || 0
            this.totalAmounts = res.data.payedAmount || 0
          } else {
            this.orderTotal = 0
            this.totalAmounts = 0
          }
        } else {
          this.orderTotal = 0
          this.totalAmounts = 0
        }
      })
    },
    // 查看详情、
    handleDetail (row) {
      this.$router.push({
        path: `/Service/PurchasedService/detail/${row.id}`
      })
    },
    reloadRow (row) {
      queryBankPayStatus({
        tradeNo: row.tradeNo
      }).then(res => {
        console.log(res)
        if (res.status == 200) {
          this.$refs.table.refresh(true)
        }
      })
    },
    // 查询
    refresh () {
      this.$refs.table.refresh(true)
      this.getTotal()
    },
    // 重置
    resetSearchForm () {
      this.queryParam.beginDate = getDate.getRecentday().starttime
      this.queryParam.endDate = getDate.getRecentday().endtime
      this.queryOrderDate = [
        moment(getDate.getRecentday().starttime, this.dateFormat),
        moment(getDate.getRecentday().endtime, this.dateFormat)
      ]
      this.queryParam = {
        dataSourceNo: '',
        custMobile: '',
        bundleName: '',
        dataSourceNo: undefined,
        salesChannelSettleStatus: '',
        freeChoiceFlag: 1
      }
      this.refresh()
    },
    // 导出
    handleExport () {
      const params = {
        bundleName: this.queryParam.bundleName,
        number: this.queryParam.number,
        custMobile: this.queryParam.custMobile,
        dataSourceNo: this.queryParam.dataSourceNo,
        salesChannelSettleStatus: this.queryParam.salesChannelSettleStatus,
        freeChoiceFlag: 1
      }
      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
      }
      // 判断两个时间段是否相差1个月  第二个参数指相差单位，第三个参数指是否返回浮点形式（小数）
      if (moment(params.endDate).diff(moment(params.beginDate), 'months', true) > 1) {
        this.$message.error('单次最多只能导出1个月的数据，请缩小查询区间后再进行导出！')
        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()
    }
  },
  mounted () {
    this.getSalesChannel()
    this.getTotal()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.queryParam.beginDate = getDate.getRecentday().starttime
      vm.queryParam.endDate = getDate.getRecentday().endtime
      vm.queryOrderDate = [
        moment(getDate.getRecentday().starttime, this.dateFormat),
        moment(getDate.getRecentday().endtime, this.dateFormat)
      ]
      vm.queryParam = {
        dataSourceNo: '',
        custMobile: '',
        bundleName: '',
        dataSourceNo: undefined,
        salesChannelSettleStatus: '',
        freeChoiceFlag: 1
      }
    })
  }
}
</script>

<style lang="less">
	.table-page-search-wrapper {
		.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>
