<template>
  <div class="login-form-wrapper2">
    <Form
      class="p-4 enter-x"
      :model="formData"
      :rules="getFormRules"
      ref="formRef"
      v-show="getShow"
    >
      <div class="formItem"></div>
      <FormItem name="account" class="enter-x">
        <a-input
          class="fix-auto-fill"
          size="large"
          :placeholder="t('sys.login.userName')"
          :type="'text'"
          v-model:value="formData.account"
        >
          <template #suffix>
            <a-tooltip>
              <span></span>
            </a-tooltip>
          </template>
        </a-input>
      </FormItem>
      <FormItem name="password" class="enter-x">
        <a-input
          class="fix-auto-fill"
          size="large"
          :placeholder="t('sys.login.password')"
          :type="showInfo ? 'password' : 'text'"
          v-model:value="formData.password"
        >
          <template #suffix>
            <a-tooltip @click="changeShow" :title="showInfo ? '点击展示密码' : '点击隐藏密码'">
              <span :style="showInfo ? notshowPassWord : showPassWord"></span>
            </a-tooltip>
          </template>
        </a-input>
      </FormItem>
      <div class="sliderBar">
        <SliderBar ref="sliderBar" :promptTextStyleSuccess="{ color: '#ffffff' }" :multiple="1" />
      </div>
      <FormItem class="enter-x">
        <Button
          id="login-btn-my"
          class="login-but ant-btn1"
          type="primary"
          size="large"
          block
          @click="handleLogin"
          :loading="loading"
        >
          {{ t('sys.login.loginButton') }}
        </Button>
      </FormItem>
    </Form>

    <a-modal
      title="初始密码更改"
      v-model:visible="initPwdVisible"
      :confirm-loading="initConfirmLoading"
      @ok="handleSubmitPwd"
    >
      <div class="boxInitPwd">
        <BasicForm @register="register" />
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref, computed, provide, onMounted } from 'vue';
  import { Form, Button } from 'ant-design-vue';
  import SliderBar from './SliderBar.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { useUserStore } from '/@/store/modules/user';
  import { LoginStateEnum, useLoginState, useFormRules, useFormValid } from './useLogin';
  import { getPlatForm } from '/@/api/oem';
  import { createLocalStorage, createSessionStorage } from '/@/utils/cache';
  import notShowPasswordImg from '/@/assets/images/notShowPassword.png';
  import showPasswordImg from '/@/assets/images/showPassword.png';
  import { getAppEnvConfig } from '/@/utils/env';

  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './pwd.data';
  import { resetPasswordLogin } from '/@/api/system/system';
  import { useAppStore } from '/@/store/modules/app';
  import { usePermissionStore } from '/@/store/modules/permission';
  const permissionStore = usePermissionStore();
  const appStore = useAppStore();
  import { session } from '/@/utils/Memory.js';
  const { VITE_GLOB_BIG_SCREEN } = getAppEnvConfig();
  import { useRouter } from 'vue-router';
  const router = useRouter();
  // import { func } from 'vue-types';
  // const ACol = Col;
  // const ARow = Row;
  const FormItem = Form.Item;
  // const InputPassword = Input.Password;
  const { t } = useI18n();
  const { notification, createMessage } = useMessage();
  // const { prefixCls } = useDesign('login');
  const userStore = useUserStore();
  // const activeKey = ref('1');

  const { getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();
  const storage = createLocalStorage();
  const sStorage = createSessionStorage();
  const formRef = ref();
  const loading = ref(false);
  const rememberMe = ref(false);
  const userInfo = storage.get('userInfo') || sStorage.get('userInfo');

  const formData = reactive({
    account: userInfo?.account ?? '',
    password: userInfo?.password ?? '',
  });

  const { validForm } = useFormValid(formRef);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);
  let verifySuccess = ref(false);
  provide('verifySuccess', verifySuccess);
  let showInfo = ref(true);
  const notshowPassWord = `background:url(${notShowPasswordImg});position: relative;width: 16px;height: 16px;`;
  const showPassWord = `background:url(${showPasswordImg});;position: relative;width: 16px;height: 16px;`;
  function changeShow() {
    showInfo.value = !showInfo.value;
  }
  onMounted(() => {
    document.onkeydown = (e) => {
      if (e.keyCode === 13) {
        let dom = document.getElementById('login-btn-my');
        if (dom) handleLogin();
      }
    };
  });
  async function handleLogin() {
    sessionStorage.removeItem('currentSystemName');
    sessionStorage.removeItem('allMenuList');
    const data = await validForm();
    if (!data) return;
    if (unref(rememberMe)) {
      storage.set('userInfo', formData);
      sStorage.set('userInfo', formData);
    } else {
      storage.set('userInfo', null);
      sStorage.set('userInfo', null);
    }
    if (!verifySuccess.value) {
      createMessage.error('请先通过滑动验证！');
      return;
    }
    loading.value = true;
    const userInfo = await userStore
      .login({
        password: data.password,
        username: data.account,
        mode: 'modal', //不要默认的错误提示
      })
      .catch((data) => {
        //登录失败如果是502，返回的html,那么提示框什么都没有
        if (data.message == 'Invalid username or password' && typeof data.message == 'string') {
          createMessage.error(data.message);
        } else if (data.message == '账号已过期,请联系管理员') {
          createMessage.error(data.message);
        } else if (data.message == '用户账号未激活或初始密码未修改') {
          handModelPwd();
        } else {
          createMessage.error(data.message);
        }
      });
    if (userInfo) {
      notification.success({
        message: t('sys.login.loginSuccessTitle'),
        description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.realName}`,
        duration: 3,
      });
      const res = await getPlatForm();
      storage.set('platformInfo', res);
      userStore.setPlatInfo(res);
      // 设置icon
      let link = (document.querySelector("link[rel*='icon']") ||
        document.createElement('link')) as HTMLLinkElement;
      link.type = 'image/x-icon';
      link.rel = 'shortcut icon';
      link.href = res.icon ?? '/favicon.ico';
      document.getElementsByTagName('head')[0].appendChild(link);

      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement('script');
        hm.src = 'https://hm.baidu.com/hm.js?909f8e22a361b08e4f5ea3918500aede';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(hm, s);
      })();
      // 直接跳转到首页
      parentSystem();
    }
    loading.value = false;
  }

  // 跳转逻辑
  function removeNodesWithType2(obj) {
    for (let i = 0; i < obj.length; i++) {
      const node = obj[i];
      if (node.children) {
        const newChildren = removeNodesWithType2(node.children);
        if (newChildren !== node.children) {
          node.children = newChildren;
        }
      }
      if (node.mat && node.meta.type === 2) {
        delete node.meta;
      }
    }
    return obj;
  }
  function parentSystem() {
    subSystem({ name: '地质灾害数据支撑子系统' }, true);
    var tk = sessionStorage.getItem('token') || 'dsge1fds2fsf3f4sdfsjsdui1245we6io6sj729bsd';
    window.location.href = `${VITE_GLOB_BIG_SCREEN}refreshToken=${tk.replace(/['"]/g, '')}`;
  }
  const subSystem = (alarmItem: object, type) => {
    var user = session.getItem('user');
    if (user.roles.indexOf('SYS_ADMIN') > -1 || user.roles.indexOf('PLATFORM_ADMIN') > -1) {
      const allMenuList = session.getItem('allMenuList');
      allMenuList.map((i) => {
        if (i.name == alarmItem.name) {
          appStore.setCurrentSystemName(alarmItem.name);
          const result = removeNodesWithType2(i.children);
          console.log('result', result);
          permissionStore.setBackMenuList(i.children);
        }
      });
    } else {
      const allMenuList = session.getItem('allMenuList');
      appStore.setCurrentSystemName('地质灾害数据支撑子系统');
      removeNodesWithType2(allMenuList);
      permissionStore.setBackMenuList(allMenuList);
      router.push({ path: '/dashbord' });
    }
  };
  /*------------------------- 密码初始化 ---------------------*/

  const initPwdVisible = ref<boolean>(false);
  const initConfirmLoading = ref<boolean>(false);
  // const modalText = ref<string>('密码初始化');

  const [register, { validate, resetFields }] = useForm({
    size: 'large',
    labelWidth: 100,
    showActionButtonGroup: false,
    schemas: formSchema,
  });

  async function handModelPwd() {
    initPwdVisible.value = true;
  }

  async function handleSubmitPwd() {
    const data = await validForm();
    if (!data) return;
    if (unref(rememberMe)) {
      storage.set('userInfo', formData);
      sStorage.set('userInfo', formData);
    } else {
      storage.set('userInfo', null);
      sStorage.set('userInfo', null);
    }
    try {
      const values = await validate();
      const { passwordNew } = values;
      const params = {
        userName: data.account,
        password: data.password,
        resetPassword: passwordNew,
      };

      await resetPasswordLogin(params).then((result) => {
        if (result.data) {
          createMessage.success('修改成功');
          setTimeout(() => {
            initPwdVisible.value = false;
            initConfirmLoading.value = false;
            resetFields();
            localStorage.clear();
            userStore.resetState();
          }, 2000);
        }
      });
    } catch (error) {}
  }

  // const handleOk = () => {
  //   modalText.value = 'The modal will be closed after two seconds';
  //   initConfirmLoading.value = true;
  //   setTimeout(() => {
  //     initPwdVisible.value = false;
  //     initConfirmLoading.value = false;
  //   }, 2000);
  // };
</script>
<style lang="less" scoped>
  .login-form-wrapper2 .p-4 {
    padding: 0;
  }

  .sliderBar {
    width: 307px;
    height: 42px;
    margin-bottom: 62px;
  }

  .formItem {
    width: 100%;
    height: 30px;
  }

  .system-name {
    font-size: 30px;
    font-family: Alimama ShuHeiTi;
    font-weight: bold;
    color: #fdfeff;
    padding-left: 40px;
    margin-bottom: 20px;
  }

  .login-form-wrapper {
    width: 470px;
    height: 492px;
    padding: 48px 58px 0 90px;
    background: ~"url('/@/assets/images/login/login-form-wrapper.png')" no-repeat 100%;

    .login-but {
      height: 40px;
      background: linear-gradient(-90deg, #0bf, #01d8eb);
      box-shadow: 0 12px 8px 0 rgba(3, 30, 55, 0.1);
      border-radius: 2px;
      &:hover,
      &:focus {
        background: linear-gradient(-90deg, #0bf, #01d8eb) !important;
        box-shadow: 0 12px 8px 0 rgba(3, 30, 55, 0.1) !important;
        border-radius: 2px !important;
      }
    }

    .ant-tabs-line {
      :deep(.ant-tabs-bar) {
        border-bottom: 0 solid #f0f0f0;
      }
    }

    .ant-tabs-nav {
      :deep(.ant-tabs-nav) {
        color: #ffe076 !important;
      }
    }

    :deep(.ant-form-item-control) {
      width: 320px;
      margin-top: 0.2604rem;
      background: transparent;
      border: none;
      line-height: 0.2083rem;
      color: #fff;
      box-shadow: inset 0 0 6px 2px #16c0ff;
      border-radius: 2px;
    }
  }

  .login-form-wrapper2 .fix-auto-fill.ant-input-affix-wrapper {
    box-shadow: inset 0 0 6px 2px #16c0ff;
    background-color: transparent;
    border: none;
  }

  :deep(#account),
  :deep(#password) {
    font-size: 14px;

    &::-webkit-input-placeholder {
      color: rgba(255, 255, 255, 0.4);
    }

    &::-moz-placeholder {
      color: rgba(255, 255, 255, 0.4);
    }

    &:-ms-input-placeholder {
      color: rgba(255, 255, 255, 0.4);
    }
  }

  :deep(.ant-form-item-explain.ant-form-item-explain-error) {
    color: rgba(0, 255, 255, 0.7);
  }

  .boxInitPwd {
    // border: 1px red solid;
    padding: 30px 30px 10px 0;
    // .ant-form-item-explain.ant-form-item-explain-error {
    :deep(.ant-form-item-explain.ant-form-item-explain-error) {
      color: red;
    }
  }
</style>
