<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <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 label="来源" prop="source">
        <el-input
          v-model="queryParams.source"
          placeholder="请输入来源"
          clearable
          @keyup.enter="handleQuery"
        />
      </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="['rawMilkTest:rawMilkTest:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['rawMilkTest:rawMilkTest:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['rawMilkTest:rawMilkTest:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['rawMilkTest:rawMilkTest:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Menu"
          @click="showColumnSelector = true"
        >字段显示</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rawMilkTestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="检测日期" align="center" prop="datetime" width="180" v-if="visibleColumns.datetime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.datetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="source" v-if="visibleColumns.source" />
      <el-table-column label="冰点" align="center" prop="freeze" v-if="visibleColumns.freeze" />
      <el-table-column label="相对密度" align="center" prop="density" v-if="visibleColumns.density" />
      <el-table-column label="脂肪g/100g" align="center" prop="fat" v-if="visibleColumns.fat" />
      <el-table-column label="蛋白质g/100g" align="center" prop="protein" v-if="visibleColumns.protein" />
      <el-table-column label="非脂g/100g" align="center" prop="nonFat" v-if="visibleColumns.nonFat" />
      <el-table-column label="干物质mg/100g" align="center" prop="dryMatter" v-if="visibleColumns.dryMatter" />
      <el-table-column label="杂质度mg/100g" align="center" prop="impurityDegree" v-if="visibleColumns.impurityDegree" />
      <el-table-column label="乳糖g/100g" align="center" prop="lactose" v-if="visibleColumns.lactose" />
      <el-table-column label="灰度g/100g" align="center" prop="ashContent" v-if="visibleColumns.ashContent" />
      <el-table-column label="酸度" align="center" prop="acidity" v-if="visibleColumns.acidity" />
      <el-table-column label="ph" align="center" prop="ph" v-if="visibleColumns.ph" />
      <el-table-column label="菌落总数" align="center" prop="bacterialColony" v-if="visibleColumns.bacterialColony" />
      <el-table-column label="乳铁蛋白" align="center" prop="lactoferrin" v-if="visibleColumns.lactoferrin" />
      <el-table-column label="免疫球蛋白" align="center" prop="ig" v-if="visibleColumns.ig" />
      <el-table-column label="体细胞" align="center" prop="somaticCell" v-if="visibleColumns.somaticCell" />
      <el-table-column label="尿素氮" align="center" prop="usea" v-if="visibleColumns.usea" />
      <el-table-column label="脂蛋比" align="center" prop="fatRatio" v-if="visibleColumns.fatRatio" />
      <el-table-column label="备注" align="center" prop="comment" v-if="visibleColumns.comment" />
      <el-table-column label="创建人" align="center" prop="createBy" v-if="visibleColumns.createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="visibleColumns.createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</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="['rawMilkTest:rawMilkTest:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['rawMilkTest:rawMilkTest: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="rawMilkTestRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="检测日期" prop="datetime">
          <el-date-picker clearable
            v-model="form.datetime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择检测日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入来源" />
        </el-form-item>
        <el-form-item label="冰点" prop="freeze">
          <el-input v-model="form.freeze" placeholder="请输入冰点" />
        </el-form-item>
        <el-form-item label="相对密度" prop="density">
          <el-input v-model="form.density" placeholder="请输入相对密度" />
        </el-form-item>
        <el-form-item label="脂肪g/100g" prop="fat">
          <el-input 
            v-model="form.fat" 
            placeholder="请输入脂肪g/100g"
            @input="calculateFatRatio"
          />
        </el-form-item>
        <el-form-item label="蛋白质g/100g" prop="protein">
          <el-input 
            v-model="form.protein" 
            placeholder="请输入蛋白质g/100g"
            @input="calculateFatRatio"
          />
        </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="干物质mg/100g" prop="dryMatter">
          <el-input v-model="form.dryMatter" placeholder="请输入干物质mg/100g" />
        </el-form-item>
        <el-form-item label="杂质度mg/100g" prop="impurityDegree">
          <el-input v-model="form.impurityDegree" placeholder="请输入杂质度mg/100g" />
        </el-form-item>
        <el-form-item label="乳糖g/100g" prop="lactose">
          <el-input v-model="form.lactose" placeholder="请输入乳糖g/100g" />
        </el-form-item>
        <el-form-item label="灰度g/100g" prop="ashContent">
          <el-input v-model="form.ashContent" placeholder="请输入灰度g/100g" />
        </el-form-item>
        <el-form-item label="酸度" prop="acidity">
          <el-input v-model="form.acidity" placeholder="请输入酸度" />
        </el-form-item>
        <el-form-item label="ph" prop="ph">
          <el-input v-model="form.ph" placeholder="请输入ph" />
        </el-form-item>
        <el-form-item label="菌落总数" prop="bacterialColony">
          <el-input v-model="form.bacterialColony" placeholder="请输入菌落总数" />
        </el-form-item>
        <el-form-item label="乳铁蛋白" prop="lactoferrin">
          <el-input v-model="form.lactoferrin" placeholder="请输入乳铁蛋白" />
        </el-form-item>
        <el-form-item label="免疫球蛋白" prop="ig">
          <el-input v-model="form.ig" placeholder="请输入免疫球蛋白" />
        </el-form-item>
        <el-form-item label="体细胞" prop="somaticCell">
          <el-input v-model="form.somaticCell" placeholder="请输入体细胞" />
        </el-form-item>
        <el-form-item label="尿素氮" prop="usea">
          <el-input v-model="form.usea" placeholder="请输入尿素氮" />
        </el-form-item>
        <el-form-item label="脂蛋比" prop="fatRatio">
          <el-input 
            v-model="form.fatRatio" 
            placeholder="自动计算" 
            readonly
          />
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="form.comment" placeholder="请输入备注" />
        </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="showColumnSelector" width="600px" append-to-body>
      <el-checkbox-group v-model="selectedColumns">
        <el-row>
          <el-col :span="8" v-for="column in allColumns" :key="column.prop">
            <el-checkbox :label="column.prop">{{ column.label }}</el-checkbox>
          </el-col>
        </el-row>
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="applyColumnSelection">确 定</el-button>
          <el-button @click="showColumnSelector = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RawMilkTest">
