<template>
  <el-dropdown trigger="click">
    <div class="flex-center h100% p13px">
      <img :src="userStore.userInfo.logo" class="rounded-full mr-10px w40px h40px" />
      <span class="title">{{ userStore.userInfo.shopName }}</span>
      <el-icon>
        <CaretBottom />
      </el-icon>
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="handleOpenUserProfile">店铺配置</el-dropdown-item>
        <el-dropdown-item divided @click="dialogVisible = true">修改密码</el-dropdown-item>
        <el-dropdown-item divided @click="logout">退出登录</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <el-dialog title="修改密码" modal-append-to-body append-to-body v-model="dialogVisible" @close="reset" width="400px">
    <el-form ref="refForm" :model="form" :rules="rules">
      <el-form-item label="旧密码" prop="oldPass">
        <el-input type="password" show-password v-model="form.oldPass" placeholder="请输入旧密码"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPass">
        <el-input type="password" show-password v-model="form.newPass" placeholder="请输入新密码"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="rnewPass">
        <el-input type="password" show-password v-model="form.rnewPass" placeholder="请再次输入新密码"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="formLoading" @click="submitHandle">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import sysUser from "@/api/account/sysUser";
defineOptions({
  name: "UserProfile",
});
import { ElNotification } from "element-plus";
import { useTagsViewStore, useUserStore } from "@/store";
import { useCartsStore } from '@/store/modules/carts'

const tagsViewStore = useTagsViewStore();
const userStore = useUserStore();

const cartStore = useCartsStore()

const route = useRoute();
const router = useRouter();

const dialogVisible = ref(false);
const formLoading = ref(false);

const form = reactive({
  oldPass: "",
  newPass: "",
  rnewPass: "",
});

function reset() {
  form.oldPass = "";
  form.newPass = "";
  form.rnewPass = "";
  refForm.value.resetFields();
}

const validateNewPass = (rule: any, value: string, callback: (error?: Error) => void) => {
  if (!form.newPass) {
    callback(new Error(" "));
  } else if (form.newPass === form.oldPass) {
    callback(new Error("请输入与旧密码不同的新密码"));
  } else {
    callback();
  }
};
const validateRnewPass = (rule: any, value: string, callback: (error?: Error) => void) => {
  if (!form.rnewPass) {
    callback(new Error(" "));
  } else if (form.rnewPass !== form.newPass) {
    callback(new Error("两次密码输入不一致"));
  } else {
    callback();
  }
};
const rules = {
  oldPass: [
    {
      required: true,
      message: " ",
      trigger: "blur",
    },
  ],
  newPass: [
    {
      required: true,
      validator: validateNewPass,
      trigger: "blur",
    },
  ],
  rnewPass: [
    {
      required: true,
      validator: validateRnewPass,
      trigger: "blur",
    },
  ],
};
const refForm = ref();
// 提交修改密码
function submitHandle() {
  refForm.value.validate(async (vaild: boolean) => {
    if (vaild) {
      try {
        formLoading.value = true;
        const res = await sysUser.pwd({
          originalPassword: form.oldPass,
          checkPassword: form.newPass,
          password: form.newPass,
        });
        ElNotification.success("修改成功，请重新登陆");
        userStore
          .logout()
          .then(() => {
            tagsViewStore.delAllViews();
          })
          .then(() => {
            router.push(`/login?redirect=${route.fullPath}`);
          });
      } catch (error) {
        formLoading.value = false;
        console.log(error);
      }
    }
  });
}
/**
 * 打开个人中心页面
 */
function handleOpenUserProfile() {
  router.push({ name: "shopConfig" });
}

/**
 * 注销登出
 */
function logout() {
  ElMessageBox.confirm("确定注销并退出系统吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    lockScroll: false,
  }).then(() => {
    userStore
      .logout()
      .then(() => {
        console.log(111111111);
        tagsViewStore.delAllViews();
      })
      .then(() => {
        console.log(222222222);
        localStorage.setItem('Instead_olold_order', '')
        localStorage.setItem('carts', '')
        cartStore.table_code = ''
        cartStore.oldOrder = ''

        console.log('cartStore.table_code', cartStore.table_code);

        router.push(`/login?redirect=${route.fullPath}`);
      });
  });
}
</script>

<style lang="scss" scoped></style>
<style scoped>
.title {
  font-size: 16px;
  color: #5a5e66;
}
</style>