<template>
  <div>
    <ex-table
      v-loading="loading"
      :table="table"
      :data="tableData"
      :columns="table5"
      :page="pageInfo"
      :size="size"
      @page-curr-change="handlePageChange"
      @page-size-change="handleSizeChange"
      @screen-reset="
        pageInfo.curr = 1;
        parmValue.page = 1;
        searchList();
      "
      @screen-submit="
        pageInfo.curr = 1;
        parmValue.page = 1;
        searchList();
      "
      @selection="selection_change"
    >
      <template #table-header="{}">
        <div style="width: 100%">
          <el-row style="padding: 0 0 0 80px">

            <el-col :span="6" style="width: 363px;">
              <periodDatePickerActive
                :start="parmValue.start_day"
                :end="parmValue.end_day"
                :placeholder="'竞价'"
                :width="'165px'"
                :size="searchSize"
                @timeReturned="time"
              />
            </el-col>

            <el-col :span="4" style="width: 350px">
              <search-supplier
                :size="'mini'"
                :value="parmValue.supplierNo"
                :disabled="false"
                :placeholder="'供应商名称'"
                :names="parmValue.supplierName"
                :is-detail="true"
                :no-disabled="true"
                @searchChange="supplierChange"
              />
            </el-col>

            <el-col :span="4" style="width: 66px; float: right">
              <el-button type="primary" style="margin-left:30px;" :size="searchSize" class="fr" @click="download">
                导出
              </el-button>
            </el-col>
            <el-col :span="3" style="width: 66px; float: right">
              <el-button
                :size="searchSize"
                type="primary"
                style="float: right; margin-left: 5px"
                @click="searchList"
              >
                刷新
              </el-button>
            </el-col>
            <el-col :span="4" style="width: 66px; float: right">
              <el-button
                type="warning"
                class="fr"
                :size="searchSize"
                @click="restSearch"
              >
                重置
              </el-button>
            </el-col>
          </el-row>
        </div>
      </template>

      <template #order_type="{scope}">
        {{ xs_order_type_options.find(({id}) => id === String(scope.row.order_type)).label }}
      </template>

      <template #order_source="{scope}">
        {{ xs_order_source_options.find(({id}) => id === String(scope.row.order_source)).label }}
      </template>

      <template #status="{scope}">
        {{ statusOptions.find(({value}) => value === String(scope.row.status)).label }}
      </template>

      <template #platform_type="{scope}">
        {{ String(scope.row.platform_type) === '1' ? 'ToB' : String(scope.row.platform_type) === '2' ? 'ToC' : '--' }}
      </template>
    </ex-table>
  </div>

</template>
<script>
import mixinPage from '@/mixins/elPaginationHandle'
import resToken from '@/mixins/resToken'
import urlConfig from '@/apis/url-config'
import asyncRequest from '@/apis/service/reportQuery/newReport'
import periodDatePickerActive from '../period-date-picker/main.vue'
import { xs_order_type_options, xs_order_source_options } from '@/assets/js/statusList'
import { table5 } from './columns'
import { mapGetters } from 'vuex'
import dayjs from 'dayjs'
import companyHelper from '@/mixins/companyHelper'

