<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    title="用采数据管理"
    draggable
  >
    <el-form label-width="auto" :model="form" inline class="formBox">
      <el-form-item label="关键字">
        <el-input
          v-model="form.searchValue"
          placeholder="关键字查询"
          clearable
          style="width: 180px"
          size="small"
        />
      </el-form-item>
      <div class="mt5">
        <el-button
          type="primary"
          :icon="Search"
          size="small"
          @click="getTableData"
          >查询</el-button
        >
        <el-button type="primary" :icon="Plus" size="small" @click="uploadFile"
          >新增</el-button
        >
        <el-button
          type="primary"
          :icon="Download"
          @click="exportTable"
          size="small"
          >导出
        </el-button>
      </div>
    </el-form>

    <div class="tableBox">
      <el-table
        :scrollbar-always-on="true"
        :data="tableData"
        height="400px"
        size="small"
        :header-cell-style="{ textAlign: 'center' }"
        v-loading="loading1"
        element-loading-background="#343849c7"
        border
      >
        <el-table-column prop="name" align="center" label="表名" />
        <el-table-column
          prop="startTime"
          align="center"
          label="起始时间"
          width="150"
        />
        <el-table-column
          prop="endTime"
          align="center"
          label="截止时间"
          width="150"
        />
        <el-table-column prop="updateTime" align="center" label="更新时间" />
        <el-table-column fixed="right" align="center" label="操作" width="140">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              v-if="row.integrity == 1"
              @click="handleClick(row)"
              >完整性详情</el-button
            >
            <el-button
              link
              type="danger"
              size="small"
              @click.stop="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      size="small"
      style="margin-top: 10px"
      :currentPage="form.pageNum"
      :page-size="form.pageSize"
      :page-sizes="[10, 20, 50, 100, 200]"
      background
      :layout="'sizes,total, ->, prev, pager, next, jumper'"
      :total="total"
      @size-change="onTableSizeChange"
      @current-change="onTableCurrentChange"
    ></el-pagination>
  </el-dialog>
  <!-- 详情 -->
  <completenessDetails ref="completenessDetailsRef" @close="close" />
  <el-dialog
    v-model="dialogVisible"
    draggable
    title="上传数据"
    width="500"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-upload
      ref="upload"
      action=""
      v-model:file-list="fileList"
      accept=".xlsx,.xls"
      :auto-upload="false"
      :on-change="choose"
      :limit="2"
    >
      <el-button type="primary" :icon="Upload" size="small">上传文件</el-button>
    </el-upload>
    <template #footer>
      <el-button @click="handleClose" size="small">取消</el-button>
      <el-button
        type="primary"
        @click="submitupload"
        :loading="loading"
        size="small"
        >确认</el-button
      >
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import completenessDetails from "./completenessDetails.vue";
import type { UploadInstance } from "element-plus";
import { Search, Plus, Upload, Download } from "@element-plus/icons-vue";
import { useStore } from "vuex";
import * as XLSX from "xlsx";
import { ElMessage , ElMessageBox} from "element-plus";
import {
  userDataList,
  uploadUserData,
  deleteUserDataByIds,
} from "@/api/manage_wx";
const store = useStore();
const visible = ref(false);
const openDialog = () => {
  visible.value = true;
};

const form = reactive({
  searchValue: "",
  pageNum: 1,
  pageSize: 20,
});
const total = ref(0); // 假设总条数为100
const tableData = ref([]);

const completenessDetailsRef = ref();
const dialogVisible = ref(false);
const upload = ref<UploadInstance>();
const fileList = ref([]);
const loading = ref(false);
const loading1 = ref(false);

// 关闭上传弹框
const handleClose = () => {
  fileList.value = [];
  dialogVisible.value = false;
  visible.value = true;
  getTableData();
};
// 详情关闭弹框
const close = () => {
  visible.value = true;
};
// 新增
const uploadFile = () => {
  dialogVisible.value = true;
  visible.value = false;
};

// 上传
const choose = (e: any) => {
  upload.value!.clearFiles();
  setTimeout(() => {
    if (e.name.includes(".xls")) {
      fileList.value = [e];
    } else {
      ElMessage.warning("请上传Excel文件！");
    }
  }, 0);
};

// 上传
const submitupload = async () => {
  if (fileList.value.length == 0) {
    ElMessage.warning("请上传文件！");
    return;
  }
  ElMessage.info("上传中,请稍等...");
  const formData = new FormData();
  formData.append("file", fileList.value[0].raw);
  loading.value = true;
  uploadUserData(formData)
    .then((res) => {
      ElMessage.success("上传成功");
      loading.value = false;
      handleClose();
      // tableStore.index();
    })
    .catch((err) => {
      loading.value = false;
    });
};
// provide("tableStore", tableStore);
// tableStore.table.params.searchValue = "";

const onTableSizeChange = (size: number) => {
  form.pageSize = size;
  // 重新加载数据
  getTableData();
};
const onTableCurrentChange = (page: number) => {
  form.pageNum = page;
  // 重新加载数据
  getTableData();
};

const getTableData = async () => {
  loading1.value = true;
  // form.deptId = store.state.deptId;
  const res: any = await userDataList(form);

  if (res.code == "A0000") {
    tableData.value = res.data.records;

    total.value = res.data.total;
  }
  loading1.value = false;
};

// 完整性详情
const handleClick = (row) => {
  visible.value = false;
  completenessDetailsRef.value.open(row);
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm("确定删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteUserDataByIds([row.id]).then(() => {
        ElMessage.success("删除成功");
        getTableData();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除取消",
      });
    });
};

// 导出
const exportTable = async () => {
  let columnExpor: any = [
    [
      "表名",
      "起始时间",
      "截止时间",
      "更新时间",
    ],
  ];

  let list = [];

  await userDataList({
    ...form,
    pageNum: 1,
    pageSize: total.value,
  }).then((res) => {
    let data = res.data.records.map((item) => {
      return [
        item.name,
        item.startTime,
        item.endTime,
        item.updateTime,
      ];
    });
    list = [...columnExpor, ...data];
    // 创建工作表
    const worksheet = XLSX.utils.aoa_to_sheet(list);

    worksheet["!cols"] = list.map((col) => ({ wch: 20 }));

    // 创建工作簿
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "用采数据管理");

    // 写出文件
    XLSX.writeFile(workbook, "用采数据管理" + ".xlsx");
  });
};

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

defineExpose({
  openDialog,
});
</script>

<style lang="scss" scoped>
@use "@/assets/scss/index.scss";
.tableBox {
  padding: 0px !important;
}
.formBox {
  display: flex;
  justify-content: space-between;
}
:deep(.el-upload-list__item-name) {
  color: #fff;
}
:deep(.el-upload-list__item:hover) {
  .el-upload-list__item-name {
    color: #909399;
  }
}
</style>
