<template>
  <div class="flex flex-col h-screen overflow-hidden">
    <div class="py-[5px] px-[10px]">
      <n-tree-select
        filterable
        label-field="Title"
        key-field="Url"
        children-field="Son"
        placeholder="菜单搜索"
        @update:value="updateValue"
        :options="menuList"
        :filter="handleFilter"
        clearable
      />
    </div>
    <n-scrollbar class="flex-1" ref="scrollbarRef">
      <n-menu
      class="pb-[90px]"
        ref="nMenuRef"
        :value="defaultPath"
        :collapsed="store.state.isCollapse"
        :options="menuList"
        :default-value="defaultPath"
        children-field="Son"
        v-model:expanded-keys="expandKeys"
        :collapsed-icon-size="22"
        :collapsed-width="63"
        :indent="15"
        key-field="Url"
        :render-icon="renderIconFunction"
        :render-label="renderLabelFunction"
        label-field="Title"
        @update:value="onMenuClick"
      />
    </n-scrollbar>
  </div>
  <n-modal v-model:show="state.showPWD" :autoFocus="false" :closeOnEsc="false" :mask-closable="false" :bordered="false">
    <n-card class="w-[600px]" :bordered="false" size="huge" role="dialog" aria-modal="true">
      <template #header>
        <div style="text-align: center">修改密码</div>
      </template>
      <template #header-extra></template>
      <div class="update-pwd">
        <div>
          <div class="item">
            <span>电话号码</span>
            <div style="color: #c3bcd8">{{ state.info.TelNum }}</div>
          </div>
          <div class="item">
            <span>验证本人</span>
            <div class="ver-code">
              <n-input v-model:value="state.code" placeholder="在此输入验证码" style="width: 180px" />
              <n-button class="code-btn" @click="getCode" v-if="canSend">获取验证码</n-button>
              <n-button v-else class="code-btn">{{ leftTime }}s</n-button>
            </div>
          </div>
          <div style="height: 40px"></div>
          <div class="item" :style="{ marginBottom: isWarn ? '10px' : '20px' }">
            <span>修改密码</span>
            <div class="ver-code">
              <n-input v-model:value="state.pass" type="password" show-password-on="click" style="width: 290px"
                       placeholder="长度在6~18之间 由字母、数字、特殊字符组成" @blur="onBlur()" @change="onBlur()" />
              <img src="@/assets/image/ok.png" style="
                  width: 24px;
                  height: 24px;
                  margin-left: 10px;
                  margin-top: 4px;
                " v-if="isTrue" />
              <n-popover trigger="hover">
                <template #header>
                  <n-text strong depth="1"> 密码规则说明</n-text>
                </template>
                <span>密码长度在6-18个字符之间，由数字、字母、特殊字符组成，请勿输入中文特殊字符</span>
                <template #trigger>
                  <img src="@/assets/image/warn.png" style="
                      width: 24px;
                      height: 24px;
                      margin-left: 10px;
                      margin-top: 4px;
                      cursor: pointer;
                    " v-if="isWarn" />
                  <div v-else></div>
                </template>
              </n-popover>
            </div>
          </div>
        </div>
        <div v-show="isWarn" class="passwordTips">
          密码长度在6-18个字符之间，由数字、字母、特殊字符组成，请勿输入中文特殊字符
        </div>
        <div class="item">
          <span>确认密码</span>
          <div>
            <n-input type="password" show-password-on="click" v-model:value="state.comPass" style="width: 290px"
                     @blur="onConfirmPWBlur()" @change="onConfirmPWBlur()" />
          </div>
          <div v-show="isConfirmPWWarn" class="passwordTips">
            两次密码输入不一致
          </div>
        </div>
      </div>
      <template #footer>
        <div style="display: flex; align-items: center; justify-content: center">
          <n-button type="primary" style="width: 150px; margin-right: 20px" :disabled="isSave || isConfirmPWWarn"
                    @click="doneSet">
            保存
          </n-button>
          <n-button style="width: 150px; margin-right: 20px" @click="logout">
            退出登录
          </n-button>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup>
