<template>
  <div>
    <el-card>
      <div style="padding: 8px">
        <el-button type="primary" @click="newArtwork()" v-preReClick>新增图稿</el-button>
      </div>
      <div
        v-infinite-scroll="load"
        class="infinite-list"
        style="overflow-y: auto; overflow-x: hidden; height: calc(100vh - 208px); display: flex; flex-wrap: wrap"
        :infinite-scroll-disabled="scrollDisabled"
        :infinite-scroll-immediate="false"
        :infinite-scroll-distance="100">
        <template v-if="tableData && tableData.length > 0">
          <div v-for="(item, index) in tableData" :key="index" style="margin: 0 40px 40px 0; text-align: center">
            <div v-if="item.imgUrl">
              <el-image
                style="cursor: pointer; border-radius: 5px; height: 26vh"
                :src="item.imgUrl"
                :zoom-rate="1.2"
                :preview-src-list="tableData.map((row) => row.imgUrl)"
                :initial-index="index"
                fit="cover" />
            </div>
            <div style="margin: 5px 0; white-space: nowrap; text-overflow: ellipsis">{{ item.artworkName }}</div>
            <div style="margin: 5px 0; display: flex; justify-content: space-between">
              <el-button type="primary" @click="clickUpdate(item)" text>编辑</el-button>
              <el-button type="danger" @click="clickDelete(item)" text>删除</el-button>
            </div>
          </div>
        </template>
      </div>
    </el-card>

    <el-dialog :title="modalType == 'add' ? '新增图稿' : '编辑图稿'" v-if="openDialog" v-model="openDialog" width="700">
      <el-form :model="formData.data" label-width="100px" :rules="rules" ref="submit">
        <el-form-item label="图稿名称:" prop="artworkName">
          <el-input v-model="formData.data.artworkName" placeholder="请输入图稿名称" :maxlength="300" />
        </el-form-item>
        <el-form-item label="事业部:" prop="departmentId" v-if="proxy.useUserStore().user.deptId === '100'">
          <el-select v-model="formData.data.departmentId" placeholder="请选择事业部" style="width: 100%" clearable>
            <el-option v-for="item in departmentList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
          </el-select>
        </el-form-item>
        <el-form-item label="图稿文件:" required style="width: 100%">
          <el-upload
            v-model:fileList="fileList"
            action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
            :data="uploadData"
            :before-upload="uploadFile"
            :on-success="handleSuccess"
            :on-preview="onPreviewFile"
            :limit="1"
            style="width: 100%">
            <el-button style="background: #20b2aa; color: #fff; border: 1px solid #20b2aa">上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="图稿图片:" required>
          <el-upload
            class="avatar-uploader"
            action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
            :data="uploadMainData"
            :show-file-list="false"
            :on-success="handleMainSuccess"
            :before-upload="uploadMainFile">
            <el-image v-if="formData.data.imgUrl" :src="formData.data.imgUrl" fit="scale-down" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="openDialog = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large" v-preReClick>确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const departmentList = ref([]);
const sourceList = ref({
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 30,
    departmentId: proxy.useUserStore().user.deptId === "100" ? "" : proxy.useUserStore().user.deptId,
  },
});
const tableData = ref([]);
const scrollDisabled = ref(false);
const load = () => {
  proxy.post("/artworkLibrary/page", sourceList.value.pagination).then((res) => {
    tableData.value = tableData.value.concat(res.rows);
    sourceList.value.pagination.total = res.total;
    if (sourceList.value.pagination.total > sourceList.value.pagination.pageNum * sourceList.value.pagination.pageSize) {
      sourceList.value.pagination.pageNum++;
      scrollDisabled.value = false;
    } else {
      scrollDisabled.value = true;
    }
  });
};
load();
const getDemandData = () => {
  proxy.post("/department/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      departmentList.value = res.rows.map((item) => {
        return {
          dictKey: item.id,
          dictValue: item.name,
        };
      });
    }
  });
};
getDemandData();
const modalType = ref("add");
const openDialog = ref(false);
const formData = reactive({
  data: {},
});
const rules = ref({
  artworkName: [{ required: true, message: "请输入图稿名称", trigger: "blur" }],
  departmentId: [{ required: true, message: "请选择事业部", trigger: "change" }],
});
const uploadData = ref({});
const fileList = ref([]);
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;
  file.uploadState = true;
  return true;
};
const handleSuccess = (any, UploadFile) => {
  UploadFile.raw.uploadState = false;
};
const uploadMainData = ref({});
const uploadMainFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadMainData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  return true;
};
const handleMainSuccess = (response, uploadFile) => {
  formData.data.imgId = uploadFile.raw.id;
  formData.data.imgName = uploadFile.raw.fileName;
  formData.data.imgUrl = uploadFile.raw.fileUrl;
};
const newArtwork = () => {
  fileList.value = [];
  modalType.value = "add";
  formData.data = {
    artworkName: "",
    imgId: "",
    imgName: "",
    imgUrl: "",
    fileId: "",
    fileName: "",
    fileUrl: "",
  };
  openDialog.value = true;
};
const submitForm = () => {
  proxy.$refs.submit.validate((valid) => {
    if (valid) {
      if (fileList.value && fileList.value.length > 0) {
        if (formData.data.imgUrl) {
          formData.data.fileId = fileList.value[0].raw.id;
          formData.data.fileName = fileList.value[0].raw.fileName;
          formData.data.fileUrl = fileList.value[0].raw.fileUrl;
          if (proxy.useUserStore().user.deptId !== "100") {
            formData.data.departmentId = proxy.useUserStore().user.deptId;
          }
          proxy.post("/artworkLibrary/" + modalType.value, formData.data).then(() => {
            ElMessage({
              message: modalType.value == "add" ? "添加成功" : "编辑成功",
              type: "success",
            });
            openDialog.value = false;
            tableData.value = [];
            sourceList.value.pagination.pageNum = 1;
            load();
          });
        } else {
          return ElMessage("请上传图稿图片");
        }
      } else {
        return ElMessage("请上传图稿文件");
      }
    }
  });
};
const openFile = (path) => {
  window.open(path);
};
const clickUpdate = (row) => {
  modalType.value = "edit";
  formData.data = proxy.deepClone(row);
  fileList.value = [
    {
      raw: {
        id: row.fileId,
        fileName: row.fileName,
        fileUrl: row.fileUrl,
      },
      name: row.fileName,
      url: row.fileUrl,
    },
  ];
  openDialog.value = true;
};
const clickDelete = (row) => {
  ElMessageBox.confirm("你是否确认此操作", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      proxy.post("/artworkLibrary/delete", { id: row.id }).then(() => {
        ElMessage({ message: "删除成功", type: "success" });
        openDialog.value = false;
        tableData.value = [];
        sourceList.value.pagination.pageNum = 1;
        load();
      });
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 148px;
  height: 148px;
  display: block;
  background-color: black;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
}
</style>
