<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="备注" prop="description">
              <el-input v-model="queryParams.description" 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-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['physical:blindStructures:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['physical:blindStructures:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['physical:blindStructures:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['physical:blindStructures:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="blindStructuresList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" v-if="true" width="88" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="预览" align="center" width="150">
          <template #default="scope">
            <span class="level-link" @click="handleViewLevels(scope.row)" style="color: #007bff; cursor: pointer; text-decoration: underline">
              {{ formatBlindLevel(scope.row.blindLevels) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="description" />
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180"> </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['physical:blindStructures:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['physical:blindStructures:remove']"
              ></el-button>
            </el-tooltip>
          </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-card>
    <!-- 添加或修改线下盲注等级主名对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body @close="cancel">
      <el-form ref="blindStructuresFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="上传盲注表" prop="file">
          <div class="upload-container">
            <el-upload
              class="upload-demo"
              action="#"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :file-list="fileList"
              :auto-upload="false"
              :limit="1"
              accept=".xlsx,.xls"
            >
              <!-- 触发上传按钮 -->
              <template #trigger>
                <el-button type="primary">点击上传盲注表</el-button>
              </template>

              <!-- 自定义文件列表 -->
              <template #file="{ file }">
                <div style="display: flex; align-items: center">
                  <span class="el-upload__tip">{{ file.name }}</span>
                  <el-button type="text" icon="el-icon-delete" @click.stop="() => handleFileRemove(file)" style="margin-left: auto"> 删除 </el-button>
                </div>
              </template>

              <!-- 提示信息 -->
              <template #tip>
                <div class="el-upload__tip">
                  <el-link type="primary" @click="downloadTemplate"> <i class="el-icon-download"></i> 模板下载 </el-link>
                  <el-button link @click="openPreview"> <i class="el-icon-document"></i> 预 览 </el-button>
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览弹窗 -->
    <el-dialog title="预览" v-model="previewVisible" width="70%" append-to-body>
      <div style="max-height: 500px; overflow-y: auto">
        <el-table :data="previewData" border v-if="previewData.length > 0">
          <!-- 使用动态表头 -->
          <el-table-column v-for="(header, index) in previewHeaders" :key="index" :label="header">
            <template #default="scope">
              {{ scope.row[index] }}
            </template>
          </el-table-column>
        </el-table>
        <p v-else>暂无数据可预览</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closePreview">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="levelsDialogVisible" title="盲注等级列表" width="80%">
      <!-- 使用 component 动态加载目标组件 -->
      <levels-index :blind-structure-id="dialogParams.blindStructureId" :name="dialogParams.name" />
    </el-dialog>
  </div>
</template>

<script setup name="BlindStructures" lang="ts">
import {
  listBlindStructures,
  getBlindStructures,
  delBlindStructures,
  addBlindStructures,
  updateBlindStructures,
  downloadImportTemplate
} from '@/api/system/physical/blindStructures';
import { BlindStructuresVO, BlindStructuresQuery, BlindStructuresForm } from '@/api/system/physical/blindStructures/types';
import * as XLSX from 'xlsx';
import LevelsIndex from '@/views/system/physical/blindLevels/index.vue';

// ✅ 引入 parseTime
import { parseTime } from '@/utils/dateUtils';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const blindStructuresList = ref<BlindStructuresVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
// 控制 Dialog 是否显示
const levelsDialogVisible = ref(false);

// 传递给子组件的参数
const dialogParams = ref({
  blindStructureId: null,
  name: null
});
const queryFormRef = ref<ElFormInstance>();
const blindStructuresFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BlindStructuresForm = {
  id: undefined,
  name: undefined,
  description: undefined,
  createdAt: undefined,
  updatedAt: undefined,
  createUserId: undefined,
  updateUserId: undefined
};
const data = reactive<PageData<BlindStructuresForm, BlindStructuresQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    description: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    createUserId: undefined,
    updateUserId: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '盲注结构名称，如：Standard, Turbo不能为空', trigger: 'blur' }]
  }
});

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

