<template>
  <a-card :bordered="false" class="shopOrder-table-page-search-wrapper">
    <div class="shopOrder-searchForm table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="refresh">
        <a-row :gutter="24">
          <a-col :lg="6" :md="8" :xs="24" :sm="12">
            <a-form-item label="投放时间:" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <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="5" :md="8" :xs="24" :sm="12">
            <a-form-item label="用户账号" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input id="releaseRecordList-customerMobile" allowClear :maxLength="11" v-model=" queryParam.customerMobile" placeholder="请输入用户账号" />
            </a-form-item>
          </a-col>
          <a-col :lg="4" :md="8" :xs="24" :sm="12">
            <a-form-item label="投放类型" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select code="RUBBISH_TYPE" v-model="queryParam.rubbishType" allowClear placeholder="请选择投放类型" id="releaseRecordList-rubbishType"></v-select>
            </a-form-item>
          </a-col>
          <a-col :lg="5" :md="8" :xs="24" :sm="12">
            <a-form-item label="兑换乐豆" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <div class="input-number">
                <a-input-number id="releaseRecordList-inputNumber" v-model="queryParam.goldNumStart" :max="999999999" @change="onChange" />-
                <a-input-number id="inputNumber" v-model="queryParam.goldNumEnd" :max="999999999" @change="onChange" />
              </div>
            </a-form-item>
          </a-col>
          <a-col :lg="4" :md="8" :xs="24" :sm="12">
            <a-form-item label="设备类型" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select code="DEVICE_TYPE" v-model="queryParam.deviceType" allowClear placeholder="请选择设备类型" id="releaseRecordList-deviceType"></v-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :lg="6" :md="8" :xs="24" :sm="12">
            <a-form-item label="设备编号" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input id="releaseRecordList-srcDeviceCode" allowClear :maxLength="120" v-model=" queryParam.srcDeviceCode " placeholder="请输入设备编号" />
            </a-form-item>
          </a-col>
          <a-col :lg="5" :md="8" :xs="24" :sm="12">
            <a-form-item label="网点名称" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-select
                id="releaseRecordList-stationNo"
                placeholder="请选择网点名称"
                allowClear
                v-model="queryParam.stationNo"
                :showSearch="true"
                option-filter-prop="children"
                :filter-option="filterOption"
              >
                <a-select-option v-for="item in optionData" :key="item.stationNo" :value="item.stationNo">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="4" :md="8" :xs="24" :sm="12">
            <a-form-item label="称重值" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select
                code="DEVICE_WEIGHT_TAG"
                mode="multiple"
                v-model="queryParam.weightTagList"
                allowClear
                placeholder="请选择(可多选)"
                id="releaseRecordList-weightTagList"></v-select>
            </a-form-item>
          </a-col>
          <a-col :lg="5" :md="8" :xs="24" :sm="12">
            <a-form-item label="投放重量">
              <div class="input-number">
                <a-input-number id="releaseRecordList-inputNumber" v-model="queryParam.rubbishWeightStart" :max="999999999" @change="onChange" />-
                <a-input-number id="inputNumber" v-model="queryParam.rubbishWeightEnd" :max="999999999" @change="onChange" />
              </div>
            </a-form-item>
          </a-col>
          <a-col :lg="4" :md="8" :xs="24" :sm="12">
            <a-form-item label="投放方式" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select code="DELIVERY_WAY" v-model="queryParam.deliveryWay" allowClear placeholder="请选择投放方式" id="releaseRecordList-deliveryWay"></v-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :lg="6" :md="8" :xs="24" :sm="12">
            <a-form-item label="网点标签" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-select
                style="max-height: 50px;overflow: auto;margin-top: 3px;"
                id="releaseRecordList-labelNoList"
                placeholder="请选择网点标签"
                allowClear
                mode="multiple"
                v-model="queryParam.labelNoList"
                :showSearch="true"
                option-filter-prop="children"
                :filter-option="filterOption"
              >
                <a-select-option v-for="item in lableData" :key="item.labelNo" :value="item.labelNo">{{ item.labelName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="18" :md="8" :xs="24" :sm="12">
            <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
              <a-button class="handle-btn serach-btn" id="releaseRecordList-serach" type="primary" @click="refresh">查询</a-button>
              <a-button class="handle-btn serach-btn" style="margin-left: 8px" id="releaseRecordList-reset" @click="handleReset">重置</a-button>
              <a-button
                class="export-btn"
                id="releaseRecordList-export"
                style="margin-left: 8px"
                v-hasPermission="'B_exportDeliveryLog'"
                :loading="loading"
                @click="handleExport">导出</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 合计 -->
    <a-alert type="info" showIcon style="margin-bottom:15px">
      <div class="ftext" slot="message">共<span> {{ orderTotal }} </span>单，兑换乐豆<span> {{ amountTotal }} </span>个</div>
    </a-alert>
    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      bordered>
      <!-- 订单状态 -->
      <template slot="one" slot-scope="text, record">
        <span v-if="record.rubbishType=='CLOTHES'">{{ record.rubbishWeight }}</span>
        <span v-else>0</span>
      </template>
      <template slot="two" slot-scope="text, record">
        <span v-if="record.rubbishType=='PAPER'">{{ record.rubbishWeight }}</span>
        <span v-else>0</span>
        </span></template>
      <template slot="three" slot-scope="text, record">
        <span v-if="record.rubbishType=='PLASTIC'">{{ record.rubbishWeight }}</span>
        <span v-else>0</span>
      </template>
      <template slot="four" slot-scope="text, record">
        <span v-if="record.rubbishType=='METAL'">{{ record.rubbishWeight }}</span>
        <span v-else>0</span>
      </template>
      <template slot="five" slot-scope="text, record">
        <span v-if="record.rubbishType=='HARM'">{{ record.rubbishWeight }}</span>
        <span v-else>0</span>
      </template>
      <template slot="six" slot-scope="text, record">
        <span v-if="record.rubbishType=='MET_PLA'">{{ record.rubbishWeight }}</span>
        <span v-else>0</span>
      </template>
      <template slot="seven" slot-scope="text, record">
        <span v-if="record.rubbishType=='GLASS'">{{ record.rubbishWeight }}</span>
        <span v-else>0</span>
      </template>
      <template slot="eight" slot-scope="text, record">
        <span v-if="record.rubbishType=='RECYCLING'">{{ record.rubbishWeight }}</span>
        <span v-else>0</span>
      </template>
    </s-table>
  </a-card>

</template>

<script>
import { STable, VSelect } from '@/components'
import { getDeliveryLogList, getDeliveryLogTotal, stationList, exportDeliveryLog, numType } from '@/api/releaseRecord.js'
import { lableSeleteList } from '@/api/labelSetting.js'
import moment from 'moment'
import getDate from '@/libs/getDate.js'
export default {
  components: { STable, VSelect },
  data () {
    return {
      loading: false,
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 }
      },
      // 将默认当天时间日期回显在时间选择框中
      queryOrderDate: [
        moment(getDate.getRecentday().starttime, this.dateFormat),
        moment(getDate.getRecentday().endtime, this.dateFormat)
      ],
      dateFormat: 'YYYY-MM-DD',
      // 查询参数
      queryParam: {
        beginDate: null, // 开始时间
        endDate: null, // 结束时间
        customerMobile: '', //  用户手机
        srcDeviceCode: '', //  设备编号
        stationNo: undefined, // 网点名称
        deviceType: '', // 设备类型
        deliveryWay: '', // 投放方式
        rubbishType: '',
        goldNumStart: null, // 兑换最小值
        goldNumEnd: null, // 兑换最大值
        rubbishWeightStart: null, // 投放重量最小值
        rubbishWeightEnd: null, // 投放重量最小值
        weightTagList: [],
        labelNoList: []
      },
      optionData: [], // 网点名称数据
      lableData: [], // 网点标签数据
      orderTotal: 0,	// 总单数
      amountTotal: 0,	// 总金额
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '投放时间', dataIndex: 'deliveryTime', width: 200, align: 'center' },
        { title: '网点名称', dataIndex: 'stationName', width: 200, align: 'center' },
        { title: '网点标签', dataIndex: 'labelName', width: 200, align: 'center', customRender: text => { return text || '--' } },
        { title: '设备编号', dataIndex: 'srcDeviceCode', width: 200, align: 'center' },
        { title: '设备类型', dataIndex: 'deviceTypeDictValue', width: 200, align: 'center' },
        { title: '用户账号', dataIndex: 'customerMobile', width: 200, align: 'center' },
        { title: '投放方式', dataIndex: 'deliveryWayDictValue', width: 200, align: 'center' },
        { title: '本次兑换乐豆（个）', dataIndex: 'goldNum', width: 100, align: 'center' },
        { title: '内置各箱体投放重量（g）',
          children: [
            { title: '废旧衣物', width: 100, align: 'center', scopedSlots: { customRender: 'one' } },
            { title: '废旧纸张', width: 100, align: 'center', scopedSlots: { customRender: 'two' } },
            { title: '废旧塑料', width: 100, align: 'center', scopedSlots: { customRender: 'three' } },
            { title: '废旧金属', width: 100, align: 'center', scopedSlots: { customRender: 'four' } },
            { title: '有害垃圾', width: 100, align: 'center', scopedSlots: { customRender: 'five' } },
            { title: '废旧金属/塑料', width: 100, align: 'center', scopedSlots: { customRender: 'six' } },
            { title: '废旧玻璃', width: 100, align: 'center', scopedSlots: { customRender: 'seven' } },
            { title: '可回收物', width: 100, align: 'center', scopedSlots: { customRender: 'eight' } }
          ]
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const searchData = Object.assign(parameter, this.queryParam)
        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 getDeliveryLogList(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
            }
            this.getListTotal()
            return res.data
          }
        })
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.queryOrderDate = [
        moment(getDate.getRecentday().starttime, vm.dateFormat),
        moment(getDate.getRecentday().endtime, vm.dateFormat)
      ],
      // 查询参数
      vm.queryParam = {
        beginDate: null, // 开始时间
        endDate: null, // 结束时间
        customerMobile: '', //  用户手机
        srcDeviceCode: '', //  设备编号
        stationNo: undefined, // 网点名称
        deviceType: '', // 设备类型
        deliveryWay: '', // 投放方式
        goldNumStart: null, // 兑换最小值
        goldNumEnd: null, // 兑换最大值
        rubbishWeightStart: null, // 投放重量最小值
        rubbishWeightEnd: null, // 投放重量最小值
        weightTagList: [],
        labelNoList: []
      }
    })
  },
  mounted () {
    this.getStationList()
    this.getlableSeleteList()
  },
  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]
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 导出
    handleExport () {
      const params = this.queryParam
      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
      }
      // 判断两个时间段是否相差m个月  第二个参数指相差单位，第三个参数指是否返回浮点形式（小数）
      if (moment(params.endDate).diff(moment(params.beginDate), 'months', true) > 3) {
        this.$message.error('单次最多只能导出3个月的数据，请缩小查询区间后再进行导出！')
        return
      }
      this.loading = true
      exportDeliveryLog(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()
    },
    // 查询
    refresh () {
      const isTNull = this.queryParam.goldNumEnd === null
      const isTEmpty = this.queryParam.goldNumEnd === ''
      const isRNull = this.queryParam.rubbishWeightEnd === null
      const isREmpty = this.queryParam.rubbishWeightEnd === ''
      //  第一个为空（可为null可为空字符）第二个不为空
      //  第一个不为空第二个为空（可为null可为空字符）
      //  第一个大于第二个
      if ((this.queryParam.goldNumStart > this.queryParam.goldNumEnd) && !(isTNull || isTEmpty)) {
        this.$message.error('请输入正确的查询范围！')
        return
      }
      if ((this.queryParam.rubbishWeightStart > this.queryParam.rubbishWeightEnd) && !(isRNull || isREmpty)) {
        this.$message.error('请输入正确的查询范围！')
        return
      }
      this.queryParam.goldNumStart = this.queryParam.goldNumStart > 999999999 ? 999999999 : this.queryParam.goldNumStart
      this.queryParam.goldNumEnd = this.queryParam.goldNumEnd > 999999999 ? 999999999 : this.queryParam.goldNumEnd
      this.queryParam.rubbishWeightStart = this.queryParam.rubbishWeightStart > 999999999 ? 999999999 : this.queryParam.rubbishWeightStart
      this.queryParam.rubbishWeightEnd = this.queryParam.rubbishWeightEnd > 999999999 ? 999999999 : this.queryParam.rubbishWeightEnd
      this.$refs.table.refresh(true)
    },
    // 获取合作商数据
    getStationList () {
      stationList().then(res => {
        if (res.status == 200) {
          this.optionData = res.data || []
        }
      })
    },
    // 获取标签数据
    getlableSeleteList () {
      lableSeleteList().then(res => {
        if (res.status == 200) {
          this.lableData = res.data || []
        }
      })
    },
    // 合计
    getListTotal () {
	  const params = this.queryParam
      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 = ''
      }
      getDeliveryLogTotal(params).then(res => {
        if (res.status == 200) {
          if (res.data) {
            this.orderTotal = res.data.totalNum || 0
            this.amountTotal = res.data.goldNum || 0
          } else {
            this.orderTotal = 0
            this.amountTotal = 0
          }
        }
      })
    },
    // 重置
    handleReset () {
      this.queryOrderDate = [
        moment(getDate.getRecentday().starttime, this.dateFormat),
        moment(getDate.getRecentday().endtime, this.dateFormat)
      ]
      this.queryParam.customerMobile = ''
      this.queryParam.srcDeviceCode = ''
      this.queryParam.stationNo = undefined
      this.queryParam.deviceType = '' // 设备类型
      this.queryParam.goldNumStart = '' // 兑换最小值
      this.queryParam.goldNumEnd = '' // 兑换最大值
      this.queryParam.rubbishWeightStart = ''// 投放重量最小值
      this.queryParam.rubbishWeightEnd = '' // 投放重量最大值
      this.queryParam.deliveryWay = '' // 投放方式
      this.queryParam.rubbishType = ''
	    this.queryParam.weightTagList = []
      this.queryParam.labelNoList = []
      this.$refs.table.refresh(true)
    }
  }
}
</script>
<style lang="less" scoped>
  .shopOrder-table-page-search-wrapper{
    .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;
    }
    .actionBtn {
    	font-size: 20px;
    	padding: 0 10px;
    }
    .blue {
    	color: #1890FF;
    }
    .green {
    	color: #16b50e;
    }
    .red {
    	color: red;
    }
  }
</style>
