<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-[20px]">
        <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="['business:structures:add']">新增盲注表</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:structures:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:structures: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="structuresList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" v-if="false" />
        <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">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createName" />

        <!--        <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updatedAt, '{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-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:structures:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:structures:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleViewLevels(scope.row)" v-hasPermi="['business:structures:query']"></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="structuresFormRef" :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 v-model="levelsDialogVisible" title="盲注等级列表" width="80%">
      <!-- 使用 component 动态加载目标组件 -->
      <levels-index :blind-structure-id="dialogParams.blindStructureId" :name="dialogParams.name" />
    </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>
  </div>
</template>

<script setup name="Structures" lang="ts">
import {
  listStructures,
  getStructures,
  delStructures,
  addStructures,
  updateStructures,
  downloadImportTemplate
} from '@/api/system/business/structures';
import { StructuresVO, StructuresQuery, StructuresForm } from '@/api/system/business/structures/types';
import { ref } from 'vue';
import LevelsIndex from '@/views/system/business/levels/index.vue';
import * as XLSX from 'xlsx';

// ✅ 引入 parseTime
import { parseTime } from '@/utils/dateUtils';
// 控制 Dialog 是否显示
const levelsDialogVisible = ref(false);

// 传递给子组件的参数
const dialogParams = ref({
  blindStructureId: null,
  name: null
});
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const structuresList = ref<StructuresVO[]>([]);
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);

const queryFormRef = ref<ElFormInstance>();
const structuresFormRef = ref<ElFormInstance>();

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

const initFormData: StructuresForm = {
  id: undefined,
  name: undefined,
  description: undefined,
  taskId: undefined,
  updatedAt: undefined
};
const data = reactive<PageData<StructuresForm, StructuresQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    description: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    name: [
      { required: true, message: '盲注结构名称不能为空', trigger: 'blur' },
      { max: 25, message: '名称长度不能超过25个字符', trigger: 'blur' }]
  }
});

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

/** 查询【请填写功能名称】列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStructures(queryParams.value);
  structuresList.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 };
  structuresFormRef.value?.resetFields();
};

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.id = undefined; // 显式设置id为undefined
  dialog.visible = true;
  dialog.title = '新增盲注表';
};

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

/** 提交按钮 */
const submitForm = () => {
  structuresFormRef.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 updateStructures(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 addStructures(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?: StructuresVO) => {
  const _ids = row?.id || ids.value;
  const name = row?.name;
  await proxy?.$modal.confirm('是否确认删除【盲注管理】名称为"' + name + '"的数据项？').finally(() => (loading.value = false));
  await delStructures(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

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;
};

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 handleFileChange = async (file) => {
  const index = fileList.value.findIndex((f) => f.uid === file.uid);

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

  try {
    const rawFile = file.raw;
    const res = await importData(rawFile);
    if (res.code === 200) {
      // 更新文件状态为成功
      fileList.value[index] = {
        ...file,
        status: 'success',
        response: res
      };
      ElMessage.success('上传成功');
    } else {
      throw new Error(res.msg);
    }
  } catch (error) {
    // 更新文件状态为失败
    fileList.value[index] = {
      ...file,
      status: 'fail',
      error: '上传失败'
    };
    ElMessage.error('上传失败，请重试');
  }
};*/
</script>
