<template>
  <div style="padding:10px">
    <div v-if="powers.some((i) => i == '001')">
      <el-row style="margin-top:10px">
      <el-col :span="6" style="width: 363px;">
        <periodDatePickerActive
          :start="parmValue.start_day"
          :end="parmValue.end_day"
          :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>

        <el-table v-loading="loading" :data="tableData" size="mini" style="margin-top:10px">
         <el-table-column label="供应商" align="center">
           <el-table-column label="供应商名称" prop="supplierName" show-overflow-tooltip />
           <el-table-column label="是否开通供应商端" width="120px" prop="is_supplier" show-overflow-tooltip />
           <el-table-column label="负责人" min-width="90px" prop="person" show-overflow-tooltip />
         </el-table-column>

         <el-table-column label="竞价反馈" align="center">
           <el-table-column label="反馈单数量" prop="feed_num" show-overflow-tooltip />
           <el-table-column label="反馈总金额" prop="total_price" show-overflow-tooltip />
           <el-table-column label="反馈商品总数量" prop="good_num" show-overflow-tooltip />
         </el-table-column>

         <el-table-column label="平台类型订单总数" align="center">
           <el-table-column label="Toc平台" prop="toc" show-overflow-tooltip />
           <el-table-column label="Tob平台" prop="tob" show-overflow-tooltip />
         </el-table-column>
        </el-table>
    </div>

    <div v-else>
      <no-auth></no-auth>
    </div>
  </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 { table2 } from './columns'
import { mapGetters } from 'vuex'
import { utils, writeFile } from 'xlsx'
import dayjs from 'dayjs'

export default {
  name: 'SaleReport',
  components: {
    periodDatePickerActive
  },
  mixins: [mixinPage, resToken],
  computed: {
    ...mapGetters(['tablebtnSize', 'searchSize', 'size']),
    powers() {
      const tran =
        this.$store.getters.btnList.find((i) => i.menu_route == "reportTableTwo") || {};
      const { action } = tran ?? {};
      return action ?? [];
    }
  },
  data() {
    return {
    // 选中数组
      changeList: [],
      // 全局url
      fileUrl: urlConfig.baseURL,
      mapTemplateProperty: {
        供应商名称: 'supplierName',
        是否开通供应商端: 'is_supplier',
        负责人: 'person',
        反馈单数量: 'feed_num',
        反馈总金额: 'total_price',
        反馈商品总数量: 'good_num',
        Toc平台: 'toc',
        Tob平台: 'tob'
      },
      // loading
      loading: false,
      // 请求参数集合
      parmValue: {
        supplierNo: '',
        start_day: '', // 起始时间
        end_day: '', // 结束时间
        page: 1, // 页码
        size: 15 // 每页显示条数

      },
      // 表格 - 数据集合
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ['setcol']
      },
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0
      },
      // 表格表头 - 列参数
      table2: table2
    }
  },
  mounted() {
    this.parmValue.start_day = dayjs().subtract(0, 'day').format('YYYY-MM-DD')
    this.parmValue.end_day = dayjs().subtract(0, 'day').format('YYYY-MM-DD')
    this.searchList()
  },

  methods: {
    getDiffDay(date_1, date_2) {
      // 计算两个日期之间的差值
      let totalDays, diffDate
      const myDate_1 = Date.parse(date_1)
      const myDate_2 = Date.parse(date_2)
      // 将两个日期都转换为毫秒格式，然后做差
      diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值
      totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
      return totalDays // 相差的天数
    },
    // 初始化http请求
    async searchList() {
      if (!this.parmValue.start_day || !this.parmValue.end_day) {
        this.$message.warning('请选择时间区间')
        this.tableData = []
        return
      }

      const diffDays = this.getDiffDay(this.parmValue.start_day, this.parmValue.end_day)
      if (Math.abs(diffDays) > 31) {
        return this.$message.warning('数据时间间隔不能超过31天')
      }

      this.loading = true

      const res = await asyncRequest.fbbs({
        ...this.parmValue,
        supplierNo: Array.isArray(this.parmValue.supplierNo) ? this.parmValue.supplierNo[0] : this.parmValue.supplierNo
      })
      if (res && res.code === 0 && res.data) {
        this.tableData = res.data
      } 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
    },

    // 重置
    restSearch() {
      this.parmValue = {
        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(0, '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()
    },
    async supplierChange(e) {
      const { code, label } = e
      this.parmValue.supplierNo = code ? [code] : []
      this.searchList()
    },
    // 导出文件
    async download() {
      if (!this.parmValue.start_day || !this.parmValue.end_day) {
        this.$message.warning('请选择时间区间')
        this.tableData = []
        return
      }

      const diffDays = this.getDiffDay(this.parmValue.start_day, this.parmValue.end_day)
      if (Math.abs(diffDays) > 31) {
        return this.$message.warning('导出文件时间间隔不能超过31天')
      }

      const template = Object.keys(this.mapTemplateProperty)
      const data = this.tableData.map(tableItem => template.reduce((prev, currenKey) => ({
        ...prev,
        [currenKey]: tableItem[this.mapTemplateProperty[currenKey]]
      }), {}))

      const workBook = utils.book_new()
      const workSheet = utils.json_to_sheet(data)

      utils.book_append_sheet(workBook, workSheet, 'sheet')

      writeFile(workBook, '竞价单情况表.xlsx', {
        bookType: 'xlsx'
      })
    }
  }
}
</script>
 <style lang="scss" scoped>
.purchaseOrder {
// text-align: right;
}
</style>
