<template>
  <div>
    <ex-table
      v-loading="loading"
      :table="table"
      :data="tableData"
      :columns="table23"
      :size="size"
      no-pagination
      @page-curr-change="handlePageChange"
      @page-size-change="handleSizeChange"
      @screen-reset="
        searchList
      "
      @screen-submit="
        searchList
      "
      @selection="selection_change"
    >
      <template #table-header="{}">
        <div style="width: 100%">
          <el-row style="width: 100%; padding: 0 0 0 80px">
            <el-col :span="6" style="width: 443px">
              <periodDatePickerActive
                :start="parmValue.start_day"
                :end="parmValue.end_day"
                :width="'205px'"
                picker-type="month"
                :size="searchSize"
                @timeReturned="time"
              />
            </el-col>

            <el-col :span="4" style="margin-right:10px">
              <el-select
                v-model="parmValue.flag"
                style="width:100%"
                :size="searchSize"
                @change="searchList"
              >
                <el-option value label="全部" />
                <el-option value="1" label="开通账号的供应商" />
                <el-option value="2" label="未开通账号的供应商" />
              </el-select>
            </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-row>

          <el-row style="margin-top:10px">
            <el-col :span="4" style="margin-right:10px">
              <el-input
                v-model="parmValue.supplierNo"
                :size="searchSize"
                placeholder="供应商编码"
                @blur=" searchList()"
              />
            </el-col>

            <el-col :span="4" style="margin-right:10px">
              <el-input
                v-model="parmValue.supplier_name"
                :size="searchSize"
                placeholder="供应商名称"
                @blur="searchList()"
              />
            </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 #name="{ scope }">
        <span>{{ Array.isArray(scope.row.person) ? scope.row.person.join(",") : scope.row.person }}</span>
      </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/saleReport'
import periodDatePickerActive from '../period-date-picker/main.vue'
import { table23 } from './columns'
import { mapGetters } from 'vuex'
import { xs_order_type_options } from '@/assets/js/statusList'
import * as dayjs from 'dayjs'

export default {
  name: 'PurchaseOrder',
  components: {
    periodDatePickerActive
  },
  mixins: [mixinPage, resToken],
  computed: {
    ...mapGetters(['tablebtnSize', 'searchSize', 'size'])
  },
  data() {
    return {
      // 选中数组
      changeList: [],
      // 全局url
      fileUrl: urlConfig.baseURL,
      // loading
      loading: false,
      // 请求参数集合
      parmValue: {
        supplier_name: '',
        supplierNo: '',
        start_day: dayjs(this.getStartDate()).format('YYYY-MM-DD'), // 起始时间
        end_day: dayjs(new Date()).format('YYYY-MM-DD'), // 结束时间
        flag: ''
      },
      // 表格 - 数据集合
      tableData: [],
      xs_order_type_options,
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ['setcol']
      },
      // 表格表头 - 列参数
      table23
    }
  },
  mounted() {
    this.searchList()
  },

  methods: {
    // 初始化http请求
    async searchList() {
      if (!this.parmValue.start_day || !this.parmValue.end_day) {
        this.$message.warning('请选择时间区间')
        this.tableData = []
        return
      }

      this.loading = true
      const { code, data, message } = await asyncRequest.popm(this.parmValue)
      if (code === 0) {
        // const { list, count } = data;
        const list = Object.keys(data).reduce((prev, currentKey) => ([...prev, data[currentKey]]), [])
        // const totalItem = list.shift()
        // list.push(totalItem)
        this.tableData = list
      } else if (code >= 100 && code <= 104) {
        await this.logout()
      } else {
        this.tableData = []
      }
      this.loading = false
    },
    // 重置
    restSearch() {
      this.parmValue = {
        start_day: dayjs(this.getStartDate()).format('YYYY-MM-DD'), // 起始时间
        end_day: dayjs(new Date()).format('YYYY-MM-DD'), // 结束时间
        supplier_name: '',
        supplierNo: '',
        flag: '',
        page: 1, // 页码
        size: 15 // 每页显示条数
      }
      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
      }

      if (!this.diffDays(30)) {
        this.$message.warning('时间区间不能超过30天')
        return
      }

      await this.searchList()
    },
    // 选中触发函数
    selection_change(e) {
      const { list } = e
      // 选中的数组集合
      this.changeList = list.length > 0 ? JSON.parse(JSON.stringify(list)) : []
    },
    // getTimeParam() {
    //   const { start_day: start, end_day: end } = this.parmValue;

    //   if (!start || !end) {
    //     return {};
    //   }

    //   const start_date_chunks = start.split("-");
    //   const end_date_chunks = end.split("-");

    //   start_date_chunks[2] = "01";

    //   const [year, month] = end_date_chunks;
    //   const end_last_day = new Date(year, month, 0).getDate();
    //   end_date_chunks[2] = end_last_day;

    //   return {
    //     start_day: start_date_chunks.join("-"),
    //     end_day: end_date_chunks.join("-")
    //   };
    // },
    getStartDate() {
      const myDate = new Date()
      myDate.setDate(myDate.getDate() - 29)
      return myDate
    },
    diffDays(days) {
      const step = 24 * 3600 * 1000
      const sDay = new Date(this.parmValue.start_day).valueOf()
      const eDay = new Date(this.parmValue.end_day).valueOf()
      let isok = true

      if (eDay - sDay > step * days) {
        isok = false
      }

      return isok
    },
    // 导出文件
    async download() {
      if (
        (this.parmValue.start_day !== '' && this.parmValue.end_day === '') ||
        (this.parmValue.start_day === '' && this.parmValue.end_day !== '')
      ) {
        this.$message.warning('时间区间不完整！')
        return
      }

      if (!this.diffDays(30)) {
        this.$message.warning('时间区间不能超过30天')
        return
      }

      const model = JSON.parse(JSON.stringify(this.parmValue))
      if (!this.loading) {
        this.loading = true
        const httpType = `aplication/zip`
        axios({
          method: 'post',
          url: this.fileUrl + 'admin/popme',
          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>
