<template>
  <basic-container>
    <el-tabs v-model="activeName" class="tabs">
      <el-tab-pane label="账户安全" name="accountSafe">
        <el-row class="content">
          <el-col :span="24">
            <el-row>
              <el-col :span="24" class="title">
                <b>账户信息</b>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">登录账号：{{userInfo.account}}</el-col>
            </el-row>
            <el-row>
              <el-col :span="24">姓名：{{userInfo.real_name}}</el-col>
            </el-row>
            <el-row>
              <el-col :span="21">手机号码：{{userInfo.account}}</el-col>
              <el-col :sm="24" :lg="3">
                <el-button type="text" @click="leaderBox = true" v-show="isAdmin">变更负责人</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row class="content">
          <el-col :span="24">
            <el-row>
              <el-col :span="24" class="title">
                <b>账户安全</b>
              </el-col>
            </el-row>
            <el-row>
              <el-col :sm="24" :lg="6">登录密码：已设置</el-col>
              <el-col :sm="24" :lg="15">安全性高的密码可以使账号更安全。</el-col>
              <el-col :sm="24" :lg="3">
                <el-button type="text" @click="passwordBox = true">修改密码</el-button>
              </el-col>
            </el-row>
            <el-row>
              <el-col :sm="24" :lg="6">绑定手机号码：已绑定</el-col>
              <el-col :sm="24" :lg="15">绑定手机后，您即可享受丰富的手机服务，如手机找回密码等。</el-col>
              <el-col :sm="24" :lg="3">
                <el-button type="text" @click="phoneBox = true">换绑手机号码</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <!--修改负责人-->
    <el-dialog
      title="变更负责人"
      append-to-body
      :visible.sync="leaderBox"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="30%"
      @closed="closed"
      :loading="leaderLoading"
    >
      <el-form
        ref="leaderForm"
        label-position="left"
        label-width="110px"
        size="small"
        :rules="rules"
        :model="leaderForm"
      >
        <el-form-item label="用户姓名" prop="realName">
          <el-input v-model="leaderForm.realName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="身份证号码" prop="idNumber">
          <el-input v-model="leaderForm.idNumber" placeholder="请输入身份证号码"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="leaderForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="短信验证码" prop="code">
          <el-input v-model="leaderForm.code" placeholder="请输入短信验证码">
            <template slot="append">
              <el-button
                type="text"
                @click="handleSend('leaderForm','phone')"
                class="msg-text"
                :loading="sending"
                :disabled="msgKey"
              >{{msgText}}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-alert title="注：变更后初始密码为手机号后六位" type="warning" :closable="false"></el-alert>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          icon="el-icon-check"
          type="primary"
          @click="submitLeader"
          size="mini"
          :loading="leaderLoading"
        >提 交</el-button>
        <el-button
          icon="el-icon-circle-close"
          @click="leaderBox = false"
          size="mini"
          :loading="leaderLoading"
        >取 消</el-button>
      </span>
    </el-dialog>
    <!--/修改负责人-->

    <!--修改密码-->
    <el-dialog
      title="修改密码"
      append-to-body
      :visible.sync="passwordBox"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="30%"
      @closed="passwordClosed"
    >
      <el-form
        ref="passwordForm"
        label-position="left"
        label-width="110px"
        size="small"
        :rules="rules"
        :model="passwordForm"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            auto-complete="off"
            placeholder="请输入原登录密码"
            :type="passwordType"
          >
            <i
              class="el-icon-view el-input__icon"
              slot="suffix"
              @mouseenter="passwordType='input'"
              @mouseleave="passwordType='password'"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            placeholder="6-20位包含数字和字母"
            :type="passwordType1"
          >
            <i
              class="el-icon-view el-input__icon"
              slot="suffix"
              @mouseenter="passwordType1='input'"
              @mouseleave="passwordType1='password'"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="newPassword1">
          <el-input
            v-model="passwordForm.newPassword1"
            placeholder="6-20位包含数字和字母"
            :type="passwordType2"
          >
            <i
              class="el-icon-view el-input__icon"
              slot="suffix"
              @mouseenter="passwordType2='input'"
              @mouseleave="passwordType2='password'"
            ></i>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          icon="el-icon-check"
          type="primary"
          @click="submitPwd"
          size="mini"
          :loading="passwordLoading"
        >提 交</el-button>
        <el-button
          icon="el-icon-circle-close"
          @click="passwordBox = false"
          size="mini"
          :loading="passwordLoading"
        >取 消</el-button>
      </span>
    </el-dialog>
    <!--/修改密码-->

    <!--修改手机号-->
    <el-dialog
      title="换绑手机号码"
      append-to-body
      :visible.sync="phoneBox"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="30%"
      @closed="phoneClosed"
    >
      <el-form
        ref="phoneForm"
        label-position="left"
        label-width="110px"
        size="small"
        :rules="rules"
        :model="phoneForm"
      >
        <el-form-item label="原手机号码" prop="oldPhone">
          <el-input v-model="phoneForm.oldPhone" placeholder="请输入原手机号码" readonly></el-input>
        </el-form-item>
        <el-form-item label="新手机号码" prop="newPhone">
          <el-input v-model="phoneForm.newPhone" placeholder="请输入要更换的手机号"></el-input>
        </el-form-item>
        <el-form-item label="短信验证码" prop="code">
          <el-input v-model="phoneForm.code" placeholder="请输入短信验证码">
            <template slot="append">
              <el-button
                type="text"
                @click.prevent="handleSend('phoneForm','newPhone')"
                class="msg-text"
                :loading="sending"
                :disabled="msgKey"
              >{{msgText}}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-alert title="注：变更后初始密码为手机号后六位" type="warning" :closable="false"></el-alert>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button
          icon="el-icon-check"
          type="primary"
          @click="submitPhone"
          size="mini"
          :loading="phoneLoading"
        >提 交</el-button>
        <el-button
          icon="el-icon-circle-close"
          @click="phoneBox = false"
          size="mini"
          :loading="phoneLoading"
        >取 消</el-button>
      </span>
    </el-dialog>
    <!--/修改手机号-->
  </basic-container>
