<template>
  <div class="app-container">
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item label="日期范围" prop="dateRange">
        <div style="display: flex; align-items: center;">
          <el-date-picker v-model="queryParams.dateRange" type="datetimerange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]">
          </el-date-picker>
          <div style="margin-left: 10px;">
            <el-button size="mini" @click="setDateRange('today')">今日</el-button>
            <el-button size="mini" @click="setDateRange('yesterday')">昨日</el-button>
            <el-button size="mini" @click="setDateRange('week')">本周</el-button>
            <el-button size="mini" @click="setDateRange('month')">本月</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="物料编号" prop="partNumber">
        <el-input v-model="queryParams.partNumber" placeholder="请输入物料编号" clearable />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable />
      </el-form-item>
      <el-form-item label="操作人" prop="operator">
        <el-input v-model="queryParams.operator" placeholder="请输入操作人" clearable />
      </el-form-item>
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table :data="dataList" v-loading="loading" ref="table" border header-cell-class-name="el-table-header-cell"
      highlight-current-row>
      <el-table-column type="index" width="50" align="center" />
      <el-table-column prop="partnumber" label="物料编号" align="center" />
      <el-table-column prop="description" label="物料名称" align="center" />
      <el-table-column prop="changePackage" label="箱数" align="center" />
      <el-table-column prop="changeQuantity" label="产品数" align="center" />
      <el-table-column prop="createdBy" label="操作人" align="center" />
    </el-table>

    <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script>
import { getOutboundReportByPage } from '@/api/materialManagement/mmOutboundReport'
import * as ExcelJS from 'exceljs'
import { saveAs } from 'file-saver'

