import { ref,onMounted,nextTick } from 'vue'
import { departInterence } from '@/api/api'
import { useAppStore } from '@/store/modules/app'
import { ElMessage } from 'element-plus'
import { router } from '@/router'

export function useLogin() {

  const isMobile = ref(window.innerWidth<=650)
  onMounted(() => {
    window.addEventListener('resize',function() {
      isMobile.value = window.innerWidth<=650
    })
  })

  //获取图形验证码
  const picSrc = ref('')
  const picId = ref('')
  async function getCodePic(){
    //存base64和id
      const res =await departInterence.getCodePic()
      if(res.Ret!==200) return 
      if(res.Data){
          picSrc.value = res.Data.Base64Blob,
          picId.value = res.Data.Id
      }
  }

  //手机验证码倒计时
  let timer = null
  const codeStr = ref('获取验证码')
  const codeCountDown = ref(60)
  function countDown(){
    codeCountDown.value--
    codeStr.value=`重新获取（${codeCountDown.value}）秒`
    if(codeCountDown.value<=0){
        clearInterval(timer)
        codeStr.value = '重新获取'
    }
  }
  async function getVerifyCodeHandle(parmas) {
    const res = await departInterence.getCodeVerify(parmas)

    if(res.Ret!==200) return 
    ElMessage.success('验证码已发送')

    //60秒倒计时
    codeCountDown.value = 60
    countDown()
    timer = setInterval(()=>{
        countDown()
    },1000)
  }

  return {
    isMobile,
    picSrc,
    picId,
    getCodePic,
    timer,
    codeStr,
    codeCountDown,
    countDown,
    getVerifyCodeHandle
  }
}

export function useForm() {
  const modelForm = ref(null);

  async function validate() {
    await modelForm.value?.validate();
  }

  async function restValidate() {
    modelForm.value?.resetFields();
  }

  return {
    modelForm,
    validate,
    restValidate
  };
}

export function useLoginSuccess(res) {
  setUserInfo(res.Data);

  getOtherRolePath('myCalendar').then(path => {
    nextTick(() => {
      // path&&router.push({ path });
      //先跳到主面板
      path&&router.push({ path:'/dashboard' });
    })
  });
  
}

export function useQuitSystem() {

  localStorage.setItem('auth','');
  localStorage.setItem('userName','');
  localStorage.setItem('Role','');
  localStorage.setItem('RoleType','');
  localStorage.setItem('AdminId','');
  localStorage.setItem('AdminName','');
  localStorage.setItem('ManageType','');
  localStorage.setItem('RoleIdentity','')
  router.replace("/login");
}

//登录成功存储信息
const setUserInfo = (Data) => {
  localStorage.setItem("auth", Data.Authorization);
  localStorage.setItem("userName", Data.RealName);
  localStorage.setItem("Role", Data.RoleTypeCode);
  localStorage.setItem("RoleIdentity", Data.SysRoleTypeCode);
  localStorage.setItem("RoleType", Data.ProductName);
  localStorage.setItem("ManageType", Data.Authority);
  localStorage.setItem("AdminId", Data.AdminId);
  localStorage.setItem("AdminName", Data.AdminName);
}

function getOtherRolePath(pathVal){
  const { SET_DATA_AUTH } = useAppStore();

  return departInterence.getMenu().then(res => {
    let resolvePath=''
    if(res.Ret === 200) {
      let menuList = res.Data.List||[];

      if(!menuList.length){
        return ElMessage.error('该账号没有任何菜单权限,请联系管理员')
      }

      // 是否已经拿到菜单信息
      sessionStorage.setItem('hasGetMenu','true')
      sessionStorage.setItem('MenuList',JSON.stringify(menuList));

      /* 是否有数据报表权限 */
      SET_DATA_AUTH(menuList.some(item => item.name === '报表统计'))

      for (let i = 0; i < menuList.length; i++) {
        const arr=menuList[i].children||[]
        if(arr.some(it => it.path == pathVal)){
          resolvePath='/'+pathVal
          break
        }
      }
      return resolvePath || '/'+menuList[0].children[0].path
    }

    return '/'+pathVal
  })
}