import { NBadge, useDialog } from "naive-ui";
import { storeToRefs } from "pinia";
import { authStore } from "@/store/modules/authorize.js";
import { h, defineProps, ref, watch, onMounted, getCurrentInstance } from "vue";
import { Local, Session } from "@/utils/storage.js";
import { useRoute, useRouter } from "vue-router";
import { useLayoutStore } from "@/components/skeleton/index.js";
import commonStore from "@/store/index";
import { useStore } from "vuex";
import { useEmployeeArchivesStore } from "@/store/modules/employeeArchives";
import { employeeFileFindOutStanding } from "@/api-norm/employeeArchives/index";
import { useStoreManage } from "@/store/modules/store-manage";
import { tabRouter } from "@/store/modules/tab-router.js";
const tabState= tabRouter()
const {pushTabs}= tabState
const {tabs,currentTab}= storeToRefs(tabState)
const dialog = useDialog();
const nMenuRef = ref(null);
const state = reactive({
  showPWD: false,
  info: {},
  code: "",
  pass: "",
  comPass: "",
  tableData: [],
  loading: false
});
const isSave = ref(true);
const canSend = ref(true);
const leftTime = ref(60);
const isTrue = ref(false);
const isWarn = ref(false);
const isConfirmPWWarn = ref(false);
const scrollbarRef = ref(null);
const vueXStore = useStore();
const employeeArchivesStore = useEmployeeArchivesStore();
const storeManage = useStoreManage();
const currentInstance = getCurrentInstance();
const { $request } = currentInstance.appContext.config.globalProperties;
const currentRoute = useRoute();
const authorizeData = authStore();
const { menuList } = storeToRefs(authorizeData);

if (currentRoute.fullPath !== "/login") {
  authorizeData.getMenuList();
}
const props = defineProps(["routes"]);
const store = useLayoutStore();
const defaultPath = ref("");
const expandKeys = ref([]);
const router = useRouter();
defaultPath.value = currentRoute.fullPath;
const handleFilter = (pattern, item) => {
  if (!pattern) return true
  return item.searchTitle.includes(pattern?.toLocaleLowerCase())
}
const updateValue = async (path, item) => {
  if (item.Pid && item.Pid !== 0) {
    expandKeys.value = [String(item.Pid)];
  }else {
    expandKeys.value = [String(item.ID)];
  }
  try {
    if (item.CanJump===1){

      await router.push(path);
      currentTab.value=path
      pushTabs(item)
    }
    requestAnimationFrame(() => {
      scrollbarRef.value?.scrollTo({
        top: item.scrollTop,
        behavior: "smooth"
      });
    });
  } catch (err) {
    console.error('Navigation failed:', err);
  }
};
const findParentIdByUrl = (nodes, targetUrl) => {
  for (const node of nodes) {
    const { Url, Pid, Son } = node;
    if (Url === targetUrl) return Pid;
    if (Son) {
      const result = findParentIdByUrl(Son, targetUrl);
      if (result !== null) return result;
    }
  }
  return null;
};
const renderIconFunction = (option) => {
  const isActive = defaultPath.value === option.Url;
  const parentID = findParentIdByUrl(menuList.value, defaultPath.value);
  const isParentActive = option.ID === parentID;
  return h("img", {
    class: ["custom-icon", isActive && "select-icon"],
    src: (isActive || isParentActive) ? option.grayIcon : option.Icon
  });
};

// 标签渲染
const renderLabelFunction = (option) => {
  const badgeConfig = {
    "审批申请": { value: vueXStore.state.DoingTotal },
    "考勤申请": { value: vueXStore.state.OADoingTotal },
    "考勤管理": { value: vueXStore.state.OADoingTotal },
    "人才招聘": { value: 0 }, // 根据实际需求设置
    "我的人才招聘": { value: 0 }, // 根据实际需求设置
    "员工档案": { value: employeeArchivesStore.bellNum },
    "画展包付款单审核": { value: vueXStore.state.exPayApproveNum },
  };
  if (option.Title in badgeConfig) {
    return h(NBadge, {
      ...badgeConfig[option.Title],
      offset: [20, 8],
      max: 99
    }, {
      default: () => option.Title
    });
  }
  return h("div", option.Title);
};

