<template>
  <div class="app-container">
    <el-form :inline="true" :model="queryParams" class="mb-4">
      <el-form-item label="日期范围">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 260px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </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="info" plain icon="Upload">导入</el-button>
        </el-upload>
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        <el-button type="primary" plain icon="Menu" @click="openColDialog">列设置</el-button>
      </el-col>
    </el-row>

    <el-dialog v-model="colDialog" title="选择展示列" width="600px">
      <div>
        <div style="margin-bottom: 10px; font-weight: bold;">饲喂来源：</div>
        <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: 20px;">
        <div style="margin-bottom: 10px; font-weight: bold;">销售去向：</div>
        <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" v-loading="loading">
      <el-table-column prop="datetime" label="日期" width="120" sortable fixed="left">
        <template #default="{ row }">
          {{ row.datetime ? row.datetime.substring(0, 10) : '' }}
        </template>
      </el-table-column>
      
      <el-table-column prop="num" label="羊数" sortable width="100" />
      <el-table-column prop="colostSheep" label="初乳羊" sortable width="100" />
      <el-table-column prop="commercialIntake" label="商乳入库" sortable width="120" />
      <el-table-column prop="antiIntake" label="抗乳入库" sortable width="120" />
      <el-table-column prop="colostIntake" label="初乳入库" sortable width="120" />
      <el-table-column prop="intakeTotal" label="入库小计" sortable width="120" />
      <el-table-column prop="commercialTest" label="商乳实验用奶" sortable width="140" />
      <el-table-column prop="colostTest" label="初乳实验用奶" sortable width="140" />
      <el-table-column prop="transferCommercial" label="商乳调拨出库" sortable width="140" />
      <el-table-column prop="transferAnti" label="抗乳调拨出库" sortable width="140" />
      <el-table-column prop="transferColost" label="初乳调拨出库" sortable width="140" />
      <el-table-column prop="transferTotal" label="调拨小计" sortable width="120" />
      <el-table-column prop="loss" label="损耗" sortable width="100" />
      
      <el-table-column v-for="f in selectedFeed" :key="'feed-'+f" :prop="f" :label="f" sortable width="120" />
      <el-table-column v-for="s in selectedSale" :key="'sale-'+s" :prop="s" :label="s" sortable width="120" />
      
      <el-table-column prop="stockCommercial" label="商乳库存" sortable width="120" />
      <el-table-column prop="stockAnti" label="抗乳库存" sortable width="120" />
      <el-table-column prop="colost" label="初乳库存" sortable width="120" />
      <el-table-column prop="returnFresh" label="爱特退回鲜奶" sortable width="140" />
      <el-table-column prop="returnYogurt" label="爱特退回酸奶" sortable width="140" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      :page-sizes="[20, 50, 100, 200, 500, 1000, 2000]"
      @pagination="getList"
    />

  </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 loading = ref(false)
const queryParams = reactive({
  datetimeStart: null,
  datetimeEnd: null,
  pageNum: 1,
  pageSize: 20 // 默认每页20条
})
const dateRange = ref([]) // 新增：日期范围变量
const rows = ref([])
const total = ref(0)
const allCols = reactive({ feed: [], sale: [] })
const selectedFeed = ref([])
const selectedSale = ref([])
const colDialog = ref(false)

function getList() {
  loading.value = true
  
  // 处理日期范围
  if (dateRange.value && dateRange.value.length === 2) {
    // 修改：手动拼接时间
    queryParams.datetimeStart = dateRange.value[0] + ' 00:00:00';
    queryParams.datetimeEnd = dateRange.value[1] + ' 23:59:59';
  } else {
    queryParams.datetimeStart = null;
    queryParams.datetimeEnd = null;
  }

  fetchList(queryParams).then(res => {
    rows.value = res.rows
    total.value = res.total
    loading.value = false
  }).catch(err => {
    loading.value = false
    console.error(err)
  })
}

function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

function resetQuery() {
  dateRange.value = [] // 重置日期
  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 || []
    
    // 如果还没选过，默认全选；否则保持当前选择
    if (selectedFeed.value.length === 0 && selectedSale.value.length === 0) {
        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() {
  // 导出前确认日期参数
  if (dateRange.value && dateRange.value.length === 2) {
    // 修改：手动拼接时间
    queryParams.datetimeStart = dateRange.value[0] + ' 00:00:00';
    queryParams.datetimeEnd = dateRange.value[1] + ' 23:59:59';
  } else {
    queryParams.datetimeStart = null;
    queryParams.datetimeEnd = null;
  }

  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()
    URL.revokeObjectURL(link.href)
  }).catch(err => {
    ElMessage.error('导出失败：' + (err.message || err))
  })
}

onMounted(() => {
  // 初始化时获取动态列，防止首次加载表格为空白列
  getColumns().then(res => {
    const d = res.data[0]
    allCols.feed = d.feed || []
    allCols.sale = d.sale || []
    selectedFeed.value = [...allCols.feed]
    selectedSale.value = [...allCols.sale]
    getList()
  })
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb-4 {
  margin-bottom: 16px;
}
</style>