</template>
<script>
import { isvalidatemobile, check18IdCardNo, password } from "@/util/validate";
import {
  changeLeader,
  changePwd,
  sendCode,
  changePhone,
} from "@/api/tenant/account";
import { resetRouter } from "@/router/router";
import { mapGetters } from "vuex";
import md5 from "js-md5";

const wait = 120;

export default {
  data() {
    const IdCardNo = (rule, value, callback) => {
      if (check18IdCardNo(value)) {
        callback();
      } else {
        callback(new Error("身份证格式不正确"));
      }
    };
    const validatePhone = (rule, value, callback) => {
      if (isvalidatemobile(value)[0]) {
        callback(new Error(isvalidatemobile(value)[1]));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      if (value && value.length !== 4) {
        callback(new Error("验证码错误"));
      } else {
        callback();
      }
    };

    const validatePassDef = (rule, value, callback) => {
      if (
        this.passwordForm.oldPassword &&
        value === this.passwordForm.oldPassword
      ) {
        callback(new Error("新密码不能与原密码相同"));
      } else if (password(value)) {
        callback(new Error("密码需要包含数字和字母，并且长度为6-20位"));
      } else {
        callback();
      }
    };

    const validatePassDef2 = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error("两次密码不一致"));
      } else if (password(value)) {
        callback(new Error("密码需要包含数字和字母，并且长度为6-20位"));
      } else {
        callback();
      }
    };

    const validatePhoneDef = (rule, value, callback) => {
      if (value === this.phoneForm.oldPhone) {
        callback(new Error("新手机号码与原手机号码不能相同"));
      } else {
        callback();
      }
    };
    return {
      passwordLoading: false,
      leaderLoading: false,
      phoneLoading: false,
      sending: false,
      passwordType: "password",
      passwordType1: "password",
      passwordType2: "password",
      msgKey: false,
      msgText: "获取验证码",
      time: null,
      activeName: "accountSafe",
      accountForm: {},
      leaderForm: {},
      passwordForm: {},
      phoneForm: {},
      loading: false,
      leaderBox: false,
      passwordBox: false,
      phoneBox: false,
      rules: {
        realName: [
          {
            required: true,
            whitespace: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        idNumber: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          { validator: IdCardNo, trigger: "blur" },
        ],
        phone: [{ required: true, trigger: "blur", validator: validatePhone }],
        code: [
          { required: true, message: "请输入短信验证码", trigger: "blur" },
          { validator: validateCode, trigger: "blur" },
        ],
        oldPassword: [
          {
            required: true,
            whitespace: true,
            message: "请输入原来登录密码",
            trigger: "blur",
          },
        ],
        newPassword: [
          {
            required: true,
            whitespace: true,
            message: "请输入新密码",
            trigger: "blur",
          },
          {
            validator: validatePassDef,
            trigger: "blur",
          },
        ],
        newPassword1: [
          {
            required: true,
            whitespace: true,
            message: "请再次输入密码",
            trigger: "blur",
          },
          {
            validator: validatePassDef2,
            trigger: "blur",
          },
        ],
        oldPhone: [
          { required: true, validator: validatePhone, trigger: "blur" },
        ],
        newPhone: [
          {
            required: true,
            message: "请输入要更换的手机号码",
            trigger: "blur",
          },
          {
            validator: validatePhoneDef,
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.phoneForm = { oldPhone: this.userInfo.account };
  },
  components: {},
  methods: {
    /*发送验证码 */
    handleSend(form, field) {
      if (this.msgKey) return;
      this.$refs[form].validateField(field, (error) => {
        if (!error) {
          this.sending = true;
          sendCode(this[form][field]).then(
            () => {
              let time = wait;
              this.msgText = `剩余${time--}s`;
              this.msgKey = true;
              this.time = setInterval(() => {
                this.msgText = `剩余${time--}s`;
                if (time <= 0) {
                  this.clearTime(); //清除定时器
                }
              }, 1000);
              this.sending = false;
            },
            () => {
              this.sending = false;
              this.$message.error("发送失败!");
            }
          );
        }
      });
    },
    /*提交变更负责人*/
    submitLeader() {
      this.$refs.leaderForm.validate((valid) => {
        if (valid) {
          this.leaderLoading = true;
          changeLeader(this.leaderForm).then(
            () => {
              this.leaderBox = false;
              this.leaderLoading = false;
              this.$store.dispatch("LogOut").then(() => {
                resetRouter();
                this.$router.push({ path: "/login" });
                this.$message({
                  type: "success",
                  message: "操作成功,请重新登录！",
                });
              });
            },
            (error) => {
              window.console.log(error);
              this.leaderLoading = false;
            }
          );
        }
      });
    },
    /*提交修改密码 */
    submitPwd() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          this.passwordLoading = true;
          changePwd(
            md5(this.passwordForm.oldPassword),
            md5(this.passwordForm.newPassword),
            md5(this.passwordForm.newPassword1)
          ).then(
            () => {
              this.passwordBox = false;
              this.passwordLoading = false;
              this.$store.dispatch("LogOut").then(() => {
                resetRouter();
                this.$router.push({ path: "/login" });
                this.$message({
                  type: "success",
                  message: "操作成功,请重新登录！",
                });
              });
            },
            (error) => {
              window.console.log(error);
              this.passwordLoading = false;
            }
          );
        }
      });
    },
    /*提交修改手机号 */
    submitPhone() {
      this.$refs.phoneForm.validate((valid) => {
        if (valid) {
          this.phoneLoading = true;
          changePhone(this.phoneForm).then(
            () => {
              this.phoneBox = false;
              this.phoneLoading = false;
              this.$store.dispatch("LogOut").then(() => {
                resetRouter();
                this.$router.push({ path: "/login" });
                this.$message({
                  type: "success",
                  message: "操作成功,请重新登录！",
                });
              });
            },
            (error) => {
              window.console.log(error);
              this.phoneLoading = false;
            }
          );
        }
      });
    },
    closed() {
      this.clearTime();
      this.leaderForm = {};
      if (this.$refs.leaderForm) {
        this.$refs.leaderForm.resetFields();
      }
    },
    passwordClosed() {
      this.passwordForm = {};
      if (this.$refs.passwordForm) {
        this.$refs.passwordForm.resetFields();
      }
    },
    phoneClosed() {
      this.clearTime();
      if (this.$refs.phoneForm) {
        this.$refs.phoneForm.resetFields();
      }
      this.phoneForm = { oldPhone: this.userInfo.account };
    },
    /*清除code定时器 */
    clearTime() {
      this.msgText = "获取验证码";
      this.msgKey = false;
      clearInterval(this.time);
    },
  },
  computed: {
    ...mapGetters(["userInfo"]),
    isAdmin() {
      return this.userInfo.is_master;
    },
  },
};
</script>
<style scoped>
  .el-form-item{
    margin-bottom: 22px !important;
  }
.el-row {
  margin-top: 10px;
}
.el-col {
  margin-bottom: 0px;
  line-height: 40px;
}
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 30px;
}
.tabs {
  padding: 20px 10px 0;
}
.content {
  border: 1px solid #333333;
  padding: 10px 40px;
  font-size: 16px;
  margin: 30px 30px;
}
.msg-text {
  display: block;
  width: 120px;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
}
</style>
