<template>
  <div class="userPage">
    <div style="height: 3vh;margin: 0 auto;width: 97%;">
      <el-page-header @back="goback()">
        <template #content>
          <span class="text-large font-600 mr-3"> 个人信息 </span>
        </template>
        <template #title >
          返回首页
        </template>
      </el-page-header>
    </div>

    <div class="userBox">
      <div class="userInfo">
        <div class="userT" @click="drawer = true">
          <el-avatar :size="150" :src="userInfo.avatar" />
        </div>
        <div class="userName">{{ userInfo.nickname }}</div>
        <!-- <div class="userName" @click="router.push('/')">返回首页</div> -->
      </div>
      <div class="collectionTopic">
        <div class="title">收藏</div>
        <div class="collectionList">
          <div
            class="collectionTme"
            v-for="emit in cpllectList"
            :key="emit.id"
            :Topic="emit"
            @click="goQuestion(emit)"
          >
            <p>
              [{{ emit.type == "select" ? "选择题" : "填空题" }}]{{
                emit.introduce
              }}
            </p>
            <el-tag v-for="itme in emit.tags" :key="itme.name" type="primary">{{
              itme.name
            }}</el-tag
            >&nbsp;
            <br />
            <br />
            <span>
              {{ emit.topicTitle }}
            </span>
          </div>
          <!-- <div class="collectionTme"></div> -->
        </div>
      </div>
    </div>
  </div>

  <el-drawer
    v-model="drawer"
    title="个人信息"
    direction="ltr"
    :before-close="handleClose"
  >
    <div class="info">
      <div class="infoItme">
        <image-upload
          ref="imgUpload"
          :image="userForm.avatar"
          style="width: 200px; height: 200px; display: inline-block"
          @upload="upload"
          :disabled="!isUpdata"
        ></image-upload>
      </div>
      <div class="infoItme">
        <div class="text">用户名</div>
        <el-input
          v-model="userForm.nickname"
          style="width: 240px"
          placeholder="Please input"
          :disabled="!isUpdata"
        />
      </div>
      <div class="infoItme">
        <div class="text">手机号</div>
        <el-input
          v-model="userForm.phone"
          style="width: 240px"
          placeholder="未登记手机号"
          :disabled="!isUpdata"
        />
      </div>
    </div>
    <template #footer>
      <el-button v-if="!isUpdata" type="success" @click="isUpdata = true"
        >更改信息</el-button
      >
      <el-button v-else type="success" @click="updateClick">保存</el-button>
      <el-button type="danger" @click="utLogin">退出登录</el-button>
      <el-button type="danger" @click="dialogFormVisible = true"
        >更改密码</el-button
      >
    </template>
  </el-drawer>
  <el-dialog v-model="dialogFormVisible" title="修改密码" width="500">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="旧密码" prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          utocomplete="off"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="ruleForm.newPassword"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="确定密码" prop="newPassword2">
        <el-input
          v-model="ruleForm.newPassword2"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >确定</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>


<script setup>
import router from "@/router";
import ImageUpload from "@/components/ImageUpload.vue";
import { ElMessage, ElStep } from "element-plus";
import { ElMessageBox } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import { login } from "@/api/user/user";
import { updateUserInfo } from "@/api/user/user";
import { computed, onMounted, reactive, ref } from "vue";
import { useTopicStore } from "@/stores/topic.js";
import { useUserStore } from "@/stores/user.js";
import TokenService from "@/utils/token";
const cpllectList = computed(() => topStore.collectTopics);
function goQuestion(item){
    useTopicStore().setQuestions(cpllectList.value,item)
    router.push({
      path: "/",
      query: {
        type: 'view'
      }
    });
}
function goback(){
  router.go(-1);
}
const upload = (url) => {
  console.log(url);
  userForm.value.avatar = url;
};
const utLogin = () => {
  TokenService.removeToken();
  router.push("/login");
};
const dialogFormVisible = ref(false);
const useSotr = useUserStore();
const userInfo = computed(() => useSotr.user);
const topStore = useTopicStore();
const ruleFormRef = ref(null);
const drawer = ref(false);
const isUpdata = ref(false);
let userForm = ref({
  username: null,
  phone: null,
  remark: null,
  avatar: null,
});
const updateClick = async () => {
  if (
   ! userForm.value 
  ) {
    ElMessage({ message: "请完善信息", type: "error" });
    return;
  }
  let res = await updateUserInfo(userForm.value);
  if (res.code == 200) {
    ElMessage({ message: "更新成功", type: "success" });
    isUpdata.value = false;
    await useSotr.UserInfo();
    userForm.value = userInfo.value
  }
  console.log(res);
};
const handleClose = (done) => {
  if (isUpdata.value) {
    ElMessageBox.confirm("更改未保存，确定退出吗？", {
      confirmButtonText: "确定退出",
      cancelButtonText: "继续修改",
    })
      .then(() => {
        userForm.value = userInfo.value
        isUpdata.value = false;
        done();
      })
      .catch(() => {
        // catch error
      });
  }
  else {
    done();
  }
};