// 获取红点
const recruitRedDot = () => {
  state.loading = true;
  $request.HTTP.permission
    .recruitRedDot({})
    .then((res) => {
      if (res.status === 0) {
        state.loading = false;
        state.tableData = res.data;
      } else {
        message.error(res.msg);
      }
    })
    .catch(() => {
      state.loading = false;
    });
};
function onMenuClick(key, item) {
  router.push(key.startsWith("/") ? key : `/${key}`);
  currentTab.value=key
  pushTabs(item)
  if (store.state.device === "mobile") {
    store.toggleCollapse(true);
  }
}

const getALLApprovalNum = async () => {
  let data = {
    UserID: Local.get("userInfo") ? Local.get("userInfo").ID : "",
    Type: "",
    menuType: 2
  };
  const res = await $request.HTTP.approval.getInformation(data);
  if (res.status === 0) {
    // 将DoingTotal存入vuex
    vueXStore.commit("GET_DOING_TOTAL", res.data.SubmitMeInfo.DoingTotal);
  }
  return res;
};
// 获取OA带我审批数
const getOAALLApprovalNum = () => {
  let data = {
    UserID: Local.get("userInfo") ? Local.get("userInfo").ID : "",
    Type: "",
    menuType: 1
  };
  $request.HTTP.approval
    .getInformation(data)
    .then((res) => {
      if (res.status === 0) {
        // 将DoingTotal存入vuex
        vueXStore.commit("GET_OADOING_TOTAL", res.data.SubmitMeInfo.DoingTotal);
      } else {
        processError(res.msg);
      }
    })
    .catch((e) => {
    });
};

// 获取画展包付款单审核待我审核数量
const getexPayApproveNum = async () => {
  const { status, data, msg } = await $request.HTTP.approval.getApprovalList({
		page: 1,
		pageSize: 1,
		status: 1,
		type: 'bundlePayPrice',
		menuType: 2,
		domain: 'all'
	})
	if (status === 0) {
		vueXStore.commit("GET_EX_PAY_APPROVE_NUM", data.Count);
	} else processError(msg)
}

const getBellNum = async () => {
  const res = await employeeFileFindOutStanding({});
  if (res.status === 0) {
    employeeArchivesStore.changeBellNum(res.data.total);
  }
};

const verCode = async () => {
  if (state.code.length !== 6) {
    return null;
  }
  let data = {
    TelNum: state.info.TelNum,
    Code: state.code
  };
  let res = null;
  res = await $request.HTTP.login.verCode(data).catch((e) => {
    message.error(e.response.data.msg || "操作失败，请稍后再试");
    res = null;
  });
  return res;
};

const doneSet = async () => {
  if (state.pass == "" || state.comPass == "") {
    message.warning("请输入密码！");
    return;
  }
  if (JSON.stringify(state.pass) !== JSON.stringify(state.comPass)) {
    message.warning("两次密码输入不一致！");
    isConfirmPWWarn.value = true;
    return;
  }
  let data = {
    ID: state.info.ID,
    Password: state.pass,
    NickName: state.info.NickName
  };
  const verCodeRes = await verCode();
  if (verCodeRes?.status == 0) {
    // message.success("验证码校验成功");
  } else {
    message.error(verCodeRes?.msg || "验证码校验失败");
    return false;
  }
  $request.HTTP.permission
    .userUpdate(data)
    .then((res) => {
      if (res.status == 0) {
        message.success("修改密码成功,请重新登录！自动跳转登录页面", {
          duration: 2000
        });
        Session.clear();
        Local.clear();
        router.push("/login");
      } else {
        message.error(res.msg);
      }
    })
    .catch((e) => {
      message.error(e.response.data.msg || "操作失败，请稍后再试");
    });
};

