<template>
    <div>
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item required prop="username"v-if='isLogin'>
          <a-input v-model="model.username" size="large" placeholder="请输入帐户名">
            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
          </a-input>
        </a-form-model-item>
        <a-form-model-item required prop="password" v-if='isLogin'>
          <a-input-password v-model="model.password" size="large" type="password" autocomplete="false" placeholder="请输入密码">
            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
          </a-input-password>
        </a-form-model-item>

        <a-row :gutter="0" v-if='isLogin'>
          <a-col :span="16">
            <a-form-model-item required prop="inputCode">
              <a-input v-model="model.inputCode" size="large" type="text" placeholder="请输入验证码">
                <a-icon slot="prefix" type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" style="text-align: right">
            <img v-if="requestCodeSuccess" style="margin-top: 2px;" :src="randCodeImage" @click="handleChangeCheckCode"/>
            <img v-else style="margin-top: 2px;" src="../../assets/checkcode.png" @click="handleChangeCheckCode"/>
          </a-col>
        </a-row>

        <a-form-model-item required  v-if='!isLogin' prop='passwordNew'>
          <a-input-password v-model="model.passwordNew" size="large"  type="password" placeholder="请输入新密码"  >
            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
          </a-input-password>
        </a-form-model-item>
        <a-form-model-item required  v-if='!isLogin' prop='passwordNew' >
          <a-input-password v-model="model.passwordNew2"  size="large" type="password"  placeholder="请确认新密码"
                    >
            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
          </a-input-password>
        </a-form-model-item>
        <a-form-item style="margin-top:24px;width: 100px" v-if='!isLogin'>
          <a-button size="large"  type="primary"  htmlType="submit" @click='updatePassword'  class="login-button"  >修改密码
          </a-button>
        </a-form-item>
      </a-form-model>
    </div>
</template>

<script>
import { getAction, postAction, putAction } from '@/api/manage'
  import Vue from 'vue'
  import { mapActions } from 'vuex'

  export default {
    name: 'LoginAccount',
    data(){
      return {
        isLogin:true,
        confirmDirty:false,
        requestCodeSuccess: false,
        randCodeImage: '',
        currdatetime: '',
        loginType: 0,
        model:{
          passwordNew: '',
          passwordNew2: '',
          username: '',
          password: '',
          inputCode: ''
        },
        validatorRules:{
            passwordNew: [
              { required: true, pattern:/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/, message: '密码由8位数字、大小写字母和特殊符号组成!' },
              { validator: this.validateToNextPassword, }
            ],
          username: [
            { required: true, message: '请输入用户名!' },
            { validator: this.handleUsernameOrEmail }
          ],
          password: [{
            required: true, message: '请输入密码!', validator: 'click'
          }],
          inputCode: [{
            required: true, message: '请输入验证码!'
          }],
          confirmpassword: [
            { required: true, message: '请确认新密码!', },
            {
              validator: this.validateToNextPassword, }],
        },

      }
    },
    created() {
      this.handleChangeCheckCode();
    },
    methods:{

      updatePassword() {
            const that = this;
            that.confirmLoading = true;
            //let params = Object.assign({username:this.model.username},values)
            let params={
              username:this.model.username,
              oldpassword:this.model.password,
              confirmpassword:this.model.passwordNew2,
             password:this.model.passwordNew
            }
            console.log("修改密码提交数据",params)
            putAction("/sys/updatePassword",params).then((res)=>{
              if(res.success){
                console.log(res)
                that.$message.success(res.message);
                that.isLogin=true;
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
      },
      compareToFirstPassword (rule, value, callback) {
        if (value && value !== this.model.passwordNew) {
          callback('两次输入的密码不一样！');
        } else {
          callback()
        }
      },
      validateToNextPassword (rule, value, callback) {
        const confirmpassword=this.model.passwordNew2;
        if (value && confirmpassword && value !== confirmpassword) {
          callback('两次输入的密码不一样！');
        }
        if (value && this.confirmDirty) {
          this.$refs.form.validateField(['confirmpassword']);
        }
        callback();
      },
      ...mapActions(['Login']),
      /**刷新验证码*/
      handleChangeCheckCode(){
        this.currdatetime = new Date().getTime();
        this.model.inputCode = ''
        getAction(`/sys/randomImage/${this.currdatetime}`).then(res=>{
          if(res.success){
            this.randCodeImage = res.result
            this.requestCodeSuccess=true
          }else{
            this.$message.error(res.message)
            this.requestCodeSuccess=false
          }
        }).catch(()=>{
          this.requestCodeSuccess=false
        })
      },
      // 判断登录类型
      handleUsernameOrEmail (rule, value, callback) {
        const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        if (regex.test(value)) {
          this.loginType = 0
        } else {
          this.loginType = 1
        }
        callback()
      },
      /**
       * 验证字段
       * @param arr
       * @param callback
       */
      validateFields(arr, callback){
        let promiseArray = []
        for(let item of arr){
          let p = new Promise((resolve, reject) => {
            this.$refs['form'].validateField(item, (err)=>{
              if(!err){
                resolve();
              }else{
                reject(err);
              }
            })
          });
          promiseArray.push(p)
        }
        Promise.all(promiseArray).then(()=>{
          callback()
        }).catch(err=>{
          callback(err)
        })
      },
      acceptUsername(username){
        this.model['username'] = username
      },
      //账号密码登录
      handleLogin(rememberMe){
        this.validateFields([ 'username', 'password', 'inputCode' ], (err)=>{
          if(!err){
            let loginParams = {
              username: this.model.username,
              password: this.model.password,
              captcha: this.model.inputCode,
              checkKey: this.currdatetime,
              remember_me: rememberMe,
            }
            //console.log("登录参数", loginParams)
            this.Login(loginParams).then((res) => {
              //判断是否首次登录
              // let httpUrl = '/sys/loginFirst';
              // postAction(httpUrl, loginParams).then((resa) => {
              //   if (!resa.success) {
              //     this.$message.error( resa.message);
              //     this.isLogin=false
              //   }else {
                  this.$emit('success', res.result)
              //   }
              // })
            }).catch((err) => {
              if (err.message.indexOf("修改密码")!== -1){
                this.isLogin=false
              }
              this.$emit('fail', err)
            });
          }else{
            this.$emit('validateFail')
          }
        })
      },
      handleConfirmBlur  (e) {
        const value = e.target.value
        this.confirmDirty = this.confirmDirty || !!value
      },

    }

  }
</script>

<style scoped>

</style>