<template>
  <div class="app-container">
    <!-- 简化查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="来源" prop="source">
        <el-input
          v-model="queryParams.source"
          placeholder="请输入来源"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检测日期" prop="datetime">
        <el-date-picker clearable
          v-model="queryParams.datetime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择检测日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['freshMilkTest:freshMilkTest:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['freshMilkTest:freshMilkTest:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['freshMilkTest:freshMilkTest:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['freshMilkTest:freshMilkTest:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Operation"
          @click="columnShowDialogVisible = true"
        >列显示</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格显示，使用列选择功能 -->
    <el-table v-loading="loading" :data="freshMilkTestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column 
        label="来源" 
        align="center" 
        prop="source" 
        v-if="selectedColumns.includes('source')" />
      <el-table-column 
        label="检测日期" 
        align="center" 
        prop="datetime" 
        width="180"
        v-if="selectedColumns.includes('datetime')">
        <template #default="scope">
          <span>{{ formatDate(scope.row.datetime) }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        label="脂肪g/100g" 
        align="center" 
        prop="fat" 
        v-if="selectedColumns.includes('fat')" />
      <el-table-column 
        label="蛋白质g/100g" 
        align="center" 
        prop="protein" 
        v-if="selectedColumns.includes('protein')" />
      <el-table-column 
        label="非脂g/100g" 
        align="center" 
        prop="nonFat" 
        v-if="selectedColumns.includes('nonFat')" />
      <el-table-column 
        label="酸度oT" 
        align="center" 
        prop="acidity" 
        v-if="selectedColumns.includes('acidity')" />
      <el-table-column 
        label="菌落总数1" 
        align="center" 
        prop="bacterialColony1" 
        v-if="selectedColumns.includes('bacterialColony1')" />
      <el-table-column 
        label="菌落总数2" 
        align="center" 
        prop="bacterialColony2" 
        v-if="selectedColumns.includes('bacterialColony2')" />
      <el-table-column 
        label="菌落总数3" 
        align="center" 
        prop="bacterialColony3" 
        v-if="selectedColumns.includes('bacterialColony3')" />
      <el-table-column 
        label="菌落总数4" 
        align="center" 
        prop="bacterialColony4" 
        v-if="selectedColumns.includes('bacterialColony4')" />
      <el-table-column 
        label="菌落总数5" 
        align="center" 
        prop="bacterialColony5" 
        v-if="selectedColumns.includes('bacterialColony5')" />
      <el-table-column 
        label="大肠菌群(CFU/ml)" 
        align="center" 
        prop="coli" 
        v-if="selectedColumns.includes('coli')" />
      <el-table-column 
        label="乳铁蛋白(mg/L)" 
        align="center" 
        prop="lactoferrin" 
        v-if="selectedColumns.includes('lactoferrin')" />
      <el-table-column 
        label="免疫球蛋白(mg/L)" 
        align="center" 
        prop="ig" 
        v-if="selectedColumns.includes('ig')" />
      <el-table-column 
        label="备注" 
        align="center" 
        prop="commnet" 
        v-if="selectedColumns.includes('commnet')" />
      <el-table-column 
        label="创建人" 
        align="center" 
        prop="createBy" 
        v-if="selectedColumns.includes('createBy')" />
      <el-table-column 
        label="创建时间" 
        align="center" 
        prop="createTime" 
        width="180"
        v-if="selectedColumns.includes('createTime')">
        <template #default="scope">
          <span>{{ formatDateTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['freshMilkTest:freshMilkTest:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['freshMilkTest:freshMilkTest:remove']">删除</el-button>
        </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="title" v-model="open" width="500px" append-to-body>
      <el-form ref="freshMilkTestRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入来源" />
        </el-form-item>
        <el-form-item label="检测日期" prop="datetime">
          <el-date-picker clearable
            v-model="form.datetime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择检测日期"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="脂肪g/100g" prop="fat">
          <el-input v-model="form.fat" placeholder="请输入脂肪g/100g" />
        </el-form-item>
        <el-form-item label="蛋白质g/100g" prop="protein">
          <el-input v-model="form.protein" placeholder="请输入蛋白质g/100g" />
        </el-form-item>
        <el-form-item label="非脂g/100g" prop="nonFat">
          <el-input v-model="form.nonFat" placeholder="请输入非脂g/100g" />
        </el-form-item>
        <el-form-item label="酸度oT" prop="acidity">
          <el-input v-model="form.acidity" placeholder="请输入酸度oT" />
        </el-form-item>
        <el-form-item label="菌落总数1" prop="bacterialColony1">
          <el-input v-model="form.bacterialColony1" placeholder="请输入菌落总数1" />
        </el-form-item>
        <el-form-item label="菌落总数2" prop="bacterialColony2">
          <el-input v-model="form.bacterialColony2" placeholder="请输入菌落总数2" />
        </el-form-item>
        <el-form-item label="菌落总数3" prop="bacterialColony3">
          <el-input v-model="form.bacterialColony3" placeholder="请输入菌落总数3" />
        </el-form-item>
        <el-form-item label="菌落总数4" prop="bacterialColony4">
          <el-input v-model="form.bacterialColony4" placeholder="请输入菌落总数4" />
        </el-form-item>
        <el-form-item label="菌落总数5" prop="bacterialColony5">
          <el-input v-model="form.bacterialColony5" placeholder="请输入菌落总数5" />
        </el-form-item>
        <el-form-item label="大肠菌群(CFU/ml)" prop="coli">
          <el-input v-model="form.coli" placeholder="请输入大肠菌群(CFU/ml)" />
        </el-form-item>
        <el-form-item label="乳铁蛋白(mg/L)" prop="lactoferrin">
          <el-input v-model="form.lactoferrin" placeholder="请输入乳铁蛋白(mg/L)" />
        </el-form-item>
        <el-form-item label="免疫球蛋白(mg/L)" prop="ig">
          <el-input v-model="form.ig" placeholder="请输入免疫球蛋白(mg/L)" />
        </el-form-item>
        <el-form-item label="备注" prop="commnet">
          <el-input v-model="form.commnet" placeholder="请输入备注" type="textarea" />
        </el-form-item>
        <el-form-item label="创建人" v-if="form.id">
          <el-input v-model="form.createBy" disabled />
        </el-form-item>
        <el-form-item label="创建时间" v-if="form.id">
          <el-input v-model="form.createTime" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 列显示设置对话框 -->
    <el-dialog title="列显示设置" v-model="columnShowDialogVisible" width="500px">
      <el-checkbox-group v-model="selectedColumns">
        <el-checkbox label="source">来源</el-checkbox>
        <el-checkbox label="datetime">检测日期</el-checkbox>
        <el-checkbox label="fat">脂肪g/100g</el-checkbox>
        <el-checkbox label="protein">蛋白质g/100g</el-checkbox>
        <el-checkbox label="nonFat">非脂g/100g</el-checkbox>
        <el-checkbox label="acidity">酸度oT</el-checkbox>
        <el-checkbox label="bacterialColony1">菌落总数1</el-checkbox>
        <el-checkbox label="bacterialColony2">菌落总数2</el-checkbox>
        <el-checkbox label="bacterialColony3">菌落总数3</el-checkbox>
        <el-checkbox label="bacterialColony4">菌落总数4</el-checkbox>
        <el-checkbox label="bacterialColony5">菌落总数5</el-checkbox>
        <el-checkbox label="coli">大肠菌群(CFU/ml)</el-checkbox>
        <el-checkbox label="lactoferrin">乳铁蛋白(mg/L)</el-checkbox>
        <el-checkbox label="ig">免疫球蛋白(mg/L)</el-checkbox>
        <el-checkbox label="commnet">备注</el-checkbox>
        <el-checkbox label="createBy">创建人</el-checkbox>
        <el-checkbox label="createTime">创建时间</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="columnShowDialogVisible = false">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { listFreshMilkTest, getFreshMilkTest, delFreshMilkTest, addFreshMilkTest, updateFreshMilkTest } from "@/api/dairyProducts/freshMilkTest/freshMilkTest.js";
import { ElMessage, ElMessageBox } from 'element-plus';
// 导入xlsx库和file-saver
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

const freshMilkTestList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const columnShowDialogVisible = ref(false);
const freshMilkTestRef = ref(null);

// 列配置映射
const columnConfig = [
  { prop: 'source', label: '来源' },
  { prop: 'datetime', label: '检测日期' },
  { prop: 'fat', label: '脂肪g/100g' },
  { prop: 'protein', label: '蛋白质g/100g' },
  { prop: 'nonFat', label: '非脂g/100g' },
  { prop: 'acidity', label: '酸度oT' },
  { prop: 'bacterialColony1', label: '菌落总数1' },
  { prop: 'bacterialColony2', label: '菌落总数2' },
  { prop: 'bacterialColony3', label: '菌落总数3' },
  { prop: 'bacterialColony4', label: '菌落总数4' },
  { prop: 'bacterialColony5', label: '菌落总数5' },
  { prop: 'coli', label: '大肠菌群(CFU/ml)' },
  { prop: 'lactoferrin', label: '乳铁蛋白(mg/L)' },
  { prop: 'ig', label: '免疫球蛋白(mg/L)' },
  { prop: 'commnet', label: '备注' },
  { prop: 'createBy', label: '创建人' },
  { prop: 'createTime', label: '创建时间' }
];

// 默认显示的列
const selectedColumns = ref([
  'source', 'datetime', 'fat', 'protein', 'nonFat', 'acidity', 
  'bacterialColony1', 'bacterialColony2', 'bacterialColony3', 
  'bacterialColony4', 'bacterialColony5', 'coli', 'lactoferrin', 
  'ig', 'commnet', 'createBy', 'createTime'
]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  source: null,
  datetime: null,
});

// 表单数据
const form = reactive({
  id: null,
  source: null,
  datetime: null,
  fat: null,
  protein: null,
  nonFat: null,
  acidity: null,
  bacterialColony1: null,
  bacterialColony2: null,
  bacterialColony3: null,
  bacterialColony4: null,
  bacterialColony5: null,
  coli: null,
  lactoferrin: null,
  ig: null,
  commnet: null,
  createBy: null,
  createTime: null
});

// 验证规则
const rules = reactive({
  source: [
    { required: true, message: "来源不能为空", trigger: "blur" }
  ],
  datetime: [
    { required: true, message: "检测日期不能为空", trigger: "blur" }
  ]
});

/** 获取当前用户名 */
const getCurrentUsername = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  return userInfo.userName || userInfo.username || userInfo.nickName || 'admin'
}

/** 查询列表 */
function getList() {
  loading.value = true;
  listFreshMilkTest(queryParams).then(response => {
    freshMilkTestList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(error => {
    console.error("获取数据失败:", error);
    loading.value = false;
    ElMessage.error("获取数据失败");
  });
}

// 日期格式化函数
function formatDate(dateString) {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch (e) {
    console.error("日期格式化错误:", e);
    return dateString;
  }
}

// 日期时间格式化
function formatDateTime(dateString) {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (e) {
    console.error("日期时间格式化错误:", e);
    return dateString;
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  resetForm();
}

// 表单重置
function resetForm() {
  Object.assign(form, {
    id: null,
    source: null,
    datetime: null,
    fat: null,
    protein: null,
    nonFat: null,
    acidity: null,
    bacterialColony1: null,
    bacterialColony2: null,
    bacterialColony3: null,
    bacterialColony4: null,
    bacterialColony5: null,
    coli: null,
    lactoferrin: null,
    ig: null,
    commnet: null,
    createBy: null,
    createTime: null
  });
  
  if (freshMilkTestRef.value) {
    freshMilkTestRef.value.resetFields();
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  Object.assign(queryParams, {
    source: null,
    datetime: null,
  });
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  resetForm();
  open.value = true;
  title.value = "添加鲜奶检验记录";
  
  // 设置创建人和创建时间
  form.createBy = getCurrentUsername();
  form.createTime = new Date().toISOString().replace('T', ' ').substring(0, 19);
}

/** 修改按钮操作 */
function handleUpdate(row) {
  resetForm();
  const id = row.id || (ids.value.length ? ids.value[0] : null);
  if (!id) {
    ElMessage.error("请选择要修改的数据");
    return;
  }
  
  getFreshMilkTest(id).then(response => {
    Object.assign(form, response.data);
    open.value = true;
    title.value = "修改鲜奶检验记录";
  }).catch(error => {
    console.error("获取详情失败:", error);
    ElMessage.error("获取详情失败");
  });
}

/** 提交按钮 */
function submitForm() {
  freshMilkTestRef.value.validate(valid => {
    if (valid) {
      const submitData = { ...form };
      if (!submitData.id) {
        submitData.createBy = getCurrentUsername();
        submitData.createTime = new Date().toISOString().replace('T', ' ').substring(0, 19);
      } else {
        delete submitData.createBy;
        delete submitData.createTime;
      }
      
      const request = submitData.id 
        ? updateFreshMilkTest(submitData) 
        : addFreshMilkTest(submitData);
      
      request.then(response => {
        ElMessage.success(submitData.id ? "修改成功" : "新增成功");
        open.value = false;
        getList();
      }).catch(error => {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const deleteIds = row.id ? [row.id] : ids.value;
  if (!deleteIds.length) {
    ElMessage.error("请选择要删除的数据");
    return;
  }
  
  ElMessageBox.confirm('是否确认删除选中的记录？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return delFreshMilkTest(deleteIds);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(error => {
    console.error("删除失败:", error);
    if (error !== 'cancel') {
      ElMessage.error("删除失败");
    }
  });
}

/** 导出按钮操作 - 前端实现 */
function handleExport() {
  // 获取当前显示的列配置
  const visibleColumnsConfig = columnConfig.filter(
    col => selectedColumns.value.includes(col.prop)
  );
  
  // 准备导出数据
  const exportData = freshMilkTestList.value.map(item => {
    const rowData = {};
    visibleColumnsConfig.forEach(col => {
      // 特殊处理日期字段
      if (col.prop === 'datetime') {
        rowData[col.label] = formatDate(item[col.prop]);
      } else if (col.prop === 'createTime') {
        rowData[col.label] = formatDateTime(item[col.prop]);
      } else {
        rowData[col.label] = item[col.prop];
      }
    });
    return rowData;
  });
  
  // 创建工作簿和工作表
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '鲜奶检验记录');
  
  // 生成Excel文件并下载
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([excelBuffer], { 
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
  });
  
  // 使用file-saver保存文件
  saveAs(blob, `鲜奶检验记录_${new Date().getTime()}.xlsx`);
}

// 初始化加载
onMounted(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.el-form-item {
  margin-bottom: 15px;
}
.el-dialog__body {
  padding: 15px 20px;
}
</style>