<template>
  <el-card>
    <div>
      <pure-table
        row-key="id"
        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 #operation="{ row, index }">
          <div v-if="!editMap[index]?.editable">
            <el-button
              v-if="
                useUserStoreHook().existsRole(['opt', 'admin', 'eng', 'root'])
              "
              class="reset-margin"
              link
              type="primary"
              :icon="useRenderIcon(Delete)"
              @click="handleDeleteProject(row)"
            >
              删除
            </el-button>
            <el-button
              v-if="
                useUserStoreHook().existsRole(['opt', 'admin', 'eng', 'root'])
              "
              class="reset-margin"
              link
              type="primary"
              @click="handleEditProject(row)"
              :icon="useRenderIcon(EditFill)"
            >
              修改
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :icon="useRenderIcon(OpenPreview)"
              @click="handleViewProject(row)"
            >
              查看
            </el-button>
          </div>

          <div v-if="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="dlgAddProjectVisible"
      title="项目信息"
      width="60%"
      :before-close="handleDlgClose"
      destroy-on-close
      top="6vh"
    >
      <EditProject
        :selProject="selProject"
        :swEditable="swEditable"
        @onSubmitData="onSubmitProjectData"
      />
      <!-- <template #footer>
      <span class="dialog-footer">
        <el-button @click="dlgAddProjectVisible = 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 OpenPreview from "~icons/codicon/open-preview";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import * as XLSX from "xlsx";
import importExcel from "./importExcel.vue";
import EditProject from "./edit.vue";
import Project from "@/model/project.js";
import { useUserStoreHook } from "@/store/modules/user";

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

const swEditable = ref(true);
const tableKey = ref(0);
const vGlobal = window.vueGlobal;
const dlgAddProjectVisible = ref(false);

const selProject = ref(new Project());

const reloadProjects = () => {
  vGlobal.refreshProjects(() => {
    dataList.value = [];
    dataList.value = vGlobal.vecProject.filter(item => item.status == 2); // 深拷贝，触发视图更新
    console.log("reloadProjects", dataList.value);
    tableKey.value += 1;
    pagination.total = dataList.value.length;
  });
};

const handleAddProject = () => {
  swEditable.value = true;
  selProject.value = new Project();
  dlgAddProjectVisible.value = true;
};

const handleEditProject = (row: Project) => {
  swEditable.value = true;
  selProject.value = row;
  dlgAddProjectVisible.value = true;
};

const handleViewProject = (row: Project) => {
  swEditable.value = false;
  selProject.value = new Project(row);
  dlgAddProjectVisible.value = true;
};

const handleDeleteProject = (row: Project) => {
  ElMessageBox.confirm("确定删除项目?删除后将无法撤回", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      vGlobal.deleteProject(row, () => {
        ElNotification.success({
          message: "删除成功"
        });
        reloadProjects();
      });
    })
    .catch(() => {});
};

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

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

onMounted(() => {
  reloadProjects();
});
</script>
