<!-- index.vue (前端视图，仅保留单日查询功能) -->
<template>
  <div class="app-container">
    <el-form ref="queryRef" :model="queryParams" inline label-width="80px">
      <!-- 单日查询 -->
      <el-form-item label="查询日期">
        <el-date-picker 
          v-model="queryDate" 
          type="date" 
          placeholder="选择查询日期" 
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
          clearable />
      </el-form-item>
      
      <!-- 管理耳号输入框 -->
      <el-form-item label="管理耳号">
        <el-input v-model="queryParams.manageEarNo" placeholder="请输入管理耳号" clearable />
      </el-form-item>
      
      <!-- 厂区下拉框 -->
      <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>
      
      <!-- 班次下拉框 -->
      <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="班次产奶量" >
        <template #default="{ row }">
          {{ row.milk ? Number(row.milk).toFixed(2) : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="correctedMilk" label="班次校正奶量" >
        <template #default="{ row }">
          {{ row.correctedMilk ? Number(row.correctedMilk).toFixed(2) : '-' }}
        </template>
      </el-table-column>
    </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 { ElMessage } from 'element-plus'
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,
  datetimeStart: null,  // 开始日期
  datetimeEnd: null,    // 结束日期
  manageEarNo: '',      // 管理耳号
  factory: null,        // 厂区
  classes: null         // 班次
})
const queryDate = ref(null)     // 查询日期
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
  
  // 设置查询参数
  if (queryDate.value) {
    queryParams.datetimeStart = queryDate.value;
    queryParams.datetimeEnd = queryDate.value;
  } else {
    queryParams.datetimeStart = null;
    queryParams.datetimeEnd = null;
  }
  
  listMilkProdclasses({
    datetimeStart: queryParams.datetimeStart,
    datetimeEnd: queryParams.datetimeEnd,
    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, 
    datetimeStart: null,
    datetimeEnd: null,
    manageEarNo: '', 
    factory: null, 
    classes: null 
  });
  queryDate.value = null;
  getList();
}

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

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

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

function handleExport() {
  // 设置查询参数
  if (queryDate.value) {
    queryParams.datetimeStart = queryDate.value;
    queryParams.datetimeEnd = queryDate.value;
  } else {
    queryParams.datetimeStart = null;
    queryParams.datetimeEnd = null;
  }
  
  exportMilkProdclasses({
    datetimeStart: queryParams.datetimeStart,
    datetimeEnd: queryParams.datetimeEnd,
    manageEarNo: queryParams.manageEarNo,
    factory: queryParams.factory,
    classes: queryParams.classes
  }).then(response => {
    // 创建Blob对象，用于文件下载
    const blob = new Blob([response], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    
    // 创建下载链接
    const downloadElement = document.createElement('a');
    const href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    
    // 设置下载文件名，包含当前日期
    const now = new Date();
    const dateStr = `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`;
    downloadElement.download = `班次产奶数据_${dateStr}.xlsx`;
    
    document.body.appendChild(downloadElement);
    // 触发点击下载
    downloadElement.click();
    // 释放URL对象
    document.body.removeChild(downloadElement);
    window.URL.revokeObjectURL(href);
    
    ElMessage.success('导出成功');
  }).catch(error => {
    console.error('导出失败:', error);
    ElMessage.error('导出失败: ' + (error.message || '未知错误'));
  });
}

getList();
</script>