<template>
  <div class="user">
    <div class="tree">
      <treeList
        title="网盘目录"
        submitType="1"
        :data="treeListData"
        v-model="sourceList.pagination.productClassifyId"
        @change="treeChange"
        @changeTreeList="getTreeList"
        @treeDelete="getList">
      </treeList>
    </div>
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :action-list="[
          {
            text: '上传文件',
            action: () => openModal(),
            disabled: false,
          },
        ]"
        @get-list="getList">
        <template #name="{ item }">
          <div>
            <a style="color: #409eff; cursor: pointer" @click="clickName(item)">{{ item.name }}</a>
          </div>
        </template>
        <template #fileSize="{ item }">
          <div>
            <div v-if="item.type === 2">
              {{ getSize(item) }}
            </div>
          </div>
        </template>
      </byTable>
    </div>

    <el-dialog title="上传文件" v-if="dialogVisible" v-model="dialogVisible" width="500" v-loading="loadingDialog">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #productFile>
          <div style="width: 100%">
            <el-upload
              v-model:fileList="fileList"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              :data="uploadData"
              multiple
              :before-upload="uploadFile"
              :on-preview="onPreviewFile">
              <el-button>上传文件</el-button>
            </el-upload>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import treeList from "@/components/webDiskData/treeList";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { computed, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const treeListData = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    parentFolderId: "",
    keyword: "",
  },
});
const treeChange = (e) => {
  sourceList.value.pagination.parentFolderId = e.id;
  sourceList.value.pagination.pageNum = 1;
  getList();
};
const getTreeList = () => {
  proxy.get("/netdisk/tree", {}).then((res) => {
    treeListData.value = res.data;
  });
};
const loading = ref(false);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/netdisk/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    loading.value = false;
  });
};
getTreeList();
getList();
const config = computed(() => {
  return [
    {
      attrs: {
        label: "文件名称",
        slot: "name",
      },
    },
    {
      attrs: {
        label: "类型",
        prop: "type",
        width: 120,
      },
      render(type) {
        return type == 1 ? "文件夹" : type == 2 ? "文件" : "";
      },
    },
    {
      attrs: {
        label: "大小",
        slot: "fileSize",
        width: 160,
      },
    },
    {
      attrs: {
        label: "创建人",
        prop: "createUserName",
        width: 140,
      },
    },
    {
      attrs: {
        label: "创建时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "操作",
        width: "100",
        align: "center",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "删除",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                proxy.post("/netdisk/delete", [row.id]).then(() => {
                  ElMessage({
                    message: "删除成功",
                    type: "success",
                  });
                  if (row.type === 1) {
                    getTreeList();
                  }
                  getList();
                });
              });
            },
          },
        ];
      },
    },
  ];
});
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const fileList = ref([]);
const uploadData = ref({});
const formData = reactive({
  data: {
    type: 2,
  },
});
const formConfig = computed(() => {
  return [
    {
      type: "treeSelect",
      prop: "parentFolderId",
      label: "网盘目录",
      data: treeListData.value,
      propsTreeLabel: "name",
      propsTreeChildren: "netdiskList",
    },
    {
      type: "slot",
      slotName: "productFile",
      prop: "fileList",
      label: "文件",
    },
  ];
});
let rules = ref({
  parentFolderId: [{ required: true, message: "请选择网盘目录", trigger: "change" }],
});
const openModal = () => {
  formData.data = {
    type: 2,
  };
  fileList.value = [];
  loadingDialog.value = false;
  dialogVisible.value = true;
};
const uploadFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  return true;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (fileList.value && fileList.value.length > 0) {
      formData.data.fileList = fileList.value.map((item) => {
        return {
          id: item.raw.id,
          fileName: item.raw.fileName,
          fileSize: item.raw.size,
        };
      });
      loadingDialog.value = true;
      proxy.post("/netdisk/add", formData.data).then(
        () => {
          ElMessage({
            message: "上传成功",
            type: "success",
          });
          dialogVisible.value = false;
          getList();
        },
        (err) => {
          console.log(err);
          loadingDialog.value = false;
        }
      );
    } else {
      return ElMessage("请上传文件");
    }
  });
};
const clickName = (item) => {
  if (item.type === 2) {
    proxy.post("/fileInfo/getList", { businessIdList: [item.id] }).then((res) => {
      window.open(res[item.id][0].fileUrl, "_blank");
    });
  } else {
    sourceList.value.pagination.pageNum = 1;
    sourceList.value.pagination.parentFolderId = item.id;
    getList();
  }
};
const getSize = (item) => {
  let size = "";
  if (1024 > item.fileSize) {
    size = item.fileSize + "B";
  } else if (1024 * 1024 > item.fileSize) {
    size = parseFloat(Number(item.fileSize) / 1024).toFixed(2) + "KB";
  } else if (1024 * 1024 * 1024 > item.fileSize) {
    size = parseFloat(Number(item.fileSize) / 1024 / 1024).toFixed(2) + "MB";
  } else if (1024 * 1024 * 1024 * 1024 > item.fileSize) {
    size = parseFloat(Number(item.fileSize) / 1024 / 1024 / 1024).toFixed(2) + "GB";
  }
  return size;
};
</script>

<style lang="scss" scoped>
.user {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  .tree {
    width: 300px;
  }
  .content {
    width: calc(100% - 320px);
  }
}
.pic {
  object-fit: contain;
  width: 50px;
  height: 50px;
  cursor: pointer;
  vertical-align: middle;
}
</style>