// 导入xlsx库
import * as XLSX from 'xlsx';
// 导入file-saver用于文件下载
import { saveAs } from 'file-saver';
import { listRawMilkTest, getRawMilkTest, delRawMilkTest, addRawMilkTest, updateRawMilkTest } from "@/api/dairyProducts/rawMilkTest/rawMilkTest.js"
import { getCurrentInstance, ref, reactive, toRefs, onMounted } from 'vue'
import { parseTime } from '@/utils/ruoyi'

const { proxy } = getCurrentInstance()

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

const rawMilkTestList = 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 showColumnSelector = ref(false)

// 所有可选的列配置
const allColumns = ref([
  { prop: 'datetime', label: '检测日期' },
  { prop: 'source', label: '来源' },
  { prop: 'freeze', label: '冰点' },
  { prop: 'density', label: '相对密度' },
  { prop: 'fat', label: '脂肪g/100g' },
  { prop: 'protein', label: '蛋白质g/100g' },
  { prop: 'nonFat', label: '非脂g/100g' },
  { prop: 'dryMatter', label: '干物质mg/100g' },
  { prop: 'impurityDegree', label: '杂质度mg/100g' },
  { prop: 'lactose', label: '乳糖g/100g' },
  { prop: 'ashContent', label: '灰度g/100g' },
  { prop: 'acidity', label: '酸度' },
  { prop: 'ph', label: 'ph' },
  { prop: 'bacterialColony', label: '菌落总数' },
  { prop: 'lactoferrin', label: '乳铁蛋白' },
  { prop: 'ig', label: '免疫球蛋白' },
  { prop: 'somaticCell', label: '体细胞' },
  { prop: 'usea', label: '尿素氮' },
  { prop: 'fatRatio', label: '脂蛋比' },
  { prop: 'comment', label: '备注' },
  { prop: 'createBy', label: '创建人' },
  { prop: 'createTime', label: '创建时间' }
])

