<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">
          <div class="img-item" v-for="(url, index) in fileList" :key="index">
            <!-- 替换原生img为el-image，新增preview相关属性 -->
            <img :src="url" alt="图片预览" class="preview-img" v-viewer />
            <span
              v-if="!disabled"
              class="delete-btn"
              @click="handleDelete(index)"
            >
              <el-icon><Delete /></el-icon>
            </span>
          </div>
          <ImgCutter v-if="!disabled" @getUrl="getUrl" />
        </div>
      </div>

      <h4>组织主页聊天群联系方式配置</h4>
      <div class="img-preview-list">
        <div
          class="img-item"
          v-for="(url, index) in chitchatImage"
          :key="index"
        >
          <img :src="url" alt="图片预览" class="preview-img" v-viewer />
          <span class="delete-btn" @click="handleChitchatDelete(index)">
            <el-icon><Delete /></el-icon>
          </span>
        </div>
        <el-upload
          v-if="!disabled"
          action="#"
          :auto-upload="false"
          :on-change="handleChitchatChange"
          :before-upload="beforeUpload"
          class="upload-btn"
          accept="image/*"
        >
          <el-icon><Plus /></el-icon>
          <span class="upload-txt">点击上传图片</span>
        </el-upload>
      </div>
      <p style="margin-top: 15px">
        <span>提示语 : </span>
        <el-input
          :disabled="disabled"
          clearable
          v-model.trim="reminder"
          class="w-50 m-2"
          placeholder="请输入提示语"
          style="width: 220px; margin-left: 15px"
        />
      </p>

      <h4>电子刊物</h4>
      <el-button v-if="!disabled" @click="addDZKW" type="primary"
        >新增</el-button
      >
      <ul class="dzkw">
        <li v-for="(item, index) in schoolValue" :key="index">
          <span>名称 : </span>
          <el-input
            :disabled="disabled"
            clearable
            v-model.trim="item.schoolName"
            class="w-50 m-2"
            placeholder="请输入名称"
            style="width: 220px; margin: 0 30px 0 15px"
          />
          <span>链接地址 : </span>
          <el-input
            :disabled="disabled"
            clearable
            v-model.trim="item.schoolUrl"
            class="w-50 m-2"
            placeholder="请输入链接地址"
            style="width: 400px; margin: 0 15px"
          />
          <el-button v-if="schoolValue.length > 1 && !disabled" @click="deleteDZKW(index)" type="danger" :icon="Delete" circle />
        </li>
      </ul>

      <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="userName"
          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>
      <h4>校友总会介绍</h4>
      <p>
        <Richtext
          v-if="richtextShow"
          @richtextClick="richtextClick"
          :fatherMessage="fatherMessage"
        ></Richtext>
      </p>
      <h4>校友总会规章制度</h4>
      <p>
        <Richtext2
          v-if="richtextShow2"
          @richtextClick="richtextClick2"
          :fatherMessage="fatherMessage2"
        ></Richtext2>
      </p>
      <h4>捐赠方式</h4>
      <p>
        <Richtext3
          v-if="richtextShow3"
          @richtextClick="richtextClick3"
          :fatherMessage="fatherMessage3"
        ></Richtext3>
      </p>

      <p>
        <el-button
          v-if="disabled && menuList.canUpdate"
          @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";

import Richtext from "./Richtext.vue";
import Richtext2 from "./Richtext.vue";
import Richtext3 from "./Richtext.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 menuList = ref({
  canAll: null,
  canApply: null,
  canDeleted: null,
  canDetail: null,
  canExport: null,
  canImport: null,
  canInsert: null,
  canTop: null,
  canUpdate: null,
  canView: null,
});

const id = ref("");
const address = ref(""); // 联系地址
const email = ref(""); // 联系邮箱
const phone = ref(""); // 联系电话
const fileList = ref([]); // 轮播图数据集合
const chitchatImage = ref([]); // 上传图片
const reminder = ref(); // 提示语
const userName = ref(); // 联系人
const schoolValue = ref([{}, {}]);

const richtextShow = ref(false);
const richtextShow2 = ref(false);
const richtextShow3 = ref(false);
const intro = ref([]); // 校友总会介绍
const rules = ref([]); // 校友总会规章制度
const donation = ref([]); // 捐赠方式

const disabled = ref(true);

const fatherMessage = ref({
  data: "",
  flag: false,
});
// 富文本传过来的数据
const richtextClick = (data) => {
  // console.log(data, "富文本传过来的数据");
  // params.value.safetyNotice = data.html;
  fatherMessage.value.data = data.html;
  intro.value = data.html;
  // accountRuleForm.contentText = data.text;
};

const fatherMessage2 = ref({
  data: "",
  flag: false,
});
// 富文本传过来的数据
const richtextClick2 = (data) => {
  // console.log(data, "富文本传过来的数据");
  // params.value.safetyNotice = data.html;
  fatherMessage2.value.data = data.html;
  rules.value = data.html;
  // accountRuleForm.contentText = data.text;
};