export default {
  name: 'mmDailyOutboundReport',
  data() {
      // 默认日期范围为今日零点到今日结束
      const startOfDay = this.$dayjs().startOf('day').toDate()
      const endOfDay = this.$dayjs().endOf('day').toDate()

      return {
        loading: false,
        showSearch: true,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          dateRange: [startOfDay, endOfDay],
          partNumber: '',
          materialName: '',
          operator: '',
          source: ''
        },
      columns: [],
      total: 0,
      dataList: [],
      queryRef: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      // 构造符合后端要求的查询参数
      const params = {
        ...this.queryParams,
        startTime: this.queryParams.dateRange ? this.$dayjs(this.queryParams.dateRange[0]).format('YYYY-MM-DD HH:mm:ss') : undefined,
        endTime: this.queryParams.dateRange ? this.$dayjs(this.queryParams.dateRange[1]).format('YYYY-MM-DD HH:mm:ss') : undefined,
        partNumber: this.queryParams.partNumber,
        materialName: this.queryParams.materialName,
        operator: this.queryParams.operator,
        source: this.queryParams.source
      }
      // 删除不需要的参数
      delete params.dateRange

      // 调用API获取数据
      getOutboundReportByPage(params).then((res) => {
        if (res.code == 200) {
          this.dataList = res.data.result || []
          this.total = res.data.totalNum || 0
          this.loading = false
        } else {
          this.dataList = []
          this.total = 0
          this.loading = false
        }
      }).catch(() => {
        this.dataList = []
        this.total = 0
        this.loading = false
      })
    },
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置查询操作
    resetQuery() {
      this.resetForm("queryRef")
      // 重置为当月25日到本月25日
      const startOfMonth = this.$dayjs().subtract(1, 'month').date(25).toDate()
      const endOfMonth = this.$dayjs().date(25).toDate()
      this.queryParams.dateRange = [startOfMonth, endOfMonth]
      this.queryParams.partNumber = ''
      this.queryParams.materialName = ''
      this.queryParams.operator = ''
      this.queryParams.source = ''
      this.handleQuery()
    },

    // 设置日期范围
    setDateRange(type) {
      let start, end
      switch (type) {
        case 'today':
          // 今日
          start = this.$dayjs().startOf('day').toDate()
          end = this.$dayjs().endOf('day').toDate()
          break
        case 'yesterday':
          // 昨日
          start = this.$dayjs().subtract(1, 'day').startOf('day').toDate()
          end = this.$dayjs().subtract(1, 'day').endOf('day').toDate()
          break
        case 'week':
          // 本周
          start = this.$dayjs().startOf('week').toDate()
          end = this.$dayjs().endOf('week').toDate()
          break
        case 'month':
          // 本月(上月25日到本月25日)
          start = this.$dayjs().subtract(1, 'month').date(25).toDate()
          end = this.$dayjs().date(25).toDate()
          break
        default:
          // 默认为本月
          start = this.$dayjs().subtract(1, 'month').date(25).toDate()
          end = this.$dayjs().date(25).toDate()
      }
      this.queryParams.dateRange = [start, end]
      this.handleQuery()
    },
    // 导出数据
    async handleExport() {
      try {
        // 检查日期范围是否为空
        if (!this.queryParams.dateRange || this.queryParams.dateRange.length !== 2 ||
          !this.queryParams.dateRange[0] || !this.queryParams.dateRange[1]) {
          this.$modal.msgError('请选择日期范围')
          return
        }

        // 显示加载提示
        this.$modal.loading('正在导出数据，请稍候...')

        // 获取所有数据
        const allData = await this.getAllData()

        // 格式化日期范围用于文件名
        const startDate = this.$dayjs(this.queryParams.dateRange[0]).format('YYYY-MM-DD')
        const endDate = this.$dayjs(this.queryParams.dateRange[1]).format('YYYY-MM-DD')
        const fileName = `出库报表_${startDate}_${endDate}.xlsx`

        // 创建工作簿
        const workbook = new ExcelJS.Workbook()
        const worksheet = workbook.addWorksheet('出库报表')

        // 设置列标题和样式
         const columns = [
           { header: '物料编号', key: 'partnumber', width: 20 },
           { header: '物料名称', key: 'description', width: 30 },
           { header: '箱数', key: 'changePackage', width: 15 },
           { header: '数量', key: 'changeQuantity', width: 15 },
           { header: '操作人', key: 'createdBy', width: 15 },
           { header: '操作时间', key: 'createdTime', width: 20 }
         ]
         worksheet.columns = columns

         // 设置标题行样式
         const headerRow = worksheet.getRow(1)
         headerRow.font = { bold: true }
         headerRow.alignment = { horizontal: 'center' }

        // 添加数据行
        allData.forEach(item => {
          worksheet.addRow({
            partnumber: item.partnumber,
            description: item.description,
            changePackage: item.changePackage,
            changeQuantity: item.changeQuantity,
            createdBy: item.createdBy,
            createdTime: item.createdTime
          })
        })

        // 生成Excel文件
        const buffer = await workbook.xlsx.writeBuffer()
        const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })

        // 下载文件
        saveAs(blob, fileName)

        // 隐藏加载提示
        this.$modal.closeLoading()
      } catch (error) {
        // 隐藏加载提示
        this.$modal.closeLoading()
        this.$modal.msgError('导出失败: ' + error.message)
      }
    },

    // 获取所有数据用于导出
    async getAllData() {
      return new Promise((resolve) => {
        // 显示加载提示
        this.$message({
          message: '正在准备导出数据，请稍候...',
          type: 'info',
          duration: 0 // 不自动关闭
        })

        // 构造查询参数
        const params = {
          ...this.queryParams,
          startTime: this.queryParams.dateRange ? this.$dayjs(this.queryParams.dateRange[0]).format('YYYY-MM-DD HH:mm:ss') : undefined,
          endTime: this.queryParams.dateRange ? this.$dayjs(this.queryParams.dateRange[1]).format('YYYY-MM-DD HH:mm:ss') : undefined,
          partNumber: this.queryParams.partNumber,
          materialName: this.queryParams.materialName,
          operator: this.queryParams.operator,
          source: this.queryParams.source
        }
        delete params.dateRange

        // 分页获取所有数据
        const allResults = []
        const fetchPage = (pageNum) => {
          getOutboundReportByPage({ ...params, pageNum, pageSize: 1000 }).then((res) => {
            if (res.code == 200) {
              const results = res.data.result || []
              allResults.push(...results)

              // 如果还有更多数据，继续获取下一页
              if (allResults.length < res.data.totalNum) {
                fetchPage(pageNum + 1)
              } else {
                // 关闭加载提示
                this.$message.closeAll()
                resolve(allResults)
              }
            } else {
              // 关闭加载提示
              this.$message.closeAll()
              this.$message({
                message: '获取导出数据失败',
                type: 'error'
              })
              resolve([])
            }
          }).catch(() => {
            // 关闭加载提示
            this.$message.closeAll()
            this.$message({
              message: '获取导出数据失败',
              type: 'error'
            })
            resolve([])
          })
        }

        // 开始获取第一页数据
        fetchPage(1)
      })
    }
  }
}
</script>

<style scoped>
/* 可以添加一些自定义样式 */
</style>