<template>
  <div class="app-container">
    <div>
      <el-form inline>
        <el-form-item label="日期" class="margin-lr-sm">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            @change="timePicked"
          />
        </el-form-item>

        <el-form-item v-if="param._Eq_GroupType == 0" label="客户" class="margin-lr-sm">
          <el-select
            v-model="param._Eq_CustomerId"
            placeholder="客户"
            clearable
            filterable
          >
            <el-option
              v-for="item in customers"
              :key="item.CustomerNumber"
              :label="`${item.CompanyName}(${item.CustomerNumber})`"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="param._Eq_GroupType == 1" label="派送渠道" class="margin-lr-sm">
          <el-select
            v-model="param._Eq_ChannelId"
            placeholder="派送渠道"
            clearable
            filterable
          >
            <el-option
              v-for="item in channels"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="param._Eq_GroupType == 2" label="业务员" class="margin-lr-sm">
          <el-select
            v-model="param._Eq_SalesmanUserId"
            placeholder="业务员"
            clearable
            filterable
          >
            <el-option
              v-for="item in users"
              :key="item.Name"
              :label="`${item.Name}`"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="分类方式" class="margin-lr-sm">
          <el-select v-model="param._Eq_GroupType" @change="groupTypeChanged">
            <el-option
              v-for="(item, idx) in groupTypes"
              :key="idx"
              :value="item.value"
              :label="item.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="汇总" class="margin-lr-sm">
          <el-switch v-model="param._Eq_GroupByTime" />
        </el-form-item>

        <el-button type="primary" :loading="loading" @click="doSearch">搜索</el-button>
        <el-button
          type="success"
          :loading="downloadLoading"
          @click="exportData"
        >导出</el-button>
      </el-form>
    </div>

    <div>
      <el-table v-loading="loading" :data="dataList">
        <el-table-column
          v-if="param._Eq_GroupType == 0"
          prop="CustomerNumber"
          label="客户编号"
        />
        <el-table-column
          v-if="param._Eq_GroupType == 0"
          prop="CustomerCompanyName"
          label="公司名称"
        />
        <el-table-column
          v-if="param._Eq_GroupType == 1"
          prop="ChannelName"
          label="渠道名称"
        />
        <el-table-column
          v-if="param._Eq_GroupType == 2"
          prop="SalesmanUserName"
          label="业务员名称"
        />

        <el-table-column
          v-if="param._Eq_GroupType == 2"
          prop="CustomerName"
          label="客户名称"
        />

        <el-table-column prop="CreateOrderTime" label="下单时间" />
        <el-table-column prop="TotalCount" label="订单数量" />
        <el-table-column prop="TotalWeight" label="订单总重（KG）" />
      </el-table>
    </div>
    <div>
      <el-pagination
        :page-sizes="[100, 200, 300, 400]"
        :current-page="param.PageIndex"
        :page-size="param.PageSize"
        background
        layout="prev, pager, next ,total ,jumper,sizes,slot "
        :total="param.total"
        @current-change="pagerSerach"
      />
    </div>
  </div>
</template>
<script>
import { _getDeliverChannel, _getAllUsers, _getCustomers } from '@/api/baseInfo'
import {
  GetOrderCountStatistics,
  DownOrderCountStatistics
} from '@/api/orderCountStatistics'
import { getToken } from '@/utils/auth'

export default {
  name: 'OrderCountStatistics',
  data() {
    return {
      downloadLoading: false,
      loading: false,
      timeRange: null,
      channels: [],
      customers: [],
      users: [],
      groupTypes: [
        { name: '按客户', value: 0 },
        { name: '按渠道', value: 1 },
        { name: '按业务员', value: 2 }
      ],

      dataList: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      param: {
        _Eq_GroupByTime: false,
        _Eq_CustomerId: null,
        _Eq_ChannelId: null,
        _Eq_GroupType: 0,
        _LeE_CreateOrderTime: null,
        _GrE_CreateOrderTime: null,
        PageIndex: 1,
        PageSize: 100,
        total: 0
      }
    }
  },
  created() {
    _getDeliverChannel().then((resp) => {
      this.channels = resp
    })
    _getCustomers().then((resp) => {
      this.customers = resp
    })
    _getAllUsers().then((resp) => {
      this.users = resp
    })
    this.param.PageIndex = 1
  },
  methods: {
    exportData() {
      this.downloadLoading = true
      var url = `${process.env.VUE_APP_BASE_API}/OrderCountStatistics/DownOrderCountStatistics`
      var x = new XMLHttpRequest()
      x.open('POST', url, true)
      x.responseType = 'blob'
      x.setRequestHeader('content-type', 'application/json')
      x.setRequestHeader('token', getToken())

      x.onload = (e) => {
        this.downloading = false
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a')
        a.href = url
        a.download = `下单量统计.xls`
        a.click()
        this.downloadLoading = false
      }

      const param = this.param
      param.QueryParamer = []
      for (var d in param) {
        if (d.indexOf('_') >= 0) {
          if (param[d] != null && param[d] != undefined && param[d] + '' != '') {
            var o = d.split('_')[1]
            var q = d.split('_')[2]
            param.QueryParamer.push({ Filed: q, Value: param[d], Method: o })
          }
        }
      }
      const data = JSON.stringify(this.param)
      x.send(data)
    },
    groupTypeChanged(e) {
      this.dataList = []
    },
    timePicked(e) {
      this.param._GrE_CreateOrderTime = e[0]
      this.param._LeE_CreateOrderTime = e[1]
    },

    doSearch() {
      this.param.PageIndex = 1
      this.search()
    },

    search() {
      const data = this.param
      this.loading = true
      const that = this
      GetOrderCountStatistics(data).then(
        (resp) => {
          this.dataList = resp.Result
          that.loading = false
          that.param.total = resp.TotalCount
          that.param.PageIndex = resp.PageIndex
        },
        () => {
          that.loading = false
        }
      )
    },
    pagerSerach(p) {
      this.param.PageIndex = p
      this.search()
    }
  }
}
</script>
<style scoped>
  .margin-lr-sm{
    margin-left: 20px;
    margin-right: 20px;
  }
</style>