export default {
  name: 'SaleReport',
  components: {
    periodDatePickerActive
  },
  mixins: [mixinPage, resToken, companyHelper],
  computed: {
    ...mapGetters(['tablebtnSize', 'searchSize', 'size'])

  },
  data() {
    return {
      xs_order_type_options,
      xs_order_source_options,
      // 选中数组
      changeList: [],
      // 全局url
      fileUrl: urlConfig.baseURL,
      // loading
      loading: false,
      // 请求参数集合
      parmValue: {
        supplierNo: [],
        start_day: '', // 起始时间
        end_day: '', // 结束时间
        // is_export:0,//是否导出0/1

        page: 1, // 页码
        size: 15 // 每页显示条数

      },
      statusOptions: [
        { value: '0', label: '待发货' },
        { value: '1', label: '待发货完成' },
        { value: '2', label: '发货已完成' },
        { value: '3', label: '订单已取消' }
      ],
      // 表格 - 数据集合
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ['setcol']
      },
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0
      },
      // 表格表头 - 列参数
      table5: table5
    }
  },
  mounted() {
    this.parmValue.start_day = dayjs().subtract(0, 'day').format('YYYY-MM-DD')
    this.parmValue.end_day = dayjs().subtract(-1, 'day').format('YYYY-MM-DD')
    this.searchList()
  },

  methods: {
    async supplierChange(e) {
      const { code, label } = e
      this.parmValue.supplierNo = code ? [code] : []
      this.searchList()
    },
    // 初始化http请求
    async searchList() {
      if (
        (this.parmValue.start_day !== '' && this.parmValue.end_day === '') ||
      (this.parmValue.start_day === '' && this.parmValue.end_day !== '')
      ) {
        this.$message.warning('时间区间不完整！')
        return
      }

      const start_day = new Date(this.parmValue.start_day).valueOf()
      const end_day = new Date(this.parmValue.end_day).valueOf()
      const flag = end_day - start_day > 31 * 24 * 60 * 60 * 1000

      if (this.parmValue.start_day != '' && this.parmValue.end_day != '') {
        if (flag) {
          this.$message.warning('筛选的时间区间不能超过31天')
          return
        }
      }

      this.loading = true
      const res = await asyncRequest.orderoutbk({
        ...this.parmValue,
        supplierNo: Array.isArray(this.parmValue.supplierNo) ? this.parmValue.supplierNo[0] : this.parmValue.supplierNo,
        companyNo: this.currentCompany
      })
      if (res && res.code === 0 && res.data) {
        this.tableData = res.data.list
        this.pageInfo.total = Number(res.data.count)
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout()
      } else {
        this.$message.warning(res.message)
        this.tableData = []
        this.pageInfo.total = 0
      }
      this.loading = false
    },

    company_idsearchChange(e) {
      const { code } = e
      this.parmValue.supplierNo = code || ''
      this.searchList()
    },

    // 重置
    restSearch() {
      this.parmValue = {
        supplierNo: [],
        start_day: '', // 新建起始时间
        end_day: '', // 新建结束时间
        // is_export:0,//是否导出0/1
        page: 1, // 页码
        size: 15 // 每页显示条数
      }

      this.parmValue.start_day = dayjs().subtract(0, 'day').format('YYYY-MM-DD')
      this.parmValue.end_day = dayjs().subtract(-1, 'day').format('YYYY-MM-DD')
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0
      }
      this.searchList()
    },

    // 时间函数
    async time(e) {
      this.parmValue.start_day = e.startTime || ''
      this.parmValue.end_day = e.endTime || ''
      if (
        (this.parmValue.start_day !== '' && this.parmValue.end_day === '') ||
      (this.parmValue.start_day === '' && this.parmValue.end_day !== '')
      ) {
        this.$message.warning('时间区间不完整！')
        return
      }

      this.pageInfo.curr = 1
      this.parmValue.page = 1
      await this.searchList()
    },

    // 选中触发函数
    selection_change(e) {
      const { list } = e
      // 选中的数组集合
      this.changeList = list.length > 0 ? JSON.parse(JSON.stringify(list)) : []
    },
    // 导出文件
    async download() {
    // if(this.changeList.length<=0){
    //   this.$message.warning("请选择有效数据")
    //   return;
    // }
      const model = JSON.parse(JSON.stringify({
        ...this.parmValue,
        companyNo: this.currentCompany,
        supplierNo: Array.isArray(this.parmValue.supplierNo) ? this.parmValue.supplierNo[0] : this.parmValue.supplierNo
      }))
      delete model['page']
      delete model['size']
      // model.is_export = 1;
      const start_day = new Date(this.parmValue.start_day).valueOf()
      const end_day = new Date(this.parmValue.end_day).valueOf()
      const flag = end_day - start_day > 31 * 24 * 60 * 60 * 1000
      if (this.parmValue.start_day != '' && this.parmValue.end_day != '') {
        if (flag) {
          this.$message.warning('导出文件的时间区间不能超过31天')
          return
        }
      } else {
        this.$message.warning('请选择导出文件的时间区间')
        return
      }
      if (!this.loading) {
        this.loading = true
        const httpType = `aplication/zip`
        axios({
          method: 'post',
          url: this.fileUrl + 'admin/OrderOutExport',
          responseType: 'blob',
          data: model,
          headers: {
            Accept: httpType
          }
        })
          .then((res) => {
            if (res && res.status == 200 && res.data) {
              const url = window.URL.createObjectURL(
                new Blob([res.data], {
                  type: httpType
                })
              )
              const link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              const excelName = '待库管发货.zip'
              link.setAttribute('download', excelName)
              document.body.appendChild(link)
              link.click()
              link.remove()
              window.URL.revokeObjectURL(url) // 释放掉blob对象
              this.$message.success(`导出成功！`)
              setTimeout(() => {
                this.loading = false
              }, 500)
            } else {
              this.$message.error(res.data.message)
              setTimeout(() => {
                this.loading = false
              }, 500)
            }
          })
          .catch((error) => {
            console.log(error)
            this.loading = false
          })
      }
    }
  }
}
</script>
 <style lang="scss" scoped>
.purchaseOrder {
// text-align: right;
}
</style>

