<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" :form="form" @keyup.enter.native="$refs.table.refresh(true)">
        <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" 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%" :disabledDate="disabledDate" v-model="queryOrderDate" format="YYYY-MM-DD"
                              :placeholder="['开始时间', '结束时间']" id="SettlementRecordsList-queryOrderDate" />
            </a-form-item> -->
			<a-form-item label="下单时间:" :label-col="{ span: 7 }" :wrapper-col="{ span: 17}">
			  <a-range-picker
			    style="width:100%"
			    id="releaseRecordList-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 ref="payStatus" code="SETTLE_STATUS_ALL" v-model="queryParam.orderFlag" 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}">
              <!-- <salesSearch ref="salesSearch" @salesChange="salesChange" placeholder="订单来源"></salesSearch> -->
              <a-select placeholder="请选择" allowClear v-model="queryParam.dataSourceNo" mode="multiple" :showSearch="true" option-filter-prop="children"
                        :filter-option="filterOption"  @change="handleChange">
                <a-select-option v-for="item in optionData" :key="item.salesChannelNo" :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" 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" v-model.trim="queryParam.vehicleNumber" 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" v-model.trim="queryParam.bundleName" placeholder="套餐名称" allowClear />
            </a-form-item>
          </a-col> -->

          <a-col :lg="6" :sm="12">
            <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
            <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
			<a-button style="margin-left: 8px" class="export-btn" @click="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>{{ 0 }}</span>单，收款金额<span>￥{{ 0 }}</span>元</div>
	</a-alert>
    <div class="card-container">
      <s-table ref="table" size="default" rowKey="id" bordered :columns="columns" :data="loadData">
        <span slot="action" slot-scope="text, record">
            <a-button type="primary"  style="margin: 5px;" @click="handleDetail(record)">详情</a-button>
            <!-- <span v-if="!$hasPermissions('CustomerBundleDetail_1')">--</span> -->
            </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 { completeDate } from '@/libs/tools.js'
