<template>
  <div>
    <h1 style="text-align: center; margin-bottom: 30px;">安全设置</h1>
    <el-divider></el-divider>

    <div class="container">
      <div class="card left-card">
        <el-card style="margin-top: 50px;">
          <h2>登录密码</h2>
          <div class="container">
            <label>安全性高的密码可以使帐号更安全.建议你定期更换密码,设置6-20位登录密码</label>
            <div class="button-wrapper">
              <button @click="openModal">修改密码</button>
            </div>
          </div>
        </el-card>
      </div>

      <div class="card right-card">
        <el-card style="margin-top: 50px;">
          <h2>手机号码</h2>
          <label>安全手机可以用于登录帐号，重置密码或其他安全验证</label>
          <button @click="openCurrentPhoneModal">修改手机号</button>

          <!-- 输入当前手机号的弹出框 -->
          <div v-if="isCurrentPhoneModalVisible" class="modal-overlay">
            <div class="modal-content">
              <h3>当前手机号</h3>
              <div>旧手机号({{ user.phonenumber }})</div>
              <button @click="sendVerificationCode">发送验证码</button>
              <button @click="closeCurrentPhoneModal">取消</button>
            </div>
          </div>

          <!-- 输入验证码的弹出框 -->
          <div v-if="isVerificationModalVisible" class="modal-overlay">
            <div class="modal-content">
              <h3>输入验证码</h3>
              <input v-model="code" placeholder="验证码" />
              <button @click="verCode">验证并输入新手机号</button>
              <button @click="closeVerificationModal">取消</button>
            </div>
          </div>


          <!-- 输入新手机号的弹出框 -->
          <div v-if="isNewPhoneModalVisible" class="modal-overlay">
            <div class="modal-content">
              <h3>输入新手机号</h3>
              <input v-model="newPhone" placeholder="新手机号" @input="validatePhone" />
              <p v-if="phoneError" style="color: red" class="error">{{ phoneError }}</p>
              <button @click="updatePhoneNumber">提交修改</button>
              <button @click="closeNewPhoneModal">取消</button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <div>
      <el-card>
        <img src="/123456789.jpg" style="width: 40%; height: auto;" alt="Big Image">
      </el-card>
    </div>

    <!-- 弹出框 -->
    <div v-if="showModal" class="modal">
      <div class="modal-content">
        <h2>身份验证</h2>
        <el-divider></el-divider>

        <!-- 手机号和验证码 -->
        <div v-if="!verificationSent">
          <label for="phonenumber">身份验证方式:</label>
          <div><h3>通过手机({{ user.phonenumber }})获取验证</h3></div>
          <button @click="sendCode">发送验证码</button>
        </div>

        <div v-if="verificationSent && !codeVerified">
          <label for="code">验证码:</label>
          <input v-model="code" id="code" type="text" placeholder="请输入验证码" />
          <button @click="verifyCode">验证验证码</button>
        </div>

        <div v-if="codeVerified">
          <el-form ref="form" :model="user" :rules="rules" label-width="80px">
            <el-form-item label="旧密码" prop="oldPassword">
              <el-input v-model="user.oldPassword" placeholder="请输入旧密码" show-password type="password"/>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="user.newPassword" placeholder="请输入新密码" show-password type="password"/>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="user.confirmPassword" placeholder="请确认新密码" show-password type="password"/>
            </el-form-item>
          </el-form>
          <button @click="submit" :disabled="!user.newPassword">提交修改</button>
        </div>
        <button @click="closeModal" class="close-button">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import {getUserProfile,sendCode,checkCode,updatePhone} from "@/api/system/user";
import {updateUserPwd} from "@/api/system/user";