// 默认选中的列
const selectedColumns = ref([
  'datetime', 'source', 'freeze', 'density', 'fat', 'protein', 'nonFat', 
  'dryMatter', 'impurityDegree', 'lactose', 'ashContent', 'acidity', 'ph',
  'bacterialColony', 'lactoferrin', 'ig', 'somaticCell', 'usea', 'fatRatio',
  'comment', 'createBy', 'createTime'
])

// 当前显示的列
const visibleColumns = ref({})

// 初始化列显示状态
const initVisibleColumns = () => {
  allColumns.value.forEach(column => {
    visibleColumns.value[column.prop] = selectedColumns.value.includes(column.prop)
  })
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    datetime: null,
    source: null
  },
  rules: {
    datetime: [
      { required: true, message: "检测日期不能为空", trigger: "blur" }
    ],
    source: [
      { required: true, message: "来源不能为空", trigger: "blur" }
    ],
    // 其他字段根据需要添加验证规则
  }
})

const { queryParams, form, rules } = toRefs(data)

// 应用列选择
const applyColumnSelection = () => {
  initVisibleColumns()
  showColumnSelector.value = false
}

// 脂蛋比计算方法
const calculateFatRatio = () => {
  try {
    const fat = parseFloat(form.value.fat)
    const protein = parseFloat(form.value.protein)
    
    if (!isNaN(fat) && !isNaN(protein) && protein !== 0) {
      form.value.fatRatio = (fat / protein).toFixed(4) // 保留4位小数
    } else {
      form.value.fatRatio = ""
    }
  } catch (e) {
    form.value.fatRatio = ""
  }
}

/** 查询生乳检验记录列表 */
function getList() {
  loading.value = true
  listRawMilkTest(queryParams.value).then(response => {
    rawMilkTestList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    datetime: null,
    source: null,
    freeze: null,
    density: null,
    fat: null,
    protein: null,
    nonFat: null,
    dryMatter: null,
    impurityDegree: null,
    lactose: null,
    ashContent: null,
    acidity: null,
    ph: null,
    bacterialColony: null,
    lactoferrin: null,
    ig: null,
    somaticCell: null,
    usea: null,
    fatRatio: null,
    comment: null
  }
  proxy.resetForm("rawMilkTestRef")
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

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

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加生乳检验记录"
  
  // 设置创建人和创建时间（格式化为YYYY-MM-DD HH:mm:ss）
  form.value.createBy = getCurrentUsername()
  form.value.createTime = new Date().toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
  
  // 初始化脂蛋比
  form.value.fatRatio = ""
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRawMilkTest(_id).then(response => {
    form.value = response.data
    // 计算脂蛋比
    calculateFatRatio()
    open.value = true
    title.value = "修改生乳检验记录"
  }).catch(() => {
    proxy.$modal.msgError("获取数据失败")
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["rawMilkTestRef"].validate(valid => {
    if (valid) {
      // 新增时设置创建信息
      if (form.value.id == null) {
        form.value.createBy = getCurrentUsername()
        form.value.createTime = new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }).replace(/\//g, '-')
      }
      
      const savePromise = form.value.id 
        ? updateRawMilkTest(form.value)
        : addRawMilkTest(form.value)
        
      savePromise.then(response => {
        proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功")
        open.value = false
        getList()
      }).catch(error => {
        console.error("保存失败:", error)
        proxy.$modal.msgError("操作失败，请重试")
      })
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除生乳检验记录编号为"' + _ids + '"的数据项？').then(function() {
    return delRawMilkTest(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(error => {
    console.error("删除失败:", error)
    proxy.$modal.msgError("删除失败")
  })
}

/** 导出按钮操作 */
function handleExport() {
  // 获取当前显示的列配置
  const visibleColumnsConfig = allColumns.value.filter(
    col => visibleColumns.value[col.prop]
  );
  
  // 准备导出数据
  const exportData = rawMilkTestList.value.map(item => {
    const rowData = {};
    visibleColumnsConfig.forEach(col => {
      // 特殊处理日期字段
      if (col.prop === 'datetime' || col.prop === 'createTime') {
        rowData[col.label] = parseTime(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(() => {
  initVisibleColumns()
  getList()
})
</script>