<template>
  <!-- 表单 -->
  <div class="field">
    <t-space style="width: 100%">
      <t-tabs class="loginTabs" v-model="loginForm.loginType" size="large">
        <t-tab-panel class="mmdl" value="password" label="密码登录" :destroyOnHide="false"> </t-tab-panel>
        <t-tab-panel value="phone" label="验证码登录" :destroyOnHide="false"> </t-tab-panel>
      </t-tabs>
    </t-space>
    <div>
      <t-form
        ref="loginForm"
        :class="['item-container', `login-${loginForm.loginType}`]"
        :data="loginForm"
        label-width="0"
        @submit="onSubmit"
      >
        <!-- 账号密码登录 -->
        <div v-show="loginForm.loginType === 'password'">
          <t-form-item name="username">
            <t-input v-model="loginForm.username" size="large" placeholder="请输入登录账号">
              <template #prefix-icon>
                <user-icon />
              </template>
            </t-input>
          </t-form-item>
          <t-form-item name="password">
            <t-input
              v-model="loginForm.password"
              type="password"
              size="large"
              placeholder="请输入密码"
              @keyup.enter.native="onSubmit"
            >
              <template #prefix-icon>
                <lock-on-icon />
              </template>
            </t-input>
          </t-form-item>
          <t-form-item name="captchaVerification" user-select:none>
            <div class="drag" ref="dragDiv">
              <div class="drag_bg"></div>
              <div class="drag_text">{{ confirmWords }}</div>
              <div
                ref="moveDiv"
                @mousedown="mouseDown($event)"
                :class="{ handler_ok_bg: confirmSuccess }"
                class="handler handler_bg"
                style="position: absolute; top: 0; left: 0"
              ></div>
            </div>
          </t-form-item>
        </div>

        <!-- 短信验证码登录 -->
        <div v-show="loginForm.loginType === 'phone'">
          <t-form-item name="mobile">
            <t-input v-model="loginForm.mobile" size="large" placeholder="请输入您的手机号">
              <template #prefix-icon>
                <user-icon />
              </template>
            </t-input>
          </t-form-item>
          <t-form-item class="verification-code" name="mobileCode">
            <t-input v-model="loginForm.mobileCode" size="large" placeholder="请输入验证码" key="verifyCode" />
            <t-button variant="outline" :disabled="countDown > 0" @click="handleCounter">
              {{ countDown === 0 ? '发送验证码' : `${countDown}秒后可重发` }}
            </t-button>
          </t-form-item>
        </div>
        <t-form-item class="btn-container">
          <t-button block size="large" type="submit"> 登录</t-button>
        </t-form-item>
        <div class="check-container remember-pwd">
          <t-checkbox>记住账号</t-checkbox>
          <span v-show="loginForm.loginType === 'password'" class="tip">忘记密码？</span>
        </div>
      </t-form>
    </div>
  </div>
</template>

<script>
import { removePassword, removeRememberMe, removeUsername } from '@/utils/auth';
import { UserIcon, LockOnIcon } from 'tdesign-icons-vue';
import { MessagePlugin } from 'tdesign-vue';
import { getVerify } from '@/pages/index/api/login';

