<template>
  <div>
    <el-form :inline="true" :model="queryParams" class="mb-4">
      <el-form-item label="开始日期">
        <el-date-picker v-model="queryParams.datetimeStart" type="date" value-format="YYYY-MM-DD"/>
      </el-form-item>
      <el-form-item label="结束日期">
        <el-date-picker v-model="queryParams.datetimeEnd" type="date" value-format="YYYY-MM-DD"/>
      </el-form-item>
      <el-button type="primary" @click="getList">查询</el-button>
      <el-button @click="resetQuery">重置</el-button>
    </el-form>

    <el-row :gutter="10" style="margin-bottom: 16px;">
      <el-col :span="24">
        <el-upload :before-upload="beforeUpload" :show-file-list="false" style="display: inline-block; margin: 0 8px;">
          <el-button type="primary">导入</el-button>
        </el-upload>
        <el-button type="success" @click="handleExport">导出</el-button>
        <el-button @click="openColDialog">列设置</el-button>
      </el-col>
    </el-row>

    <el-dialog v-model="colDialog" title="选择展示列">
      <div>
        <strong>饲喂来源：</strong>
        <el-checkbox-group v-model="selectedFeed">
          <el-checkbox v-for="f in allCols.feed" :key="f" :label="f">{{ f }}</el-checkbox>
        </el-checkbox-group>
      </div>
      <div style="margin-top:1em">
        <strong>销售去向：</strong>
        <el-checkbox-group v-model="selectedSale">
          <el-checkbox v-for="s in allCols.sale" :key="s" :label="s">{{ s }}</el-checkbox>
        </el-checkbox-group>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="applyCols">确认</el-button>
          <el-button @click="colDialog = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-table :data="rows" border style="margin-top:16px">
      <!-- 前面的固定列 -->
      <el-table-column prop="datetime" label="日期"/>
      <el-table-column prop="num" label="羊数"/>
      <el-table-column prop="colostSheep" label="初乳羊"/>
      <el-table-column prop="commercialIntake" label="商乳入库"/>
      <el-table-column prop="antiIntake" label="抗乳入库"/>
      <el-table-column prop="colostIntake" label="初乳入库"/>
      <el-table-column prop="intakeTotal" label="入库小计"/>
      <el-table-column prop="commercialTest" label="商乳实验用奶"/>
      <el-table-column prop="colostTest" label="初乳实验用奶"/>
      <el-table-column prop="transferCommercial" label="商乳调拨出库"/>
      <el-table-column prop="transferAnti" label="抗乳调拨出库"/>
      <el-table-column prop="transferColost" label="初乳调拨出库"/>
      <el-table-column prop="transferTotal" label="调拨小计"/>
      <el-table-column prop="loss" label="损耗"/>
      
      <!-- 动态饲喂来源列（插入到这里） -->
      <el-table-column v-for="f in selectedFeed" :key="'feed-'+f" :prop="f" :label="f"/>
      <!-- 动态销售去向列 -->
      <el-table-column v-for="s in selectedSale" :key="'sale-'+s" :prop="s" :label="s"/>
      
      <!-- 后面的固定列 -->
      <el-table-column prop="stockCommercial" label="商乳库存"/>
      <el-table-column prop="stockAnti" label="抗乳库存"/>
      <el-table-column prop="colost" label="初乳库存"/>
      <el-table-column prop="returnFresh" label="爱特退回鲜奶"/>
      <el-table-column prop="returnYogurt" label="爱特退回酸奶"/>
    </el-table>

    <el-pagination
      style="margin-top:16px; text-align:right"
      :total="total"
      v-model:page-size="queryParams.pageSize"
      v-model:current-page="queryParams.pageNum"
      @current-change="getList">
    </el-pagination>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getList as fetchList, importExcel, exportExcel, getColumns } from '@/api/dairyProducts/milkInOutStore/milkInOutStore.js'
import { ElMessage } from 'element-plus'

const queryParams = reactive({
  datetimeStart: null,
  datetimeEnd: null,
  pageNum: 1,
  pageSize: 10
})
const rows = ref([])
const total = ref(0)
const allCols = reactive({ feed: [], sale: [] })
const selectedFeed = ref([])
const selectedSale = ref([])
const colDialog = ref(false)

function getList() {
  fetchList(queryParams).then(res => {
    rows.value = res.rows
    total.value = res.total
  })
}

function resetQuery() {
  queryParams.datetimeStart = null
  queryParams.datetimeEnd = null
  queryParams.pageNum = 1
  getList()
}

function openColDialog() {
  getColumns().then(res => {
    const d = res.data[0]
    allCols.feed = d.feed || []
    allCols.sale = d.sale || []
    // 默认勾选所有源/销项列
    selectedFeed.value = [...allCols.feed]
    selectedSale.value = [...allCols.sale]
    colDialog.value = true
  })
}

function applyCols() {
  colDialog.value = false
  getList()
}

function beforeUpload(file) {
  importExcel(file).then(() => {
    ElMessage.success('导入成功')
    getList()
  }).catch(err => {
    ElMessage.error('导入失败：' + (err.message || err))
  })
  return false
}

function handleExport() {
  exportExcel(queryParams).then(blob => {
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `milk_in_out_store_${Date.now()}.xlsx`
    link.click()
  }).catch(err => {
    ElMessage.error('导出失败：' + (err.message || err))
  })
}

onMounted(() => getList())
</script>