<template>
  <el-card>
    <template #header>
      <div
        v-if="useUserStoreHook().existsRole(['eng', 'root'])"
        class="card-header"
      >
        <span style="margin-right: 10px">
          启用编辑
          <el-switch
            v-model="swEditable"
            class="ml-2"
            inline-prompt
            style="--el-switch-off-color: #666666"
          />
        </span>

        <el-button @click="handleExport"> 导出到Excel </el-button>

        <el-button
          v-if="swEditable"
          type="primary"
          @click="dlgImportExcelVisible = true"
        >
          从Excel导入
        </el-button>

        <el-button v-if="swEditable" type="primary" @click="updateAnchors">
          更新数据库
        </el-button>

        <el-button @click="reloadAnchors"> 重置列表 </el-button>

        <el-button
          v-if="swEditable"
          :icon="useRenderIcon(AddFill)"
          @click="onAdd"
        >
          添加一行数据
        </el-button>
      </div>
    </template>

    <div>
      <pure-table
        align-whole="center"
        :header-cell-style="{
          background: 'var(--el-fill-color-light)',
          color: 'var(--el-text-color-primary)'
        }"
        :columns="columns"
        :table-key="tableKey"
        border
        adaptive
        :adaptiveConfig="adaptiveConfig"
        showOverflowTooltip
        :loading="false"
        :loading-config="loadingConfig"
        :data="
          dataList.slice(
            (pagination.currentPage - 1) * pagination.pageSize,
            pagination.currentPage * pagination.pageSize
          )
        "
        :pagination="pagination"
        @page-size-change="onSizeChange"
        @page-current-change="onCurrentChange"
      >
        <template #toolbar>
          <el-button plain size="small">查看日志</el-button>
          <el-button plain size="small">导出数据</el-button>
          <el-button type="primary" size="small">添加一行数据</el-button>
        </template>

        <template #operation="{ row, index }">
          <div v-if="swEditable && !editMap[index]?.editable">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :icon="useRenderIcon(Delete)"
              @click="onDel(row)"
            >
              删除
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              @click="onEdit(row, index)"
              :icon="useRenderIcon(EditFill)"
            >
              修改
            </el-button>
          </div>

          <div v-if="swEditable && editMap[index]?.editable">
            <el-button
              class="reset-margin"
              link
              type="primary"
              @click="onSave(index)"
              :icon="useRenderIcon(SaveFill)"
            >
              保存
            </el-button>
            <el-button
              class="reset-margin"
              link
              @click="onCancel(index)"
              :icon="useRenderIcon(Close)"
            >
              取消
            </el-button>
          </div>
        </template>
      </pure-table>
    </div>

    <el-dialog
      v-model="dlgImportExcelVisible"
      title="Excel导入"
      width="60%"
      :before-close="handleDlgClose"
      destroy-on-close
      top="6vh"
    >
      <importExcel ref="importExcelRef" @onExcelData="onExcelData" />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dlgImportExcelVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDlgConfirm"> 导入 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

import { useColumns } from "./columns";
import Empty from "../empty.svg?component";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import AddFill from "~icons/ep/plus";
import Delete from "~icons/ep/delete";
import EditFill from "~icons/ep/edit";
import SaveFill from "~icons/bi/save";
import Close from "~icons/ep/close";
import { ElNotification, ElMessageBox } from "element-plus";
import * as XLSX from "xlsx";
import importExcel from "./importExcel.vue";
import { useUserStoreHook } from "@/store/modules/user";

const {
  loading,
  editMap,
  columns,
  dataList,
  options,
  pagination,
  loadingConfig,
  adaptiveConfig,
  onEdit,
  onSave,
  onCancel,
  onAdd,
  onDel,
  onSizeChange,
  onCurrentChange
} = useColumns();

const swEditable = ref(false);
const tableKey = ref(0);
const vGlobal = window.vueGlobal;
const dlgImportExcelVisible = ref(false);
const excelData = ref([]);

const reloadProjects = () => {
  // vGlobal.refreshProjects(() => {
  //   options.value = [];
  //   options.value.push({
  //     label: "无项目",
  //     value: 0
  //   });
  //   for (const p of vGlobal.vecProject) {
  //     options.value.push({
  //       label: p.name,
  //       value: p.id
  //     });
  //   }
  //   console.log("reloadProjects", options.value);
  //   tableKey.value += 1;
  // });

  options.value = [];
  options.value.push({
    label: "无项目",
    value: 0
  });
  for (const p of vGlobal.vecProject) {
    options.value.push({
      label: p.name,
      value: p.id
    });
  }
  console.log("reloadProjects", options.value);
  tableKey.value += 1;
};

const reloadAnchors = () => {
  vGlobal.refreshAnchors(() => {
    dataList.value = [];
    dataList.value = vGlobal.vecAnchor.map(item => item); // 深拷贝，触发视图更新
    console.log("reloadAnchors", dataList.value);
    tableKey.value += 1;
    pagination.total = dataList.value.length;
  });
};

const updateAnchors = () => {
  ElMessageBox.confirm("确定更新基站数据?更新后将无法撤回", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      ElNotification.info({
        message: "开始更新"
      });
      const vec = [];
      for (const v of dataList.value) {
        vec.push(v);
      }
      vGlobal.updateAnchors(vec, () => {
        ElNotification.success({
          message: "更新成功"
        });
        reloadAnchors();
      });
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: 'Delete canceled',
      // })
    });
};

// 导出逻辑
const handleExport = () => {
  try {
    // 1. 处理导出数据
    const exportData = dataList.value.map(item => ({
      // 只导出需要的字段，并映射为中文表头
      id: item.id,
      imei: item.imei,
      iccid: item.iccid,
      projId: item.projId
    }));

    if (exportData.length === 0) {
      ElNotification.warning({ message: "没有可导出的数据" });
      return;
    }

    // 2. 创建工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData);

    // 3. 计算列宽（关键步骤）
    const header = Object.keys(exportData[0]);
    const cols = header.map(key => {
      // 计算表头文字长度
      let maxLength = key.length * 2;

      // 计算数据列最大文字长度
      exportData.forEach(row => {
        const value = String(row[key] || "");
        // 中文字符宽度约为英文字符的2倍，这里做特殊处理
        const length = value.replace(/[^\x00-\xff]/g, "aa").length;
        if (length > maxLength) {
          maxLength = length;
        }
      });

      // 增加缓冲宽度（避免内容太满）
      return { width: maxLength + 2 };
    });

    // 设置列宽配置
    worksheet["!cols"] = cols;

    // 4. 创建工作簿并添加工作表
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "基站列表");

    // 5. 生成Excel文件并下载
    const fileName = `基站列表_${new Date().getTime()}.xlsx`;
    XLSX.writeFile(workbook, fileName);
  } catch (error) {
    console.error("导出失败:", error);
    ElNotification.error({
      message: "导出失败，请重试"
    });
  }
};

const handleDlgConfirm = () => {
  // 将导入的数据合并到dataList
  dataList.value = [];
  for (const v of excelData.value) {
    dataList.value.push(v);
  }
  tableKey.value += 1;
  dlgImportExcelVisible.value = false;
  pagination.total = dataList.value.length;
};

const handleDlgClose = (done: () => void) => {
  ElMessageBox.confirm("确定要关闭这个对话框吗?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};

const onExcelData = (data: any[]) => {
  console.log("onExcelData", data);
  excelData.value = data;
};

onMounted(() => {
  reloadProjects();
  reloadAnchors();

  console.log(
    "exist",
    useUserStoreHook().existsRole(["opt", "admin", "eng", "root"])
  );
});
</script>