const ishasToChangePWD = () => {
  const userInfo = Local.get("userInfo");
  state.info = userInfo;
  if (userInfo.IsNeedChange === 1) {
    state.showPWD = true;
  }
};

const getCode = () => {
  $request.HTTP.login
    .getCode({ TelNum: state.info.TelNum })
    .then((res) => {
      if (res.status == 0) {
        // 倒计时逻辑
        canSend.value = false;
        let timer = setInterval(() => {
          leftTime.value--;
          if (leftTime.value <= 0) {
            canSend.value = true;
            clearInterval(timer);
            leftTime.value = 60;
          }
        }, 1000);
        message.success("验证码已发送");
      } else {
        message.error(res.msg);
      }
    })
    .catch((e) => {
      message.error(e.response.data.msg || "操作失败，请稍后再试");
    });
};

const onBlur = () => {
  isTrue.value = false;
  isWarn.value = false;
  if (state.pass == "" || state.pass.length < 5) {
    isWarn.value = true;
    isSave.value = true;
    return;
  }
  let reg =
    /^(?=.*[A-Za-z])(?=.*\d)(?=.*[`~!@#$%^&*()_+<>?:"{},.\/\\;'[\]])[A-Za-z\d`~!@#$%^&*()_+<>?:"{},.\/\\;'[\]]{6,18}$/;
  if (reg.test(state.pass)) {
    isTrue.value = true;
    isSave.value = false;
  } else {
    isWarn.value = true;
    isSave.value = true;
  }
};

const onConfirmPWBlur = () => {
  if (JSON.stringify(state.pass) !== JSON.stringify(state.comPass)) {
    isConfirmPWWarn.value = true;
  } else {
    isConfirmPWWarn.value = false;
  }
};

const logout = () => {
  dialog.warning({
    title: "提示",
    content: "是否要退出当前账号？",
    positiveText: "退出",
    negativeText: "再想想",
    onPositiveClick: () => {
      router.replace("/login");
      Local.clear();

    }
  });
};

watch(
  () => currentRoute.fullPath,
  (newVal) => {
    defaultPath.value = newVal;
    storeManage.menu = currentRoute.meta.title;
  },
  {
    immediate: true
  }
);
// watchEffect(() => {
//   console.log(1111111111111, currentRoute)
// })
onMounted(() => {
  // getALLApprovalNum();
  // getOAALLApprovalNum();
  ishasToChangePWD();
  // recruitRedDot();
  // getBellNum();
  // getexPayApproveNum();
});
</script>

<style lang="scss" scoped>
:deep(.n-menu .n-submenu .n-menu-item-content__icon) {
  font-size: 16px !important;
}

:deep(.n-menu .n-menu-item-content .n-menu-item-content__icon) {
  font-size: 16px !important;
}
:deep(.n-menu .n-menu-item::before) {
  left: 0;
  right: 0;
  border-radius: 0;
}

:deep(.n-menu .n-menu-item:hover) {
  background-color: var(--item-color-active);
}

@import "@/assets/styles/variables.scss";

.scrollbar {
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.update-pwd {
  width: 500px;
  // height: 750px;
  padding: 0 30px;
  margin: 40px 40px 40px 0;

  .title {
    color: #6d5c9c;
    padding: 30px 0;
    text-align: center;
    border-bottom: 1px solid #c1b2e5;
    font-size: 16px;
  }

  .item {
    display: flex;
    align-items: center;
    margin: 10px 0;

    .ver-code {
      display: flex;

      .code-btn {
        border-radius: 18px;
        font-size: 12px;
        color: #764cf6;
        background: #f1edfa;
        width: 100px;
        height: 34px;
        margin-left: 10px;
      }
    }

    span {
      flex-shrink: 0;
      width: 80px;
    }
  }

  .btn-box {
    margin-top: 50px;
    display: flex;
    justify-content: center;

    button {
      width: 100px;
    }
  }
}

.passwordTips {
  line-height: 1.25;
  color: red;
  margin-left: 70px;
}
</style>
