<template>
  <div class="login-container" v-loading="loginLoading" :element-loading-text="$t('login:tip:waitLogin')"
    element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
    <div class="login-header">
      <!-- <img src="@/assets/login-logo.png" class="login-logo"> -->
    </div>
    <div class="login-body">
      <div class="login-l">
        <div class="login-logo">
          <!-- <img v-if="language === 'zh' && hospital.HospitalLogoPath"  -->
          <img v-if="language === 'zh'" :src="OSSclientConfig.basePath + hospital.HospitalLogoPath"
            crossOrigin="anonymous" alt="" :style="`max-height:60px;max-width:${config.logoScale.login * 60}px`" />
          <img v-else-if="NODE_ENV === 'usa'" :src="OSSclientConfig.basePath + hospital.HospitalLogoPath" alt=""
            class="usa-logo" :style="`max-height:60px;max-width:${config.logoScale.login * 60}px`" />
          <!-- <img v-else src="@/assets/zzlogo3.png" alt="" /> -->
        </div>
        <div class="login-image">
          <img src="@/assets/login-bg.png" />
        </div>
      </div>
      <div class="login-r">
        <div class="title-container">
          <!-- IRC Management System -->
          <div class="title">
            {{ $t('login:title:system') }}
          </div>
        </div>
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
          label-position="left">
          <el-form-item prop="username" :rules="[
            {
              required: true,
              message: this.$t('login:formRule:userName'),
              trigger: 'blur',
            },
          ]">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <!-- User Name -->
            <el-input ref="username" v-model="loginForm.username" size="small" :placeholder="$t('login:form:userName')"
              name="username" type="text" tabindex="1" />
          </el-form-item>

          <el-form-item prop="password" :rules="[
            {
              required: true,
              message: this.$t('login:formRule:password'),
              trigger: 'blur',
            },
          ]">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <!-- password -->
            <el-input :key="passwordType" ref="password" v-model="loginForm.password" size="small" :type="passwordType"
              :placeholder="$t('login:form:password')" name="password" tabindex="2" @keyup.enter.native="handleLogin" />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <!-- Login -->
          <el-button :loading="loading" type="primary" style="width: 100%; margin-bottom: 10px" size="medium"
            @click.native.prevent="handleLogin">
            {{ $t('login:button:login') }}
          </el-button>
          <div style="text-align: right">
            <!-- Forget password? -->
            <el-button type="text" size="medium" @click.native.prevent="handleResetPwd">
              {{ $t('login:button:forgetPassword') }}
            </el-button>
            <TopLang v-if="isDev" />
          </div>
        </el-form>
      </div>
    </div>
    <div class="login-footer">
      <!-- <span>Copyright © 2024 上海展影医疗科技有限公司 版权所有</span>
      <span> | </span>
      <a target="_blank" href="https://beian.miit.gov.cn/">
        <span> 沪ICP备2021037850-2 </span>
      </a>
      <span> | </span>
      <a
        target="_blank"
        href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=31011002005859"
      >
        <img src="@/assets/filing.png" />
        <span>沪公网安备 31011002005859号</span>
      </a> -->
      <span><span @click.stop="openHospital">{{ $t('login:copyright:title:construct') }}</span>{{ hospital.HospitalName
      }}</span>
      <span> | </span>
      <span>{{ $t('login:copyright:title:support') }}{{ language === 'zh' ? config.company : config.companyEN }}</span>
      <el-popover placement="top" trigger="click">
        <div class="file_a_box">
          <a :href="`${OSSclientConfig.basePath}/SupportDownload/ConfigurationDocumentation.pdf`"
            download="ConfigurationDocumentation" target="_blank">{{
              $t("login:file:ConfigurationDocumentation")
            }}</a>
          <a :href="`${OSSclientConfig.basePath}/SupportDownload/Certificate.zip`" download="Certificate">{{
            $t("login:file:Certificate")
          }}</a>
          <a :href="`${OSSclientConfig.basePath}/SupportDownload/GoogleChromePortable.zip`"
            download="GoogleChromePortable">{{ $t("login:file:GoogleChrome")
            }}</a>
        </div>
        <span slot="reference" style="color:#409EFF;cursor: pointer;">{{ $t("login:file:click") }}</span>
      </el-popover>
    </div>
    <Vcode :show="isShow" slider-text="拖到滑块完成验证" :imgs="[Img1]" @success="onSuccess" />
    <el-dialog :title="$t('login:hospital:title:changeHospital')" :visible.sync="visible" width="30%"
      :append-to-body="true">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item :label="$t('login:hospital:form:changeHospital')">
          <el-select v-model="form.Id" placeholder="" style="width:100%">
            <el-option v-for="item in hospitalList" :key="item.Id" :label="item.HospitalName" :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{ $t("common:button:cancel") }}</el-button>
        <el-button type="primary" @click="saveHospital">{{ $t("system:hospital:save") }}</el-button>
      </span>
    </el-dialog>
    <toggleRole v-if="toggleRoleVisible" :visible.sync="toggleRoleVisible" :loading="toggleRoleLoading"
      @save="loginByRole" @cancel="cancel" />
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
import TopLang from './topLang'
// import NoticeMarquee from '../trials/trials-layout/components/noticeMarquee'
import Vcode from 'vue-puzzle-vcode'
import Img1 from '@/assets/pic-1.png'
import logoImg from '@/assets/zzlogo2.png'
import { getHospital } from '@/api/hospital.js'
import { getHIRHospitalList, updateDefaultHospital } from '@/api/admin'
import toggleRole from '@/components/toggleRole'
import { resetRouter } from '@/router'