const FORM_RULES = {
  mobile: [{ required: true, message: '手机号必填', type: 'error' }],
  username: [{ required: true, message: '账号必填', type: 'error' }],
  password: [{ required: true, message: '密码必填', type: 'error' }],
  mobileCode: [{ required: true, message: '验证码必填', type: 'error' }],
};
export default {
  components: {
    UserIcon,
    LockOnIcon,
  },
  data() {
    return {
      beginClientX: 0 /* 距离屏幕左端距离 */,
      mouseMoveState: false /* 触发拖动状态  判断 */,
      maxWidth: '' /* 拖动最大宽度，依据滑块宽度算出来的 */,
      confirmWords: '请按住滑块，拖动到最右边' /* 滑块文字 */,
      confirmSuccess: false /* 验证成功判断 */,
      width: 350,
      height: 42,
      textSize: '18px',
      FORM_RULES,
      loginForm: {
        loginType: 'password',
        username: '',
        password: '',
        captchaVerification: '',
        mobile: '',
        mobileCode: '',
        rememberMe: false,
      },
      countDown: 0,
      intervalTimer: null,
    };
  },
  beforeDestroy() {
    clearInterval(this.intervalTimer);
  },
  methods: {
    async onSubmit() {
      if (this.loginForm.loginType === 'password') {
        if (!this.loginForm.username) {
          MessagePlugin.info({
            content: '请输入用户名',
            duration: 1000,
          });
          return;
        }
        if (!this.loginForm.password) {
          MessagePlugin.info({
            content: '请输入密码',
            duration: 1000,
          });
          return;
        }
        if (!this.confirmSuccess) {
          MessagePlugin.info({
            content: '请先完成滑块验证',
            duration: 1000,
          });
          return;
        }
      } else {
        if (!this.loginForm.mobile) {
          MessagePlugin.info({
            content: '请输入手机号',
            duration: 1000,
          });
          return;
        }
        if (!this.loginForm.mobileCode) {
          MessagePlugin.info({
            content: '请输入验证码',
            duration: 1000,
          });
          return;
        }
      }

      const { href } = window.location;
      this.loading = true;
      removeUsername();
      removePassword();
      removeRememberMe();
      // 发起登陆
      this.$store
        .dispatch('Login', this.loginForm)
        .then(() => {
          console.log('111111');
          // this.$router.replace('/demo/demo').catch(() => '');
          // 本地之外
          // window.location.href = href.replace('sso/login', 'htgl/mhsy');
          // 本地
          window.location.href = `/view/kxtfwzx/glxtSy`;
        })
        .catch((error) => {
          console.log('22222');
          return
          // if (error === 1004003) {
          //   this.reSetSlider();
          // }
        });
    },
    handleCounter() {
      this.countDown = 60;
      this.intervalTimer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown -= 1;
        } else {
          clearInterval(this.intervalTimer);
          this.countDown = 0;
        }
      }, 1000);
    },
    // mousedown 事件
    mouseDown(e) {
      if (!this.confirmSuccess) {
        e.preventDefault && e.preventDefault(); // 阻止文字选中等 浏览器默认事件
        this.mouseMoveState = true;
        this.beginClientX = e.clientX;
      }
    },
    // 验证成功函数
    successFunction() {
      getVerify().then((res) => {
        this.loginForm.captchaVerification = res.data;
        this.confirmSuccess = true;
        this.confirmWords = '验证通过';
      });
      if (window.addEventListener) {
        document.getElementsByTagName('html')[0].removeEventListener('mousemove', this.mouseMoveFn);
        document.getElementsByTagName('html')[0].removeEventListener('mouseup', this.moseUpFn);
      } else {
        document.getElementsByTagName('html')[0].removeEventListener('mouseup', () => {});
      }
      document.getElementsByClassName('drag_text')[0].style.color = '#fff';
      document.getElementsByClassName('handler')[0].style.left = `${this.maxWidth}px`;
      document.getElementsByClassName('drag_bg')[0].style.width = `${this.maxWidth}px`;
    },
    // mousemove事件
    mouseMoveFn(e) {
      if (this.mouseMoveState) {
        const width = e.clientX - this.beginClientX;
        if (width > 0 && width <= this.maxWidth) {
          document.getElementsByClassName('handler')[0].style.left = `${width}px`;
          document.getElementsByClassName('drag_bg')[0].style.width = `${width}px`;
        } else if (width > this.maxWidth) {
          this.successFunction();
        }
      }
    },
    // mouseup事件
    moseUpFn(e) {
      this.mouseMoveState = false;
      const width = e.clientX - this.beginClientX;
      if (width < this.maxWidth) {
        document.getElementsByClassName('handler')[0].style.left = `${0}px`;
        document.getElementsByClassName('drag_bg')[0].style.width = `${0}px`;
      }
    },
    reSet() {
      this.formData.sfzhm = '';
      this.formData.xm = '';
      this.reSetSlider();
    },
    reSetSlider() {
      this.confirmSuccess = false;
      this.mouseMoveState = false;
      this.cxBtnDisabled = true;
      this.confirmWords = '请按住滑块，拖动到最右边';
      document.getElementsByClassName('handler')[0].style.left = `${0}px`;
      document.getElementsByClassName('drag_bg')[0].style.width = `${0}px`;
      document.getElementsByClassName('drag_text')[0].style.color = 'black';
      document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
      document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
    },
  },
  mounted() {
    // 计算滑块滑动最大值
    this.maxWidth = this.$refs.dragDiv.clientWidth - this.$refs.moveDiv.clientWidth;
    // 添加监听事件
    document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn);
    document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn);
  },
};
</script>
<style lang="less" scoped>
@import url('../index.less');
::v-deep .t-tabs {
  .t-tabs__nav-wrap {
    margin: 0 auto;
  }
  .t-tabs__nav-item {
    padding: 0 40px;
  }
  .t-tabs__content {
    padding: 15px;
  }
}
.drag {
  position: relative;
  width: 350px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: #e8e8e8;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.handler {
  width: 40px;
  height: 38px;
  cursor: move;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.handler_bg {
  background: #fff
    url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA3hpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj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AQDGx279Jf50AAAAAABJRU5ErkJggg==')
    no-repeat center;
  border-bottom-left-radius: 0;
  border-top-left-radius: 0;
}
.drag_bg {
  width: 0;
  height: 38px;
  background-color: #7ac23c;
  border-radius: 4px 0 0 4px;
}
.drag_text {
  position: absolute;
  top: 0;
  width: 100%;
  text-align: center;
  user-select: none;
}
</style>