export default {
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.user.newPassword !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      isVisible: false,
      currentPhone: '',
      newPhone: '',
      phoneError: '',
      verificationCode: '',
      isCurrentPhoneModalVisible: false,
      isVerificationModalVisible: false,
      isNewPhoneModalVisible: false,
      // 表单校验
      rules: {
        oldPassword: [
          {required: true, message: "旧密码不能为空", trigger: "blur"}
        ],
        newPassword: [
          {required: true, message: "新密码不能为空", trigger: "blur"},
          {min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur"}
        ],
        confirmPassword: [
          {required: true, message: "确认密码不能为空", trigger: "blur"},
          {required: true, validator: equalToPassword, trigger: "blur"}
        ]
      },
      user: {
        oldPassword: undefined,
        newPassword: undefined,
        confirmPassword: undefined
      },
      showModal: false,
      aModel: false,
      phonenumber: '',
      code: '',
      oldPassword: '',
      newPassword: '',
      verificationSent: false,
      codeVerified: false,
    };
  },
  created() {
    this.getUser();
  },
  methods: {
    validatePhone() {
      const phonePattern = /^[0-9]{11}$/; // 只允许11位数字
      if (!this.newPhone) {
        this.phoneError = '手机号不能为空';
      } else if (!phonePattern.test(this.newPhone)) {
        this.phoneError = '请输入有效的11位手机号';
      } else {
        this.phoneError = '';
      }
    },
    updatePhoneNumber() {
      updatePhone(this.newPhone).then(response => {
        this.closeNewPhoneModal();
        this.$message({
          message: '修改成功',
          type: 'success'
        });
      });
    },
    closeNewPhoneModal() {
      this.isNewPhoneModalVisible = false;
    },
    closeVerificationModal() {
      this.isVerificationModalVisible = false;
    },
    sendVerificationCode() {
      try {
        sendCode(this.user.phonenumber)
        this.closeCurrentPhoneModal();
        this.isVerificationModalVisible = true;
        alert('验证码已发送');
      } catch (error) {
        console.error('发送验证码失败', error);
        alert('发送验证码失败');
      }
    },
    openCurrentPhoneModal() {
      this.isCurrentPhoneModalVisible = true;
    },
    closeCurrentPhoneModal() {
      this.isCurrentPhoneModalVisible = false;
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data.sysUser;
      });
    },
    openModal() {
      this.showModal = true;
    },
    closeModal() {
      this.showModal = false;
      this.resetForm();
    },
    async sendCode() {
      try {
        sendCode(this.user.phonenumber)
        this.verificationSent = true;
        alert('验证码已发送');
      } catch (error) {
        console.error('发送验证码失败', error);
        alert('发送验证码失败');
      }
    },
    submit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateUserPwd(this.user.oldPassword, this.user.newPassword).then(response => {
            this.$modal.msgSuccess("修改成功");
          });
        }
      });
    },
    async verCode() {
      checkCode(this.user.phonenumber, this.code).then(response => {
        if (response.code === 200) {
          this.closeVerificationModal();
          this.isNewPhoneModalVisible = true; // 验证成功后弹出新手机号输入框
          alert('验证码验证成功');
        } else {
          alert('验证码验证失败');
        }
      })
    },
    async verifyCode() {
      checkCode(this.user.phonenumber, this.code).then(response => {
        if (response.code === 200) {
          this.codeVerified = true;
          alert('验证码验证成功');
        } else {
          alert('验证码验证失败');
        }
      })
    }
  },


  resetForm() {
    this.phonenumber = '';
    this.code = '';
    this.oldPassword = '';
    this.newPassword = '';
    this.verificationSent = false;
    this.codeVerified = false;
  }
};
</script>

<style>
/* 简单样式，仅供参考 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.container {
  display: flex;
  justify-content: space-between;
}

.button-wrapper {
  margin-left: auto; /* 将按钮移动到右侧 */
}


.modal-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

h2 {
  margin-top: 0;
}

label {
  display: block;
  margin-top: 10px;
  font-weight: bold;
}

input {
  width: 100%;
  padding: 10px;
  margin-top: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
}


.card {
  width: 50%;
  padding: 20px;
  box-sizing: border-box;
}

.modal {
  /* 样式设置 */
}

.modal-content {
  /* 样式设置 */
}

.left-card {
  background-color: #f1f1f1;
}

.right-card {
  background-color: #e1e1e1;
}


.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}


button {
  margin-top: 20px;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  background-color: #007bff;
  color: #fff;
  cursor: pointer;
}

button:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.close-button {
  background-color: #dc3545;
}

.close-button:hover {
  background-color: #c82333;
}
</style>
