<template>
  <div>
    <el-form
      ref="loginForm"
      :rules="loginRules"
      :model="loginForm"
      class="login-form"
      status-icon
      label-width="0"
    >
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          size="small"
          maxlength="11"
          auto-complete="off"
          placeholder="请输入用户名"
          @keyup.enter.native="handleLogin"
        >
          <i slot="prefix" class="icon-yonghu" />
        </el-input>
      </el-form-item>

      <el-form-item prop="drugEntId">
        <!--

              @blur="getDrugEntList"

        <el-select v-model="loginForm.drugEntId"-->
        <!--               v-show="isShowEnt"-->
        <!--               class="login-select animated fadeIn"-->
        <!--               style="width:  300px !important;text-align:left !important"-->
        <!--               placeholder="点击请选择药企"-->
        <!--               >-->
        <!--      <el-option v-for="dept in deptList"-->
        <!--                 :key="dept.id"-->
        <!--                 :label="dept.entname"-->
        <!--                 :value="dept.id"></el-option>-->
        <!--    </el-select>-->
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          :type="passwordType"
          v-model="loginForm.password"
          size="small"
          auto-complete="off"
          placeholder="请输入密码"
          @keyup.enter.native="handleLogin"
        >
          <i
            slot="suffix"
            class="el-icon-view el-input__icon"
            @click="showPassword"
          />
          <i slot="prefix" class="iconfont icon-mima"></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <Verify
          @success="verifySuccess"
          :mode="'pop'"
          :captchaType="'blockPuzzle'"
          :imgSize="{ width: '330px', height: '155px' }"
          ref="verify"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="small"
          class="login-submit"
          @click.native.prevent="handleLogin"
          >登录
        </el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      append-to-body
      title="短信认证"
      top="30vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :visible.sync="codeVisible"
      width="30vw"
      center
    >
      <el-form :model="codeForm" @submit.native.prevent>
        <el-form-item>
          <div class="font-gry">
            验证码已发送到您的手机：{{ phoneHide(this.codeForm.phone) }}，
            请查收！
          </div>
        </el-form-item>
        <el-input
          v-model="codeForm.code"
          auto-complete="off"
          oninput="value=value.replace(/[^\d.]/g,'')"
          placeholder="请输入验证码"
          @keyup.enter.native="codeSubmit"
        >
          <template slot="append">
            <el-button
              :loading="codeLoading"
              @click="snedCodeFn"
              :disabled="title != '发送验证码'"
              >{{ title }}</el-button
            >
          </template>
        </el-input>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="codeFnLoading"
          :disabled="codeFnDisable"
          @click="codeSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { randomLenNum } from "@/util/util";
import { mapGetters } from "vuex";
import { getCode } from "@/api/code";
import Verify from "@/components/verifition/Verify";
import { getDeptList, sendCodeApi, verifyCodeApi } from "@/api/admin/dept";
import { debounce } from "@/util/util";

export default {
  name: "Userlogin",
  components: {
    Verify
  },
  data() {
    return {
      drugEntId: "",
      title: "发送验证码",
      codeLoading: false,
      codeFnDisable: true,
      codeFnLoading: false,
      loginInfo: {},
      codeForm: {
        code: "",
        phone: ""
      },
      codeVisible: false,
      isShowEnt: false,
      deptList: [],
      socialForm: {
        code: "",
        state: ""
      },
      loginForm: {
        username: "",
        password: "",
        code: "",
        randomStr: "blockPuzzle",
        drugEntId: ""
      },
      checked: false,
      code: {
        src: undefined,
        len: 4
      },
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" }
          // { min: 6, message: "密码长度最少为6位", trigger: "blur" }
        ]
      },
      passwordType: "password"
    };
  },
  computed: {
    ...mapGetters(["tagWel"])
  },
  methods: {
    phoneHide(phone) {
      let reg = /^(1[3-9][0-9])\d{4}(\d{4}$)/; // 定义手机号正则表达式
      phone = phone.replace(reg, "$1****$2");
      return phone; // 185****6696
    },
    showPassword() {
      this.passwordType == ""
        ? (this.passwordType = "password")
        : (this.passwordType = "");
    },
    getDrugEntList() {
      if (
        null != this.loginForm.username &&
        undefined != this.loginForm.username &&
        "" != this.loginForm.username
      ) {
        var obj = {
          username: this.loginForm.username
        };
        getDeptList(obj).then(response => {
          if (undefined == response.data.data || null == response.data.data) {
            this.$router.push({ path: this.tagWel.value });
            return;
          }

          const result = response.data.data;
          if (result.length > 0) {
            for (var i = 0; i < result.length; i++) {
              this.deptList.push({
                id: result[i].id,
                entname: result[i].entname
              });

              if (result.length > 1) {
                this.$router.push({ path: "/checkEnt" });
                return;
              } else {
                this.$router.push({ path: this.tagWel.value });
                return;
              }
            }
          }
        });
      }
    },

    handleLogin() {
      // if(this.isShowEnt)
      // {
      //   if(undefined==this.loginForm.drugEntId||this.loginForm.drugEntId.length==0)
      //   {
      //     this.$notify.error('请选择企业')
      //     return false;
      //   }
      // }

      this.$refs.verify.show();
    },

    snedCodeFn: debounce(async function() {
      this.codeLoading = true;
      sendCodeApi(this.codeForm.phone, this.loginInfo.access_token).then(
        res => {
          this.codeLoading = false;
          this.codeFnDisable = false;
          if (!res.data.data) {
            return this.$message.info(res.data.msg);
          } else {
            this.$message.success("发送成功");

            let count = 60;
            let timer = setInterval(() => {
              if (count === 0) {
                this.title = "发送验证码";
                clearInterval(timer);
              } else {
                count--;
                this.title = count;
              }
            }, 1000);
          }
        }
      );
    }, 500),
    verifySuccess(params) {
      this.loginForm.code = params.captchaVerification;
      this.loginForm.w1 = this.loginForm.password;
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.$store
            .dispatch("LoginByUsername", this.loginForm)
            .then(async res => {
              console.log("res", res);
              this.loginInfo = res.data;
              if (res.data.user_info) {
                this.codeForm.phone = res.data.user_info.phone;
                this.codeVisible = true;
              }
              return;
              // this.getDrugEntList();
            });
        }
      });
    },
    async codeSubmit() {
      if (!this.codeForm.code) {
        return this.$message.error("请输入验证码");
      }
      this.codeFnLoading = true;
      const res = await verifyCodeApi(
        this.codeForm.phone,
        this.codeForm.code,
        this.loginInfo.access_token
      );
      this.codeFnLoading = false;
      if (res.data.data) {
        this.$store.dispatch("SetInfo", this.loginInfo);
        this.$store.dispatch("getDeptExpiryAction");
        this.$router.push({ path: this.tagWel.value });
      } else {
        return this.$message.error("验证码错误");
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.font-gry {
  color: #d2d2d2;
}
</style>