import {
  STable,
  VSelect
} from '@/components'
import {
  listCustomerBundle,
  queryBankPayStatus,
  salesChannelList,
	countListBundle,
	exportBundle
} from '@/api/customerBundle'
// import salesSearch from '@/components/salesQuery/salesSearch'
export default {
  name: 'OrderList',
  components: {
    VSelect,
    STable
  },
  data () {
    return {
      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 = ''
        }
        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
          }
          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: '',
        beginDate: null,
        endDate: null,
        orderFlag: '',
        custMobile: '',
        bundleName: '',
        vehicleNumber: '',
        dataSourceNo: undefined
      },
      optionData: [],
      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
      },
	  {
	    title: '购买数量',
	    dataIndex: '',
	    align: 'center',
	    width: 100
	  },
      {
        title: '收款金额',
        dataIndex: 'totalAmount',
        width: 100,
        align: 'center'
      },
      {
        title: '订单状态',
        dataIndex: 'orderFlag',
        width: 100,
        align: 'center',
        customRender: (text) => {
          const payStatus = this.$refs.payStatus.getOptionDatas()
          if (payStatus) {
            if (_.find(payStatus, ['code', text])) {
              return _.find(payStatus, ['code', text]).dispName
            }
          }
          return text
        }
      },
	  {
	    title: '结算状态',
	    dataIndex: '',
	    width: 100,
	    align: 'center',
	    // customRender: (text) => {
	    //   const payStatus = this.$refs.payStatus.getOptionDatas()
	    //   if (payStatus) {
	    //     if (_.find(payStatus, ['code', text])) {
	    //       return _.find(payStatus, ['code', text]).dispName
	    //     }
	    //   }
	    //   return text
	    // }
	  },
      {
        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]
	  }
	},
    handleChange (value) {
      console.log(`selected ${value}`)
    },
    // handleBlur () {
    //   console.log('blur')
    // },
    // handleFocus () {
    //   console.log('focus')
    // },
    filterOption (input, option) {
	  return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
	  )
    },
		// 合计
		getTotal () {
		  const params = {
		    beginDate: this.searchForm.beginDate,
		    endDate: this.searchForm.endDate,
		    bundleName: this.searchForm.bundleName,
		    number: this.searchForm.number,
		    custMobile: this.searchForm.custMobile,
		    orderFlag: this.searchForm.orderFlag,
		    salesChannelSettleStatus: this.searchForm.salesChannelSettleStatus,
		    partner: this.searchForm.partner
		  }
		  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
		    }
		  })
		},
	// 查看详情、
	handleDetail(row){
		this.$router.push({
		  path: `/Service/PurchasedService/detail/${row.id}`
		})
	},
   //  getSalesListData () {
	  // salesChannelList().then(res => {
   //      if (res.status == 200) {
			//  this.optionData = res.data || []
			//  const obj = { salesChannelName: '自有', salesChannelNo: 0 }
			//   const a = this.optionData.unshift(obj)
			//   console.log(this.optionData, '---------------添加自有')
   //      }
	  // })
   //  },
    reloadRow (row) {
      queryBankPayStatus({
        tradeNo: row.tradeNo
      }).then(res => {
        console.log(res)
        if (res.status == 200) {
          this.$refs.table.refresh(true)
        }
      })
    },
		// 重置
    resetSearchForm () {
      this.queryOrderDate = undefined
	  this.queryOrderDate = [
	    moment(getDate.getRecentday().starttime, this.dateFormat),
	    moment(getDate.getRecentday().endtime, this.dateFormat)
	  ]
      this.queryParam = {
        number: '',
        beginDate: '',
        endDate: '',
        orderFlag: '',
        custMobile: '',
        bundleName: '',
        vehicleNumber: '',
        dataSourceNo: undefined
      }
      // this.$refs.salesSearch.setVal(undefined)
      this.$refs.table.refresh(true)
    },
    // 来源change
    salesChange (data) {
      this.queryParam.dataSourceNo = data ? data.salesChannelNo : ''
    },
	// 导出
	handleExport () {
	  const params = {
	    beginDate: this.queryParam.beginDate == null ? getDate.getToday().starttime : this.queryParam.beginDate,
	    endDate: this.queryParam.endDate == null ? getDate.getToday().endtime : this.queryParam.endDate,
	    bundleName: this.queryParam.bundleName,
	    number: this.queryParam.number,
	    custMobile: this.queryParam.custMobile,
	    orderFlag: this.queryParam.orderFlag,
	    vehicleNumber: this.queryParam.vehicleNumber,
	    dataSourceNo: this.queryParam.dataSourceNo
	  }
	  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()
	}
	
	// 导出
	// handleExport () {
	//   this.form.validateFields((err, values) => {
	//     if (!err) {
	//       this.queryParam = values.queryParam
	//       this.queryOrderDate = values.queryOrderDate
	//       this.queryParam.beginDate = moment(this.queryOrderDate[0]).format('YYYY-MM-DD')
	//       this.queryParam.endDate = moment(this.queryOrderDate[1]).format('YYYY-MM-DD')
	//       // 获取距开始日期3个月后的时间戳
	//       const tVal = getThreeMonthsAfter(this.queryParam.beginDate)
	//       // 获取结束时间时间戳
	//       const endVal = new Date(this.queryParam.endDate.replace(/-/g, '/'))
	//       if (endVal.valueOf() > tVal - 86400000) {
	//         return this.$message.warning('单次最多只能导出3个月的数据，请缩小查询区间后再进行导出！')
	//       }
	//       const params = _.cloneDeep(this.queryParam)
	//       let requestObj = null
	//       // 按核销服务量进行结算
	//       if (this.settleType == 'ITEM_VERIFY') {
	//         params.bundName = params.bundleName
	//         params.bizNum = params.orderBundleNo
	//         delete params.bundleName
	//         delete params.orderBundleNo
	//         requestObj = exportByItem
	//       } else {
	//         requestObj = exportByBundle
	//       }
	//       this.exportLoading = true
	//       exportBundle(params).then(res => {
	//         console.log(res, 'rrrrrrrrrrr')
	//         this.exportLoading = 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.resetSearchForm()
      // vm.getSalesListData()
    })
  }
}
</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>