const ruleForm = reactive({
  password: "",
  newPassword: "",
  newPassword2: "",
});
const usernamevalidate = async (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输旧密码"));
  }
  else {
    let res = await login({ username: useSotr.username, password: value });
    if (res.code == 200) {
      callback();
    }
    else {
      callback(new Error("密码错误"));
    }
  }
};

const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输新入密码"));
  }
  else {
    if (ruleForm.password !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("》》");
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输确认新密码"));
  }
  else if (value !== ruleForm.newPassword) {
    callback(new Error("密码不一致"));
  }
  else {
    callback();
  }
};
const submitForm = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      let res = await updateUserInfo({
        password: ruleForm.newPassword,
      });
      if (res.code == 200) {
        ElMessage({ message: "更新成功,请重新登录账号", type: "success" });
        dialogFormVisible.value = false;
        ruleForm.password = "";
        ruleForm.newPassword = "";
        ruleForm.newPassword2 = "";
        TokenService.removeToken();
        router.push("/login");
        // await useSotr.UserInfo();
      }
    }
  });
};
const rules = reactive({
  password: [{ validator: usernamevalidate, trigger: "blur" }],
  newPassword: [{ validator: validatePass, trigger: "blur" }],
  newPassword2: [{ validator: validatePass2, trigger: "blur" }],
});
onMounted(async () => {
  await useSotr.UserInfo();
  userForm.value = userInfo.value;
  setTimeout(() => {
    console.log(userInfo.value)

  }, 400);

});
</script>
<style lang="scss" scoped>
.userPage {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.userBox {
  border-radius: 20px 20px 0 0;
  width: 100vw;
  flex: 1;
  // height: 100vh;
  background-image: url("@/assets/image/mimi.jpg");
  background-size: cover; // 背景图片铺满元素
  background-position: center; // 背景图片居中显示
  background-repeat: no-repeat; // 背景图片不重复
  display: flex;
  justify-content: center;
  align-items: center;

  .userInfo {
    height: 90%;
    width: 20%;
    // background-color: #fff;
    display: flex;
    flex-direction: column;
    // justify-content: space-between;
    align-items: center;

    .userName {
      margin-top: 30px;
      font-size: 30px;
    }

    .userT {
      margin-top: 90px;
    }
  }

  .collectionTopic {
    margin-left: 30px;
    width: 60%;
    height: 90%;
    // background-color: #ff0;
    display: flex;
    flex-direction: column;
    // justify-content: space-between;
    align-items: center;

    .title {
      margin-top: 10px;
      font-size: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 90%;
      height: 5%;
      background-color: #ededec;
      background-image: url("@/assets/image/btbg.png");
      background-position: center;
      background-repeat: repeat;
      border-radius: 70px;
    }

    .collectionList {
      overflow-y: auto;
      scrollbar-width: none;
      /* Firefox */
      -ms-overflow-style: none;

  

      flex: 1;
      width: 90%;
      box-sizing: border-box;
      display: flex;
      // justify-content: space-between;
      flex-wrap: wrap;
      padding: 10px;

      .collectionTme {
        /* 宽度是固定好的 */
        width: 30%;
        height: 47%;
        // background-color: #d2fce3;
        box-sizing: border-box;
        padding-top: 1%;
        padding-left: 5%;
        font-family: "黑体";
        font-size: 17px;
        line-height: 17px;
        background-image: url("@/assets/image/zhibg.png");
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
        margin-bottom: 10px;
        margin-right: 17px;
      }
    }

    .collectionList:after {
      content: "";
      flex: auto;
    }
  }
}

.infoItme {
  display: flex;
  justify-content: center;
  width: 80%;
  margin: 20px auto;

  .text {
    width: 30%;
    text-align: right;
    margin-right: 30px;
  }
}

.info {
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
}
</style>