const fatherMessage3 = ref({
  data: "",
  flag: false,
});
// 富文本传过来的数据
const richtextClick3 = (data) => {
  // console.log(data, "富文本传过来的数据");
  // params.value.safetyNotice = data.html;
  fatherMessage3.value.data = data.html;
  donation.value = data.html;
  // accountRuleForm.contentText = data.text;
};

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;
    reminder.value = res.data.reminder;
    userName.value = res.data.userName;
    chitchatImage.value = res.data.chitchatImage ? res.data.chitchatImage : [];
    reminder.value = res.data.reminder;
    userName.value = res.data.userName;
    schoolValue.value=res.data.schoolValue;

    richtextShow.value = false;
    richtextShow2.value = false;
    richtextShow3.value = false;
    setTimeout(() => {
      richtextShow.value = true;
      richtextShow2.value = true;
      richtextShow3.value = true;
      fatherMessage.value.flag = false;
      fatherMessage2.value.flag = false;
      fatherMessage3.value.flag = false;
      fatherMessage.value.data = res.data.intro;
      fatherMessage2.value.data = res.data.rules;
      fatherMessage3.value.data = res.data.donation;
      intro.value = res.data.intro;
      rules.value = res.data.rules;
      donation.value = res.data.donation;
    }, 50);
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};

const addDZKW=()=>{
  schoolValue.value.push({
    schoolName:'',
    schoolUrl:''
  })
}
const deleteDZKW=(index)=>{
  schoolValue.value.splice(index, 1); 
}

// 上传前的校验
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 handleDelete = (index) => {
  fileList.value.splice(index, 1);
};
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 handleChitchatDelete = (index) => {
  chitchatImage.value.splice(index, 1);
};
// 文件选择变化时触发
const handleChitchatChange = async (file, newFileList) => {
  console.log(file);
  let formData = new FormData();
  formData.append("file", file.raw);
  let res = await uploadFile(formData);
  if (res.code == 200) {
    chitchatImage.value.push(res.data.fileUrl); // 赋值给响应式fileList，页面自动刷新
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.message,
      center: true,
    });
  }
};
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 edit = () => {
  disabled.value = false;
  // fatherMessage.value.flag = false;
  // fatherMessage2.value.flag = false;
  // fatherMessage3.value.flag = false;
  richtextShow.value = false;
  richtextShow2.value = false;
  richtextShow3.value = false;
  setTimeout(() => {
    richtextShow.value = true;
    richtextShow2.value = true;
    richtextShow3.value = true;
    fatherMessage.value.flag = true;
    fatherMessage2.value.flag = true;
    fatherMessage3.value.flag = true;
  }, 0);
};
const confirm = async () => {
  let res = await updateAlumniSystem({
    id: id.value,
    address: address.value,
    email: email.value,
    phone: phone.value,
    files: fileList.value,
    chitchatImage: chitchatImage.value,
    reminder: reminder.value,
    userName: userName.value,
    intro: intro.value,
    rules: rules.value,
    donation: donation.value,
    schoolValue:schoolValue.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;
  fatherMessage.value.flag = false;
  fatherMessage2.value.flag = false;
  fatherMessage3.value.flag = false;
  richtextShow.value = false;
  richtextShow2.value = false;
  richtextShow3.value = false;
  setTimeout(() => {
    fatherMessage.value.flag = true;
    fatherMessage2.value.flag = true;
    fatherMessage3.value.flag = true;
    fatherMessage.value.flag = true;
    fatherMessage2.value.flag = true;
    fatherMessage3.value.flag = true;
  }, 0);
  getList();
};

onBeforeMount(() => {
  getList();
  let list = JSON.parse(sessionStorage.getItem("roleList"));
  console.log(list);
  list.forEach((i) => {
    if (i.menuName == "系统设置") {
      i.childs.forEach((item) => {
        if (item.menuName == "系统设置") {
          menuList.value = item;
        }
      });
    }
  });
  console.log(menuList.value);
});
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;
    overflow-y: auto;
    overflow-x: hidden; // 隐藏X轴滚动条，避免横向滚动
    // 核心2：自定义滚动条样式（适配Chrome/Edge等webkit内核浏览器）
    &::-webkit-scrollbar {
      width: 8px; // 滚动条宽度（越大越明显）
      height: 8px;
    }
    // 滚动条轨道样式
    &::-webkit-scrollbar-track {
      background: #f5f5f5; // 轨道底色
      border-radius: 4px; // 圆角，和滚动条滑块呼应
    }
    // 滚动条滑块样式（拖动的部分）
    &::-webkit-scrollbar-thumb {
      background: #c9c7c7; // 滑块默认颜色
      border-radius: 4px; // 圆角更美观
      // 鼠标悬浮时滑块变色
      &:hover {
        background: #9e9e9e;
      }
    }
    h4 {
      margin: 20px 0;
      font-size: 18px;
    }
    p {
      margin: 0 0 15px 0;
    }
    .img-upload-wrap {
      width: 100%;
      padding: 0 10px 0;
    }
    .dzkw {
      padding: 0;
      li {
        list-style: none;
        margin-bottom: 15px;
      }
    }
    /* 上传按钮样式：自定义，可根据需求修改 */
    :deep(.el-upload) {
      width: 140px;
      height: 140px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
