<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <p class="fs18">修改密码</p>
      </div>
      <el-form :model="setForm" label-width="160px" size="small" class="set-form">

        <el-form-item label="平台登录账号：">
          <el-input v-model="setForm.name" :disabled="true" style="width: 300px;margin-right:20px;"></el-input>
          <el-button type="primary" icon="el-icon-edit" @click="editAccount('accountForm')">修改账号</el-button>
        </el-form-item>

        <el-form-item label="登录密码：">
          <el-input v-model="setForm.loginpsd" :disabled="true" style="width: 300px;margin-right:20px;"></el-input>
          <el-button type="primary" icon="el-icon-edit" @click="editLogin('loginForm')">修改密码</el-button>
        </el-form-item>

        <el-form-item>
          <p class="tipsGray">平台登陆账号和密码用于登陆开放平台，建议您定期修改</p>
        </el-form-item>

        <div style="width: 320px;margin:30px 160px 50px;">
          <el-divider></el-divider>
        </div>

        <el-form-item label="提现密码：">
          <el-input v-model="setForm.paypsd" :disabled="true" style="width: 300px;margin-right:20px;"></el-input>
          <el-button type="primary" icon="el-icon-edit" @click="editPay('payForm')">修改密码</el-button>
        </el-form-item>

        <el-form-item>
          <p class="tipsGray">提现密码用于提现，请妥善保管您的提现密码，切勿告诉其他人，以免财产造成损失！</p>
        </el-form-item>
      </el-form>
    </el-card>
    <!--修改 账号 对话框-->
    <el-dialog title="修改登录账号" :visible.sync="isAccount" width="50%">
      <el-form :model="accountForm" :rules="accountRules" ref="accountForm" label-width="200px" size="small">

        <el-form-item label="登录密码：" prop="password">
          <el-input v-model="accountForm.password" placeholder="请输入登录密码" style="width: 300px"></el-input>
        </el-form-item>

        <el-form-item label="新手机号：" prop="mobile">
          <el-input v-model="accountForm.mobile" placeholder="请输入新的手机号码"
                    style="width: 300px;margin-right:20px;"></el-input>
          <el-button type="primary" icon="el-icon-edit" @click="getAccountCode()" v-if="isAccountCode">获取验证码</el-button>
          <el-button type="info" style="width: 109px" :disabled="true" v-if="!isAccountCode">倒计时 {{ accountCountDown }}
            S
          </el-button>
        </el-form-item>

        <el-form-item label="短信验证码：" prop="code">
          <el-input v-model="accountForm.code" placeholder="请输入短信验证码" style="width: 300px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel('accountForm')">取 消</el-button>
        <el-button type="primary" @click="submitAccount('accountForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改登录密码 对话框-->
    <el-dialog title="修改登录密码" :visible.sync="isLogin" width="50%">
      <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="200px" size="small">

        <el-form-item label="新密码：" prop="password">
          <el-input v-model="loginForm.password" plackeholder="请输入新密码" style="width: 300px" show-password></el-input>
        </el-form-item>

        <el-form-item label="确认新密码：" prop="password2">
          <el-input v-model="loginForm.password2" plackeholder="请输入新密码" style="width: 300px"
                    show-password></el-input>
        </el-form-item>

        <el-form-item label="短信验证码：" prop="code">
          <el-input v-model="loginForm.code" :placeholder="showMobilePlaceholder"
                    style="width: 300px;margin-right:20px;"></el-input>
          <el-button type="primary" icon="el-icon-edit" @click="getLoginCode()" v-if="isLoginCode">获取验证码</el-button>
          <el-button type="info" style="width: 109px" :disabled="true" v-if="!isLoginCode">倒计时 {{ loginCountDown }} S
          </el-button>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel('loginForm')">取 消</el-button>
        <el-button type="primary" @click="submitLogin('loginForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改提现密码 对话框-->
    <el-dialog title="修改提现密码" :visible.sync="isPay" width="50%">
      <el-form :model="payForm" :rules="payRules" ref="payForm" label-width="200px" size="small">

        <el-form-item label="新密码：" prop="password">
          <el-input v-model="payForm.password" plackeholder="请输入新密码" style="width: 300px" show-password></el-input>
        </el-form-item>

        <el-form-item label="确认新密码：" prop="password2">
          <el-input v-model="payForm.password2" plackeholder="请输入新密码" style="width: 300px"
                    show-password></el-input>
        </el-form-item>

        <el-form-item label="短信验证码：" prop="code">
          <el-input v-model="payForm.code" :placeholder="showMobilePlaceholder"
                    style="width: 300px;margin-right:20px;"></el-input>
          <el-button type="primary" icon="el-icon-edit" @click="getPayCode()" v-if="isPayCode">获取验证码</el-button>
          <el-button type="info" style="width: 109px" :disabled="true" v-if="!isPayCode">倒计时 {{payCountDown}} S
          </el-button>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel('payForm')">取 消</el-button>
        <el-button type="primary" @click="submitPay('payForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {changeTelphone, getTelphoneCode,getEditPayPasswordCode,changeLoginPassword,changePayPassword } from '@/api/module/settings'

  export default {
    name: "Setpsd",
    data() {
      // 手机号码格式校验
      let checkTel = (rule, value, callback) => {
        const reg = /^1[3456789]\d{9}$/;
        if (value === '') {
          callback(new Error('手机号码不能为空'));
        } else if (!reg.test(value)) {
          callback(new Error('手机号码格式不对,请重新输入'));
        } else {
          callback();
        }
      };
      // 校验新 登录密码
      let checkNewPsd = (rule, value, callback) => {
        const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/;
        if (value === '') {
          callback(new Error('密码不能为空'));
        } else if (!reg.test(value)) {
          callback(new Error('密码为8-16位，由数字和字母组成'));
        } else {
          callback();
        }
      };
      // 二次输入 登录密码
      let checkNewPsdAgain = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('密码不能为空'));
        } else if (value !== this.loginForm.password) {
          callback(new Error('两次密码不一致，请检查后重新输入'));
        } else {
          callback();
        }
      };
      // 校验 提现密码
      let checkPayPsd = (rule, value, callback) => {
        const reg = /^[0-9]{6}$/;
        if (value === '') {
          callback(new Error('密码不能为空'));
        } else if (!reg.test(value)) {
          callback(new Error('密码位6位数字'));
        } else {
          callback();
        }
      };
      // 二次输入 登录密码
      let checkPayPsdAgain = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('密码不能为空'));
        } else if (value !== this.payForm.password) {
          callback(new Error('两次密码不一致，请检查后重新输入'));
        } else {
          callback();
        }
      };
      return {
        isAccount: false,
        isLogin: false,
        isPay: false,
        isAccountCode: true,
        isLoginCode: true,
        isPayCode: true,
        accountCountDown: '',
        loginCountDown: '',
        payCountDown: '',
        showMobilePlaceholder: '',
        setForm: {
          name: '',
          loginpsd: '******',
          paypsd: '******'
        },
        accountForm: {
          password: '',
          mobile: '',
          code: ''
        },
        accountRules: {
          password: [{required: true, message: '登录密码不能为空', trigger: 'blur'}],
          mobile: [{required: true, validator: checkTel, trigger: 'blur'}],
          code: [{required: true, message: '验证码不能为空', trigger: 'blur'}],
        },
        loginForm: {
          password: '',
          password2: '',
          code: ''
        },
        loginRules: {
          password: [{required: true, validator: checkNewPsd, trigger: 'blur'}],
          password2: [{required: true, validator: checkNewPsdAgain, trigger: 'blur'}],
          code: [{required: true, message: '验证码不能为空', trigger: 'blur'}]
        },
        payForm: {
          password: '',
          password2: '',
          code: '',
        },
        payRules: {
          password: [{required: true, validator: checkPayPsd, trigger: 'blur'}],
          password2: [{required: true, validator: checkPayPsdAgain, trigger: 'blur'}],
          code: [{required: true, message: '验证码不能为空', trigger: 'blur'}],
        }
      }
    },
    mounted() {
      this.setForm.name = this.$store.state.user.name;
      //console.log(333,this.setForm.name);
      let repStr = this.setForm.name.substring(3,7);
      this.showMobilePlaceholder = '请输入' + this.setForm.name.replace(repStr, '****') + '的验证码';
    },
    methods: {
      // 修改 账号
      editAccount() {
        this.isAccount = true;
      },
      // 修改 登录密码
      editLogin() {
        if (this.$refs.loginForm) {
          this.$refs['loginForm'].resetFields();
        }
        this.isLogin = true;
      },
      // 修改 提现密码
      editPay() {
        this.isPay = true;
      },
      // 修改账号 获取验证码
      getAccountCode() {
        // 先校验
        if (this.accountForm.password === '') {
          this.$refs.accountForm.validateField('password');
          return;
        }
        //
        const telphoneReg = /^1[3456789]\d{9}$/;
        if (!telphoneReg.test(this.accountForm.mobile)) {
          this.$refs.accountForm.validateField('mobile');
          return;
        }
        const TIME_COUNT = 60;
        // let count =
        if (!this.timer) {
          this.accountCountDown = TIME_COUNT;
          this.isAccountCode = false;
          this.timer = setInterval(() => {
            if (this.accountCountDown > 0 && this.accountCountDown <= TIME_COUNT) {
              this.accountCountDown--;
            } else {
              this.isAccountCode = true;
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000)
        }
        // 获取验证码
        getTelphoneCode(this.accountForm.mobile).then(res => {
          if(res.code === 1) {
            this.$message({type:"success",message: '验证码发送成功'});
          }else {
            this.$message({type:"error",message: '验证码发送失败'});
          }
        });

      },
      // 修改登录密码的 获取校验码 loginCountDown
      getLoginCode() {
        let loginpsdReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/;
        if (this.loginForm.password === '' || !loginpsdReg.test(this.loginForm.password)) {
          this.$refs.loginForm.validateField('password');
          return;
        }

        if (this.loginForm.password2 === '' || this.loginForm.password2 !== this.loginForm.password) {
          this.$refs.loginForm.validateField('password2');
          return;
        }

        const TIME_COUNT = 60;
        if (!this.timer) {
          this.loginCountDown = TIME_COUNT;
          this.isLoginCode = false;
          this.timer = setInterval(() => {
            if (this.loginCountDown > 0 && this.loginCountDown <= TIME_COUNT) {
              this.loginCountDown--;
            } else {
              this.isLoginCode = true;
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000)
        }
        getTelphoneCode(this.setForm.name).then(res => {
          if(res.code == 1) {
            this.$message({type:"success",message: '验证码发送成功'});
          }else {
            this.$message({type:"error",message: res.message ? res.message : '验证码发送失败'});
          }
        });
      },
      // 修改提现密码，获取手机验证码
      getPayCode() {
        let paypsdReg = /^[0-9]{6}$/;
        if (this.payForm.password === '' || !paypsdReg.test(this.payForm.password)) {
          this.$refs.payForm.validateField('password');
          return;
        }

        if (this.payForm.password2 === '' || this.payForm.password2 !== this.payForm.password) {
          this.$refs.payForm.validateField('password2');
          return;
        }

        const TIME_COUNT = 60;
        if (!this.timer) {
          this.payCountDown = TIME_COUNT;
          this.isPayCode = false;
          this.timer = setInterval(() => {
            if (this.payCountDown > 0 && this.payCountDown <= TIME_COUNT) {
              this.payCountDown--;
            } else {
              this.isPayCode = true;
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000)
        }
        getEditPayPasswordCode(this.setForm.name).then(res => {
          if(res.code === 1) {
            this.$message({type:"success",message: '验证码发送成功'});
          }else {
            this.$message({type:"error",message: '验证码发送失败'});
          }
        });
      },
      // 平台登录账号修改 提交
      submitAccount(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {

            changeTelphone(this.accountForm).then(res => {
              if(res.code === 1) {
                this.$message({type:"success",message: '登录账号修改成功，需重新登录'});
                this.isAccount = false;
                // 修改成功，则强制退出，重新登录
                this.$store.dispatch('LogOut').then(() => {
                  var ssa = window.location.host
                  setTimeout(function (){
                    if(ssa =='localhost:1024'){
                      window.location.href='http://sso.jxhh.com/api/v2/logout?redirect=http://'+ssa+'/login'
                    }else{
                      window.location.href='http://sso.jxhh.com/api/v2/logout?redirect=http://'+ssa+'/login'
                    }
                  }, 1000)
                })
              }else {
                let msg = res.msg || '修改失败';
                this.$message({type:"error",message: msg});
              }
              this.clearAccountCodeDown();
            });
          }
        });
      },
      // 登录密码  确定
      submitLogin(formName) {
        // console.log(378,this.loginForm);
        this.$refs[formName].validate(valid => {
          if (valid) {
            changeLoginPassword(this.loginForm).then(res=> {
              if(res.code === 1) {
                this.$message({type:"success",message: '登录密码修改成功，需重新登录'});
                // 修改成功，则强制退出，重新登录
                this.$store.dispatch('LogOut').then(() => {
                  var ssa = window.location.host
                  setTimeout(function (){
                    if(ssa =='localhost:1024'){
                      window.location.href='http://sso.jxhh.com/api/v2/logout?redirect=http://'+ssa+'/login'
                    }else{
                      window.location.href='http://sso.jxhh.com/api/v2/logout?redirect=http://'+ssa+'/login'
                    }
                  }, 1000)
                })
              }else {
                let msg = res.msg || '修改失败';
                this.$message({type:"error",message: msg});
              }
              this.clearAccountCodeDown();
              this.isLogin = false;
            });
          }
        });
      },
      // 提现密码 确定
      submitPay(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            changePayPassword(this.payForm).then(res => {
              if(res.code === 1) {
                this.$message({type:"success",message: '提现密码修改成功'});
                this.clearAccountCodeDown();
                this.isPay = false;
              }else {
                let msg = res.msg || '修改失败';
                this.$message({type:"error",message: msg});
              }
            });
          }
        });
      },
      // 取消
      cancel(formName) {
        // 清空倒计时
        this.clearAccountCodeDown();
        if (formName === 'accountForm') {
          this.isAccount = false;
          this.$refs[formName].resetFields();
        } else if (formName === 'loginForm') {
          this.isLogin = false;
          this.$refs[formName].resetFields();
        } else if (formName === 'payForm') {
          this.isPay = false;
          this.$refs[formName].resetFields();
        }
      },

      // 强制清空倒计时
      clearAccountCodeDown() {
        this.isAccountCode = true;
        this.isLoginCode = true;
        this.isPayCode = true;
        this.accountCountDown = '';
        this.loginCountDown = '';
        this.payCountDown = '';
      }
    }
  }
</script>

<style lang="scss" type="text/stylus" scoped>
  .card-cont {
    margin: 50px 0;
  }

  .set-form {
    width: 90%;
    margin: 40px 0 30px 100px;

    /deep/ .el-form-item {
      margin-top: 18px !important;
    }
  }

  .tipsGray {
    font-size: 14px;
    color: #C9C9C9;
  }
</style>
