<template>
  <div class="loginView w-screen h-screen overflow-hidden flex">
    <div class="w-96 bg-white m-auto border-t-8 border-[#075985] shadow-xl rounded-md pl-9 pr-9" v-if="!isCorpWX">
      <div class="m-auto pt-4">
        <img class="w-1/5 m-auto" :src="loginLogo" alt="">
      </div>
      <h2 class="text-xl text-center pt-4 font-bold">智能客户管家</h2>
      <el-form class="pt-4" ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <el-form-item prop="username">
          <el-input clearable :prefix-icon="UserFilled" size="large" class="mt-2" v-model.trim="ruleForm.username"
            autocomplete="off" placeholder="账号/手机号" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input clearable :prefix-icon="Lock" show-password size="large" class="mt-4"
            v-model.trim="ruleForm.password" autocomplete="off" placeholder="密码" />
        </el-form-item>
        <div class="pt-4">
          <el-button type="primary" size="large" class="w-full" :loading="loginLoading"
            @click="login(ruleFormRef)">登录</el-button>
        </div>
      </el-form>
      <el-divider content-position="center">或</el-divider>
      <div class="m-auto mb-5" @click="wxworkCli()">
        <img class="w-9 m-auto p-1 rounded-full border-blue-300 border-2 cursor-pointer" :src="qiyeweixin" alt="">
      </div>
      <div class="flex justify-between pb-5">
        <!-- <el-link type="primary" :underline="false">联系客服</el-link> -->
        <el-link type="primary" class="btn" style="float:left;" :underline="false">联系客服
          <div class="service">
            <p style="color: #333">联系客服</p>
            <img src="../assets/code.jpg">
            <p><span style="color: #333">电话：</span><span id="QQ">15895914665</span></p>
          </div>
        </el-link>
        <div class="flex justify-around">
          <el-link class="mr-4" type="primary" :underline="false" @click="useHelp()">使用说明</el-link>
          <el-link type="primary" :underline="false" @click="toRegister()">企业注册</el-link>
        </div>
      </div>
      <el-dialog v-model="helpDialog" width="30%" title="使用说明">
        <div class="p-2 text-xl">
          <a style="color:#075985;text-decoration:none" href="upload/客户管家使用说明书.docx" download="客户管家使用说明书.docx"
            target="_blank">客户管家使用说明书.docx</a>
        </div>
      </el-dialog>
    </div>

    <div v-else class="w-full flex justify-center py-[50px] text-[40px] colo-[#505458]">
      正在进入系统中...
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, inject, onMounted } from "vue";
import { useRouter } from "vue-router";
import loginLogo from "@/assets/login/login_logo.png";
import qiyeweixin from "@/assets/login/qiyeweixin.png";
import { UserFilled, Lock } from '@element-plus/icons-vue'
import { type FormInstance, type FormRules } from 'element-plus'
import { useStore } from '@/store/index'
import { post } from "@/utils/request";
import { LOGIN } from "./api";
const { setRouters, setValue } = useStore()
const router = useRouter();
const globalPopup = inject<GlobalPopup>('globalPopup')
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  // username: "18122222222",
  // password: "000000",
  username: "",
  password: "",
});
const loginLoading = ref(false);
const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ required: true, trigger: "blur", message: "请输入账号/手机号" }],
  password: [{ required: true, trigger: "blur", message: "请输入密码" }],
})
const helpDialog = ref(false);
const isCorpWX = ref(false)

const login = (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return
  }
  formEl.validate((valid: boolean) => {
    if (!valid) {
      return false as any;
    }
    loginLoading.value = true;
    post(LOGIN, { ...ruleForm.value }).then(res => {
      if (res.code == 'error') {
        globalPopup?.showError(res.msg)
        loginLoading.value = false;
        return
      }
      globalPopup?.showSuccess('登录成功')
      loginLogic(res.data)
      // sessionStorage.setItem('token', res.data.id)
      // setValue(res.data, 'userInfo')
      // // 将数据分析放到第一位
      // const index = res.data?.moduleList.findIndex((obj: any) => obj.path === '/analysis');
      // if (index !== -1) {
      //   const item = res.data?.moduleList.splice(index, 1)[0];
      //   res.data?.moduleList.unshift(item);
      // }
      // console.log(res.data?.moduleList)
      // setValue(res.data?.moduleList, 'routers')
      // setTimeout(() => {
      //   loginLoading.value = false;
      //   // router.push(res.data?.moduleList[0].path);
      //   router.push('/analysis');
      // }, 100)
    }).catch(_err => {
      loginLoading.value = false;
    })
    return
    // let newRouter = [
    //   {
    //     path: '/thread',
    //     name: 'thread'
    //   }
    // ]
    // setRouters(newRouter)
    // setTimeout(() => {
    //   loginLoading.value = false;
    //   router.push(newRouter[0].path);
    // }, 1000);
  })

};

