<!-- index.vue (前端视图，修改 resetQuery 以匹配正确字段) -->
<template>
  <div class="app-container">
    <el-form ref="queryRef" :model="queryParams" inline label-width="80px">
      <el-form-item label="日期范围">
        <el-date-picker v-model="dateRange" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
      </el-form-item>
      <!-- 管理耳号变成输入框 -->
      <el-form-item label="管理耳号">
        <el-input v-model="queryParams.manageEarNo" placeholder="请输入管理耳号" clearable />
      </el-form-item>
       <!-- 厂区下拉框，数据源来自字典 da_ranch -->
      <el-form-item label="厂区">
        <el-select v-model="queryParams.factory" clearable placeholder="请选择">
          <el-option
            v-for="d in ranchOptions"
            :key="d.value"
            :label="d.label"
            :value="d.value" />
        </el-select>
      </el-form-item>
      <!-- 班次只有 1、2 -->
      <el-form-item label="班次">
        <el-select v-model="queryParams.classes" clearable placeholder="请选择">
          <el-option :value="1" label="1" />
          <el-option :value="2" label="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row>
      <el-button type="info" plain @click="handleImport" v-hasPermi="['milkProdclasses:milkProdclasses:import']">
        <el-icon><Upload /></el-icon> 导入
      </el-button>
      <el-button type="warning" plain @click="handleExport" v-hasPermi="['milkProdclasses:milkProdclasses:export']">
        <el-icon><Download /></el-icon> 导出
      </el-button>
    </el-row>

    <el-table :data="tableData" v-loading="loading">
      <el-table-column prop="datetime" label="日期" width="110" />
      <el-table-column prop="manageEarNo" label="管理耳号" />
      <el-table-column prop="electronicEarNo" label="电子耳号" />
      <el-table-column prop="parity" label="胎次" />
      <el-table-column prop="factory" label="厂区" />
      <el-table-column prop="classes" label="班次" />
      <el-table-column prop="milk" label="班次产奶量" />
      <el-table-column prop="correctedMilk" label="班次校正奶量" />
    </el-table>

    <pagination v-show="total>0" :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList" />

    <!-- 导入弹窗 -->
    <el-dialog title="Excel导入" v-model="openImport" width="400px">
      <el-upload drag :action="uploadUrl" :headers="headers"
                 accept=".xls,.xlsx" :on-success="uploadSuccess" :on-error="uploadError">
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div>将文件拖到此处或<em>点击上传</em></div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { listMilkProdclasses, importMilkProdclasses, exportMilkProdclasses } from '@/api/dairyProducts/milkProdclasses/milkProdclasses'
import { getToken } from '@/utils/auth'
import { getRanchList } from '@/api/dairyProducts/ranch/ranch.js'
import { Upload, Download, UploadFilled } from '@element-plus/icons-vue';

const ranchOptions = ref([])

onMounted(() => {
  getRanchList().then(res => {
    ranchOptions.value = res.data.map(item => ({
      label: item.ranchName,
      value: item.ranchCode
    }))
  }).catch(err => {
    console.error('获取厂区列表失败:', err)
  })
})

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  manageEarNo: '',   // 管理耳号
  factory: null,
  classes: null
})
const dateRange = ref([])
const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const openImport = ref(false)

const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/milkProdclasses/milkProdclasses/import';
const headers = { Authorization: 'Bearer ' + getToken() };

function getList() {
  loading.value = true
  const [start, end] = dateRange.value || []
  listMilkProdclasses({
    datetimeStart: start,
    datetimeEnd: end,
    manageEarNo: queryParams.manageEarNo,
    factory: queryParams.factory,
    classes: queryParams.classes,
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize
  }).then(res => {
    tableData.value = res.rows
    total.value = res.total
    loading.value = false
  }).catch(err => {
    console.error('查询失败:', err);
    loading.value = false;
  });
}

function resetQuery() {
  Object.assign(queryParams, { pageNum: 1, manageEarNo: '', factory: null, classes: null });
  dateRange.value = [];
  getList();
}

function handleImport() {
  openImport.value = true;
}

function uploadSuccess(response) {
  console.log('上传成功:', response);
  openImport.value = false;
  getList();
}

function uploadError(err) {
  console.error('上传失败:', err);
}

function handleExport() {
  const [start, end] = dateRange.value || [];
  exportMilkProdclasses({
    datetimeStart: start,
    datetimeEnd: end,
    manageEarNo: queryParams.manageEarNo,  // 与后台参数统一
    factory: queryParams.factory,
    classes: queryParams.classes
  });
}

getList();
</script>
