<template>
  <div class="topbar">
    <div class="topbar_title">
      <img src="~@/assets/img/logo.png" />
    </div>
    <div class="topbar_user">
      <el-dropdown @command="handleCommand" trigger="hover">
        <div class="avatar-wrapper">
          <div class="user_avatar">
            <el-icon><UserFilled /></el-icon>
          </div>
          <span>{{ userInfo.name }}</span>
          <el-icon><ArrowDown /></el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="logout">
              <span>退出登录</span>
            </el-dropdown-item>
            <el-dropdown-item divided command="updatepw">
              <span>修改密码</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
  <el-dialog v-model="dialogFormVisible" title="修改密码" width="500">
    <el-form :model="form" :rules="rules" ref="passwordForm" label-width="100">
      <el-row>
        <el-col :span="12">
          <el-form-item label="仓库简称：">{{ userInfo.name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名：">{{ userInfo.username }}</el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="原始密码：" prop="currentPassword">
        <el-input
          v-model="form.currentPassword"
          type="password"
          placeholder="请输入原始密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="新密码：" prop="newPassword">
        <el-input
          v-model="form.newPassword"
          type="password"
          placeholder="请输入原始密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码：" prop="confirmNewPassword">
        <el-input
          v-model="form.confirmNewPassword"
          type="password"
          placeholder="请输入原始密码"
          show-password
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm(passwordForm)">关闭</el-button>
        <el-button type="primary" @click="submitForm(passwordForm)">提交</el-button>
      </div>
    </template>
  </el-dialog>
  <topTag />
</template>

<script setup lang="ts">
import topTag from "./topTag.vue";

import { ref } from "vue";
import { useStore } from "vuex";
import { ElMessageBox, FormInstance } from "element-plus";
import { UserFilled, ArrowDown } from "@element-plus/icons-vue";
import { changePassword } from "@/api/login";

const store = useStore();
const userInfo: any = ref("");
const dialogFormVisible = ref(false)
const passwordForm = ref<FormInstance>()

const form = ref({
  currentPassword: '',
  newPassword: '',
  confirmNewPassword: ''
});

const rules = {
  currentPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '新密码长度应在6到20个字符之间', trigger: 'blur' }
  ],
  confirmNewPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
};

function validateConfirmPassword(rule, value, callback) {
  if (value !== form.value.newPassword) {
    callback(new Error('两次输入的新密码不一致'));
  } else {
    callback();
  }
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 提交密码变更请求到后端接口（这里假设有一个changePassword方法处理API调用）
      let postData = {
        password: form.value.currentPassword,
        newpassword1: form.value.newPassword,
        userId: userInfo.value.userId,
        username: userInfo.value.username,
      }
      changePassword(postData).then((res: any) => {
        dialogFormVisible.value = false
        formEl.resetFields()
        store.dispatch("LogOut").then(() => {
          // 刷新登录页面，避免多次弹框
          window.location.reload();
        });
      }).catch((error) => {
        console.error("@@@@",error);
      });
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogFormVisible.value = false
}

store.dispatch("GetUserInfo").then((res: any) => {
  userInfo.value = res;
});

const handleCommand = (command: string) => {
  if(command == 'logout'){
    ElMessageBox.confirm("即将退出登录，是否确定？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      store.dispatch("LogOut").then(() => {
        // 刷新登录页面，避免多次弹框
        window.location.reload();
      });
    });
  }else{
    dialogFormVisible.value = true
  }
};
</script>

<style lang="scss" scoped>
.topbar {
  position: relative;
  height: 90px;
  width: 100%;
  display: flex;
  align-items: center;
  background-image: url(~@/assets/img/top-bj.png);
  background-size: 100% 100%;
  box-sizing: border-box;
  &_title {
    flex: 1;
    img {
      height: 40px;
    }
  }
  &_search {
    .el-input {
      width: 280px;
      margin-right: 30px;
    }
  }
  &_user {
    min-width: 180px;
    .avatar-wrapper {
      color: #000;
      font-weight: bolder;
      font-size: 16px;
      display: flex;
      align-items: center;
      .user_avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        text-align: center;
        line-height: 40px;
        margin-right: 5px;
        .el-icon {
          margin: 0;
          color: #020066;
          font-size: 30px;
        }
      }
      .el-icon {
        margin-left: 10px;
      }
    }
  }
}
</style>