export default {
  name: 'Login',
  components: { TopLang, Vcode, toggleRole },
  data() {
    return {
      NODE_ENV: process.env.NODE_ENV, // process.env.NODE_ENV
      config: WINDOW_CONFIG,
      visible: false,
      logoImg,
      VUE_APP_OSS_CONFIG_REGION: process.env.VUE_APP_OSS_CONFIG_REGION,
      loginForm: {
        username: '',
        password: '',
      },
      loginRules: {
        username: [
          {
            required: true,
            message: this.$t('login:formRule:userName'),
            trigger: 'blur',
          },
          { max: 20, message: `${this.$t('common:ruleMessage:maxLength')} 20` },
        ],
        password: [
          // {
          //   required: true,
          //   trigger: "blur",
          //   validator: this.$validatePassword
          // },
          {
            required: true,
            message: this.$t('login:formRule:password'),
            trigger: 'blur',
          },
          { max: 20, message: `${this.$t('common:ruleMessage:maxLength')} 20` },
        ],
      },
      loading: false,
      passwordType: 'password',
      loginType: null,
      location: null,
      isShow: false,
      Img1,
      hospital: {
        HospitalLogoPath: null,
        HospitalName: null,
        Id: null
      },
      hospitalList: [],
      form: {
        Id: null
      },

      toggleRoleVisible: false,
      toggleRoleLoading: false,

      loginLoading: false
    }
  },
  computed: {
    ...mapGetters(['asyncRoutes', 'routes', 'language']),
    isDev() {
      return process.env.VUE_APP_OSS_PATH === "/hir_test/dist"
    }
  },
  created() {
    this.getInfo()
    this.getList()
  },
  mounted() {
    this.loginType = this.$route.query.loginType
    this.location = this.$route.query.location
    zzSessionStorage.setItem('loginType', this.loginType)
    localStorage.setItem('location', this.location)
    if (process.env.NODE_ENV === "usa") {
      this.$i18n.locale = "en";
      this.setLanguage("en");
      this.$updateDictionary();
    } else {
      //   if (this.location === "USA") {
      //     this.$i18n.locale = "en";
      //     this.setLanguage("en");
      //     this.$updateDictionary();
      //   } else {
      this.$i18n.locale = 'zh'
      this.setLanguage('zh')
      this.$updateDictionary()
    }
    // }
    if (this.$route.query.token) {
      this.loginLoading = true
      this.TJUserLoginInfo(this.$route.query.token)
    }
  },
  methods: {
    ...mapMutations({ setLanguage: 'lang/setLanguage' }),
    cancel() {
      this.showCode = true
      this.loading = false
      this.toggleRoleLoading = false
      // this.toggleRoleVisible = false
    },
    // 置换token
    async TJUserLoginInfo(Token) {
      this.$store
        .dispatch('user/loginByToken', { Token }).then(res => {
          if (res.length === 1) {
            return this.loginByRole({
              UserId: res[0].Id, UserTypeId: res[0].UserTypeId
            })
          }
          this.loginLoading = false
          this.toggleRoleVisible = true
        }).catch(err => {
          this.loginLoading = false
          console.log(err)
        })
    },
    async saveHospital() {
      if (this.form.Id === this.hospital.Id) return this.visible = false
      let res = await updateDefaultHospital({
        HirHospitalId: this.form.Id
      })
      if (res.IsSuccess) {
        this.visible = false
        this.getInfo()
        this.getList()
      }
    },
    openHospital() {
      if (this.hospitalList.length <= 1) return false
      this.form.Id = this.hospital.Id
      this.visible = true
    },
    // 获取医院列表
    getList() {
      getHIRHospitalList({
        HospitalName: null,
        Country: null,
        City: null,
        Province: null,
        Address: null,
        Phone: null,
        Asc: false,
        SortField: 'CreateTime',
        PageIndex: 1,
        PageSize: 1000,
      })
        .then((res) => {
          this.hospitalList = res.Result.CurrentPageData
        })
        .catch(() => {
        })
    },
    // 获取医院信息
    async getInfo() {
      try {
        let res = await getHospital()
        if (res.IsSuccess) {
          Object.keys(this.hospital).forEach((key) => {
            this.hospital[key] = res.Result[key]
          })
        }
      } catch (err) {
        console.log(err)
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.loginType = this.$route.query.loginType
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // this.isShow = true
          this.loginIn()
        } else {
          return false
        }
      })
    },
    loginIn() {
      this.loading = true
      this.$store
        .dispatch('user/login', this.loginForm)
        .then((res) => {
          if (res.BasicInfo.LoginState === 2) {
            this.$message.warning(this.$t('login:message:login4'))
          }
          if (res.BasicInfo.IsFirstAdd) {
            // 当前用户为首次登录,请先修改密码之后再次登录
            this.$message.success(this.$t('login:message:login1'))
            setTimeout(() => {
              this.$router.push({
                path: `/recompose?userName=${this.loginForm.username}`,
              })
            }, 500)
            return
          } else if (res.BasicInfo.NeedChangePassWord) {
            // 请先修改密码后再登录！
            this.$alert(
              this.$t('login:message:login3'),
              this.$t('common:title:warning'),
              {
                callback: (action) => {
                  this.$router.push({
                    path: `/recompose?userName=${this.loginForm.username}`,
                  })
                  return
                },
              }
            )
            return
          }
          zzSessionStorage.removeItem('userId')
          zzSessionStorage.removeItem('identityUserId')
          this.changeRoleLogin()
        })
        .catch(() => {
          this.loading = false
        })
    },
    changeRoleLogin() {
      if (
        Array.isArray(this.$store.state.user.roles) &&
        this.$store.state.user.roles.length === 1
      ) {
        this.loginByRole(this.$store.state.user.roles[0].Id)
        return
      }
      if (
        Array.isArray(this.$store.state.user.roles) &&
        this.$store.state.user.roles.filter((item) => item.IsUserRoleDisabled)
          .length ===
        this.$store.state.user.roles.length - 1
      ) {
        let role = this.$store.state.user.roles.find(
          (item) => !item.IsUserRoleDisabled
        )
        this.loginByRole(role.Id)
        return
      }
      return (this.toggleRoleVisible = true)
    },
    loginByRole(userRoleId) {
      this.toggleRoleLoading = true
      this.$store
        .dispatch('user/loginByRole', { userRoleId })
        .then((res) => {
          this.toggleRoleLoading = false
          if (res) {
            this.$store
              .dispatch('permission/generateRoutes')
              .then((res) => {
                this.loading = false
                if (res && res.length > 0) {
                  this.$store.dispatch('global/getNoticeList')
                  this.$router.addRoutes(res)
                  // if (this.LoginState === 2) {
                  //   this.$message.warning(this.$t('login:message:login4'))
                  // }
                  if (this.loginType === 'DevOps') {
                    this.$router.replace({ path: res[0].path })
                    return
                  }
                  if (this.hasPermi(['role:radmin'])) {
                    this.$router.replace({ path: res[0].path })
                    return
                  }
                  if (
                    this.hasPermi(['role:pm', 'role:sa', 'role:admin', 'role:dev', 'role:ga'])
                  ) {
                    history.replaceState(null, null, '/trials/trials-inspection')
                    history.go(0)
                  } else {
                    history.replaceState(null, null, '/trials/trials-list')
                    history.go(0)
                  }
                } else {
                  this.toggleRoleLoading = false
                  // 此账户暂未配置菜单权限，请联系管理员处理后再登录。
                  this.$message.warning(this.$t('login:message:login2'))
                }
              })
              .catch((err) => {
                this.toggleRoleLoading = false
              })
          } else {
            this.toggleRoleLoading = false
          }
        })
        .catch((err) => {
          this.showCode = true
          this.loading = false
          this.toggleRoleLoading = false
        })
    },
    onSuccess() {
      this.isShow = false
      this.loginIn()
    },
    handleResetPwd() {
      this.$router.push({ name: 'Resetpassword' })
    },
  },
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */

