<template>
  <div>
    <!-- 修改密码页面 -->
    <!-- 头部标签 -->
    <LHeader :text="$route.meta.title"></LHeader>

    <van-form
      @submit="onSubmit"
      :scroll-to-error="true"
      :show-error="false"
      validate-trigger="onSubmit"
    >
      <van-field
        v-model="form.oldPassword"
        required
        type="text"
        name="oldPassword"
        label="旧密码"
        placeholder="请输入旧密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        required
        v-model="form.newPassword"
        type="password"
        name="newPassword"
        label="新密码"
        @input="checkPassword()"
        placeholder="请输入新密码"
        :rules="[
          { required: true, message: '请填写密码' },
          {
            message: '密码必须大于8个字符小于30个字符',
            validator: (val) => {
              return val['length'] >= 8 && val['length'] < 30;
            },
          },
        ]"
      />
      <!-- 密码等级提示 -->
      <van-cell-group>
        <div class="intensity">
          <div style="width: 8.2em;"></div>
          <div>
            <div class="pass-level">
                <span class="psdText">密码强度</span>
                <span class="line" :class="[level.includes('low') ? 'low' : '']"></span>
                <span class="line" :class="[level.includes('middle') ? 'middle' : '']" ></span>
                <span class="line" :class="[level.includes('high') ? 'high' : '']" ></span>
            </div>
          </div>
        </div>
      </van-cell-group>
      <van-field
        required
        v-model="form.confirm"
        type="password"
        name="confirm"
        label="再次输入"
        placeholder="再次输入新密码"
        :rules="[
          { validator, required: true, message: '二次密码输入不一致' },
          {
            message: '密码必须大于等于8个字符小于30个字符',
            validator: (val) => {
              return val['length'] >= 8 && val['length'] < 30;
            },
          },
        ]"
      />

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import LHeader from "@/components/header.vue";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getFun, postFun } from "@/service/table.js";
import { getUserInfo } from "@/utils/userInfo";
import { removeToken } from "@/utils/auth"; // get token from cookie
export default {
  components: {
    LHeader,
  },
  data() {
    return {
      form: {
        oldPassword: "",
        newPassword: "",
        confirm: "",
      },
      level : []
    };
  },
  mounted() {
    console.log(getUserInfo());
  },
  methods: {
    validator(val) {
      return this.form.newPassword == val;
    },
    onSubmit(val) {
      // 判断level数组是否含有middle
      let isMiddleLevel = this.level.includes('high')
      if(!isMiddleLevel){
        this.$toast.fail("密码等级较低")
        return
      }
      this.$toast.loading({
        message: "请求中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      postFun("/mobile/resetPwd", this.obj2formdata(val)).then((data) => {
        if (data.code == 0) {
          this.$toast.clear();
          this.$toast.success("密码修改成功!");
          localStorage.setItem('pwd',encrypt(this.form.newPassword))
          this.$router.push('/save-workbench')
        }
      });
    },
    obj2formdata(data) {
      console.log(data, "fasfasdfsd");
      let fd = new FormData();
      for (let k in data) {
        if (data[k]) {
          fd.append(k, data[k]);
        }
      }
      return fd;
    },

    // 密码等级校验
    checkPassword() {
      this.level = [];
      // 校验是数字
      const regex1 = /^\d+$/;
      // 校验字母
      const regex2 = /^[A-Za-z]+$/;
      // 校验符号
      const regex3 =
        /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]+$/;

      if (regex1.test(this.form.newPassword)) {
        this.level.push("low");
      } else if (regex2.test(this.form.newPassword)) {
        this.level.push("low");
      } else if (regex3.test(this.form.newPassword)) {
        this.level.push("low");
      } else if (/^[A-Za-z\d]+$/.test(this.form.newPassword)) {
        this.level.push("low");
        this.level.push("middle");
      } else if (
        /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、\d]+$/.test(
          this.form.newPassword
        )
      ) {
        this.level.push("low");
        this.level.push("middle");
      } else if (
        /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z]+$/.test(
          this.form.newPassword
        )
      ) {
        this.level.push("low");
        this.level.push("middle");
      } else if (
        /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z\d]+$/.test(
          this.form.newPassword
        )
      ) {
        this.level.push("low");
        this.level.push("middle");
        this.level.push("high");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.intensity {
  display: flex;
  padding: 0.26667rem 0.42667rem;
  line-height: 0.64rem;
	.psdText {
		font-size: 14px;
		margin-right: 10px;
	}

	.line {
		display: inline-block;
		width: 48px;
		height: 4px;
		background: #d8d8d8;
		border-radius: 3px;
		margin-right: 8px;
	}
	.low {
		background: #f4664a;
	}
	.middle {
		background: #ffb700;
	}
	.high {
		background: #2cbb79;
	}
}

</style>