<template>
  <div class="content-box">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">系统设置</span>
    </div>
    <div class="scroll">
      <h4>小程序首页封面轮播图设置</h4>
      <p>可上传多张图片</p>
      <div class="img-upload-wrap">
        <!-- 2. 自己循环纯链接数组fileList，展示图片（核心：自定义渲染） -->
        <div class="img-preview-list" v-if="fileList.length > 0">
          <div class="img-item" v-for="(url, index) in fileList" :key="index">
            <!-- 替换原生img为el-image，新增preview相关属性 -->
            <img
              :src="url"
              alt="图片预览"
              class="preview-img"
              @click="handlePreview(fileList, index)"
            />
            <span
              v-if="!disabled"
              class="delete-btn"
              @click="handleDelete(index)"
            >
              <el-icon><Delete /></el-icon>
            </span>
          </div>
          <ImgCutter v-if="!disabled" @getUrl="getUrl" />
          <!-- <el-upload
            v-if="!disabled"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            class="upload-btn"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
            <span class="upload-txt">点击上传图片</span>
          </el-upload> -->
        </div>
      </div>

      <h4>联系我们设置</h4>
      <p>
        <span>联系地址 : </span>
        <el-input
          :disabled="disabled"
          clearable
          v-model.trim="address"
          class="w-50 m-2"
          placeholder="请输入联系地址"
          style="width: 220px; margin-left: 15px"
        />
      </p>
      <p>
        <span>联系邮箱 : </span>
        <el-input
          :disabled="disabled"
          clearable
          v-model.trim="email"
          class="w-50 m-2"
          placeholder="请输入联系邮箱"
          style="width: 220px; margin-left: 15px"
        />
      </p>
      <p>
        <span>联系电话 : </span>
        <el-input
          :disabled="disabled"
          clearable
          v-model.trim="phone"
          class="w-50 m-2"
          placeholder="请输入联系电话"
          style="width: 220px; margin-left: 15px"
        />
      </p>
      <p>
        <el-button v-if="disabled" @click="edit" type="primary">编辑</el-button>
        <el-button v-if="!disabled" @click="confirm" type="primary"
          >确认</el-button
        >
        <el-button v-if="!disabled" @click="cancel">取消</el-button>
      </p>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  watch,
  reactive,
  nextTick,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { genFileId, ElMessage, ElMessageBox } from "element-plus";
import { dayjs } from "element-plus";

import { storeToRefs } from "pinia";
import { useCounterStore } from "@/stores/index";

import { api as viewerApi } from "v-viewer";

import { getQueryAlumniSystem, updateAlumniSystem } from "@/api/system.js";
import { uploadFile } from "@/api/uploadFile.js";

import ImgCutter from "@/components/ImgCutter.vue";

const router = useRouter();
const store = useCounterStore();

// 为避免解构时失去响应性
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";

const { name, age, isCollapse, realAge, collegeRole } = storeToRefs(store);

const id = ref("");
const address = ref("");
const email = ref("");
const phone = ref("");
const fileList = ref([]);

const disabled = ref(true);

const getList = async () => {
  let res = await getQueryAlumniSystem();
  console.log(res);

  if (res.code == 200) {
    address.value = res.data.address;
    email.value = res.data.email;
    id.value = res.data.id;
    phone.value = res.data.phone;
    fileList.value = res.data.files;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};

const handleDelete = (index) => {
  fileList.value.splice(index, 1);
};

const handlePreview = (images, index) => {
  // 核心：复制数组，把点击的图片移到第一位
  const newImages = [...images]; // 拷贝原数组，避免修改原数据
  const currentImg = newImages.splice(index, 1)[0]; // 取出当前点击的图片
  newImages.unshift(currentImg); // 放到数组开头

  // 传给预览器，此时插件显示的第一张就是点击的图片
  viewerApi({
    images: newImages,
    zIndex: 3000,
    initial: index, // 添加这一行
  });
};

// 上传前的校验
const beforeUpload = (file) => {
  // 校验文件类型
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("只能上传图片格式文件");
    return false;
  }
  // 校验文件大小（2MB）
  const isLt2M = file.size / 1024 / 1024 < 4;
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过4MB");
    return false;
  }
  return true;
};

// 文件选择变化时触发
const handleFileChange = async (file, newFileList) => {
  console.log(file);
  let formData = new FormData();
  formData.append("file", file.raw);
  let res = await uploadFile(formData);
  // console.log(res.data.fileUrl);
  if (res.code == 200) {
    fileList.value.push(res.data.fileUrl); // 赋值给响应式fileList，页面自动刷新
    // ElMessage({
    //   type: "success",
    //   showClose: true,
    //   message: res.message,
    //   center: true,
    // });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
const getUrl = (res) => {
  if (res.code == 200) {
    fileList.value.push(res.data.fileUrl); // 赋值给响应式fileList，页面自动刷新
    // ElMessage({
    //   type: "success",
    //   showClose: true,
    //   message: res.message,
    //   center: true,
    // });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};

const edit = () => {
  disabled.value = false;
};
const confirm = async () => {
  let res = await updateAlumniSystem({
    id: id.value,
    address: address.value,
    email: email.value,
    phone: phone.value,
    files: fileList.value,
  });
  console.log(res);
  if (res.code == 200) {
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.message,
      center: true,
    });
    disabled.value = true;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
const cancel = () => {
  disabled.value = true;
  getList();
};

onBeforeMount(() => {
  getList();
});
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.content-box {
  width: calc(100% - 40px);
  height: calc(100% - 105px);
  margin: 20px auto;
  background-color: #fff;
  color: #000;
  display: flex;
  flex-direction: column;

  .svg {
    width: 22px;
    height: 22px;
  }

  .left {
    width: calc(100% - 60px);
    height: 60px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ccc;
    color: #000;
    font-size: 18px;
    font-weight: 600;
    .camera {
      margin-right: 15px;
      color: #4392f7;
    }
  }
  .scroll {
    width: calc(100% - 60px);
    height: calc(100% - 61px);
    margin: 0 auto;
    // display: flex;
    // flex-direction: column;
    overflow: auto;
    h4 {
      margin: 20px 0;
      font-size: 18px;
    }
    p {
      margin: 0 0 15px 0;
    }
    .img-upload-wrap {
      width: 100%;
      padding: 0 10px 0;
    }
    /* 上传按钮样式：自定义，可根据需求修改 */
    :deep(.el-upload) {
      width: 140px;
      height: 140px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