const loginLogic = (data: any) => {
  if(data.moduleList.length <= 0) {
    alert('无权访问，请联系管理员为您分配权限')
    return
  }
  data.moduleList = data.moduleList.filter((item: any) => item.path != '/corpreport')
  sessionStorage.setItem('isExistBusiness', data.company.isExistBusiness || 0)
  sessionStorage.setItem('token', data.id)
  localStorage.setItem('SUPERSONIC_TOKEN', data.supersonicToken)
  setValue(data, 'userInfo')
  // 将数据分析放到第一位
  const index = data?.moduleList.findIndex((obj: any) => obj.path === '/analysis');
  if (index !== -1) {
    const item = data?.moduleList.splice(index, 1)[0];
    data?.moduleList.unshift(item);
  }
  setValue(data?.moduleList, 'routers')
  setTimeout(() => {
    loginLoading.value = false;
    // router.push(data?.moduleList[0].path);
    router.push('/analysis');
  }, 100)
}
const useHelp = () => {
  helpDialog.value = true;
}
const toRegister = () => {
  router.push("/register");
}

// 涉及第三方登录
const checkLogin = () => { // 检查登录
  const userAgent = navigator.userAgent.toLowerCase();
  const href = window.location.href;
  const isCorpWXs = userAgent.includes("wxwork");
  if (isCorpWXs) {
    isCorpWX.value = true;
  }

  //直接使用userId进入系统，可能是后端授权成功后跳转过来的，也能方便开发人员调试
  if (href.indexOf("userId") > 0) {
    isCorpWX.value = true;
    //后台经过验证后，重定向过来带上了userId
    var loginUserId = href.substring(href.indexOf("userId=") + "userId=".length);
    if (loginUserId.includes('#/')) {
      loginUserId = loginUserId.substring(0, loginUserId.indexOf('#/'));
    }
    if (loginUserId.includes('&')) {
      loginUserId = loginUserId.substring(0, loginUserId.indexOf('&'));
    }
    loginByUserId(loginUserId);
  } 
}

const loginByUserId = (userId: any) => {
  post(`/user/loginByUserId`, { userId }).then(res => {
    if (res.code == 'error') {
      globalPopup?.showError(res.msg)
      return
    }
    loginLogic(res.data)
  }).catch(err => {
    console.log(err)
  })
}
const tryAutoLogin = () => {
  var appId = "wwdd1137a65ce0fc87";//企业微信第三方的SUIT ID
  var url = "https://crm.ttkuaiban.com/api/corpWXAuth";//授权回调页面
  var weixinUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + encodeURI(url) + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
  window.location.href = weixinUrl;
}
const wxworkCli = () => {
    var appId = "ww19f9868980b9bb43";//服务商新版登录授权suitId
    var url = "https://crm.ttkuaiban.com/api/corpWXScanningAuth";//授权回调页面
    // var weixinUrl=`https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?appid=${appId}&redirect_uri=${url}&state=0&usertype=member`;
    var weixinUrl=`https://login.work.weixin.qq.com/wwlogin/sso/login?login_type=ServiceApp&appid=${appId}&redirect_uri=${url}&state=0`;
    window.location.href = weixinUrl;
}

onMounted(() => {
  checkLogin()
})
</script>

<style lang="scss" scoped>
.loginView {
  background: #f0f2f5 url("../assets/login/background.png") no-repeat;
}

.service {
  display: none;
  width: 120px;
  position: absolute;
  background: #fff;
  text-align: center;
  padding: 10px;
  left: -30px;
  top: -210px;
  border-radius: 5px;
  box-shadow: 3px 3px 10px #dfdfdf;

  img {
    width: 80px;
  }
}

.btn:hover .service {
  display: block;
}
</style>