$bg: #283443;
$light_gray: #909399;
$cursor: #fff;

// @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
//   .login-container .el-input input {
//     // color: #fff;
//   }
// }

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: #f4f4f5;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      // color: $light_gray;
      height: 47px;
      // caret-color: $cursor;

      // &:-webkit-autofill {
      //   box-shadow: 0 0 0px 1000px $bg inset !important;
      //   -webkit-text-fill-color: $cursor !important;
      // }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: #f4f4f5;
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #606266;

.file_a_box {

  a {
    margin-bottom: 5px;
    display: block;

    &:last-child {
      margin: 0;
    }
  }
}

.login-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: auto;
  background: rgb(249, 249, 249);

  .login-header {
    margin: 10px 0px 20px 10px;
    height: 3rem;
    width: 720px;

    .login-logo {
      height: 100%;
    }
  }

  .login-body {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    // margin-top: -230px;
    // margin-left: -400px;
    width: 1200px;
    height: 600px;
    // margin: 30px auto;
    box-sizing: border-box;
    background: rgb(255, 255, 255);
    border-radius: 10px 0px 0px 10px;

    .login-l {
      position: relative;
      float: left;
      width: 50%;
      height: 100%;

      .login-logo {
        position: absolute;
        top: 35px;
        left: 50px;

        // img {
        //   max-height: 60px;
        //   max-width: 250px;
        // }

        // .usa-logo {
        //   height: 60px;
        // }
      }

      .login-image {
        position: absolute;
        top: 10px;
        left: 0px;
        // transform: translateY(-50%);
        height: 100%;

        img {
          height: 100%;
        }
      }
    }

    .login-r {
      position: relative;
      float: left;
      width: 50%;
      height: 100%;

      .login-form {
        position: absolute;
        top: 55%;
        // transform: translateY(-50%);
        left: 50%;
        transform: translate(-50%, -50%);
        width: 80%;
        padding: 10px;
        margin: 0 auto;
        overflow: hidden;
      }

      .title-container {
        // margin-bottom: 50px;
        text-align: center;
        margin-top: 20%;

        .title {
          font-size: 35px;
          color: $light_gray;
          text-align: center;
          font-weight: bold;
        }
      }

      .tips {
        font-size: 14px;
        color: #fff;
        margin-bottom: 10px;

        span {
          &:first-of-type {
            margin-right: 16px;
          }
        }
      }

      .svg-container {
        padding: 6px 5px 6px 15px;
        color: $dark_gray;
        vertical-align: middle;
        width: 30px;
        display: inline-block;
      }

      .show-pwd {
        position: absolute;
        right: 10px;
        top: 7px;
        font-size: 16px;
        color: $dark_gray;
        cursor: pointer;
        user-select: none;
      }
    }
  }

  .login-footer {
    position: absolute;
    bottom: 50px;
    left: 0px;
    width: 100%;
    text-align: center;
    line-height: 20px;
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
    // color: rgb(180, 190, 199);
    color: #909399;

    a {
      display: inline-block;
      text-decoration: none;
      height: 20px;
      line-height: 20px;
      display: flex;
      justify-content: center;
    }

    span {
      margin: 0 2px;
    }

    img {
      height: 20px;
      line-height: 20px;
    }

    // p{
    //   display: inline-block;
    //   height:20px;
    //   line-height:20px;
    //   margin: 0px 0px 0px 5px;
    //   color:#939393;
    // }
  }
}
</style>