/** 查询线下盲注等级主名列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBlindStructures(queryParams.value);
  blindStructuresList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  // ✅ 清空文件和预览数据
  fileList.value = [];
  previewData.value = [];
  previewHeaders.value = [];
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  blindStructuresFormRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: BlindStructuresVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: BlindStructuresVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getBlindStructures(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改';
};

const submitForm = () => {
  blindStructuresFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        const formData = new FormData();

        // 如果有文件，添加文件字段
        if (fileList.value.length > 0 && fileList.value[0].raw) {
          formData.append('file', fileList.value[0].raw); // 假设后端接收字段名为 'file'
        } else {
          buttonLoading.value = false;
          //return proxy?.$modal.msgError('文件内容为空');
        }
        // 添加常规字段
        formData.append('name', form.value.name || '');
        formData.append('description', form.value.description || '');
        // 发送请求
        const uds = form.value.id;
        if (uds) {
          const json = JSON.stringify({ 'name': form.value.name || '', 'description': form.value.description || '', 'id': uds || '' });
          const blob = new Blob([json], { type: 'application/json' });
          formData.append('BlindStructuresBo', blob);
          await updateBlindStructures(formData).finally(() => (buttonLoading.value = false));
        } else {
          // 如果有文件，添加文件字段
          if (fileList.value.length > 0 && fileList.value[0].raw) {
            // formData.append('file', fileList.value[0].raw); // 假设后端接收字段名为 'file'
          } else {
            buttonLoading.value = false;
            return proxy?.$modal.msgError('文件内容为空');
          }
          await addBlindStructures(formData).finally(() => (buttonLoading.value = false));
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;

        // ✅ 清空文件和预览数据
        fileList.value = [];
        previewData.value = [];
        previewHeaders.value = [];

        await getList();
      } catch (error) {
        proxy?.$modal.msgError('提交失败');
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: BlindStructuresVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delBlindStructures(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'physical/blindStructures/export',
    {
      ...queryParams.value
    },
    `盲注表${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};

onMounted(() => {
  getList();
});

const downloadTemplate = async () => {
  try {
    const response = await downloadImportTemplate();
    // 创建 Blob 对象（直接使用 response）
    // 确保正确获取 blob 数据
    const blobData = new Blob([response.data || response], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    // 创建对象 URL
    const urlBlob = window.URL.createObjectURL(blobData);
    const link = document.createElement('a');
    link.href = urlBlob;
    link.setAttribute('download', '盲注结构模板.xlsx');
    document.body.appendChild(link);

    // 触发点击事件并稍作延迟，确保链接生效
    link.click();
    setTimeout(() => {
      link.remove();
      window.URL.revokeObjectURL(urlBlob);
    }, 0);
  } catch (error) {
    console.error('Download error:', error); // 输出具体的错误信息
    ElMessage.error('下载失败，请重试');
  }
};

const fileList = ref([]);
const handleFileChange = (file) => {
  const index = fileList.value.findIndex((f) => f.uid === file.uid);

  // 如果文件不存在于列表中，则添加进去
  if (index === -1) {
    fileList.value.push(file);
  }
};

// 删除文件处理函数
const handleFileRemove = (file) => {
  const index = fileList.value.findIndex((f) => f.uid === file.uid);
  if (index > -1) {
    const newFileList = [...fileList.value];
    newFileList.splice(index, 1);
    fileList.value = newFileList;
  }
};

// 预览数据
const previewData = ref<any[]>([]);
const previewHeaders = ref<string[]>([]); // 新增表头数组
const previewVisible = ref(false); // 控制预览弹窗
//  打开预览弹窗并解析文件
const openPreview = () => {
  if (fileList.value.length === 0) {
    return;
  }

  const file = fileList.value[0].raw;
  const isValidType = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(file.type);
  if (!isValidType) {
    return;
  }

  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target?.result as ArrayBuffer);
    const workbook = XLSX.read(data, { type: 'array' });

    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];

    // 获取表头（第二行）
    const headerRow = XLSX.utils.decode_range(worksheet['!ref']).e.r + 1;
    const headerRange = `A2:E2`; // 假设最多5列
    const headerCells = XLSX.utils.decode_range(headerRange);
    previewHeaders.value = [];
    for (let C = headerCells.s.c; C <= headerCells.e.c; ++C) {
      const cellAddress = XLSX.utils.encode_cell({ c: C, r: 0 });
      const cell = worksheet[cellAddress];
      if (cell && cell.v) {
        previewHeaders.value.push(cell.v.toString());
      }
    }

    // 获取数据（第三行开始）
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, range: 1 }); // 从第3行开始读取
    previewData.value = jsonData;
    previewVisible.value = true;
  };
  reader.readAsArrayBuffer(file);
};

// 关闭预览弹窗
const closePreview = () => {
  previewVisible.value = false;
};

const formatBlindLevel = (blindLevels) => {
  if (!blindLevels || !Array.isArray(blindLevels) || blindLevels.length === 0) {
    return '—';
  }
  const firstLevel = blindLevels[0];
  const smallBlind = firstLevel.smallBlind ?? 0;
  const bigBlind = firstLevel.bigBlind ?? 0;
  const ante = firstLevel.ante ?? 0;
  return `${smallBlind}/${bigBlind} ${ante}`;
};
const handleViewLevels = (row) => {
  dialogParams.value.blindStructureId = row.id;
  dialogParams.value.name = row.name;
  levelsDialogVisible.value = true;
};
</script>
