<template>
    <div class="main">
        <img src="@/assets/images/login_back.png" alt="" class="back-image">
        <div class="login-box">
            <img class="logo" src="@/assets/images/logo.png" alt="" />
            <div class="change-bar">
                <div class="checked">用户名登录</div>
                <div style="margin-left: 32px; margin-right: 32px; color: #C4C4C4">|</div>
                <div>验证码登录</div>
            </div>
            <div class="ipt">
                <img src="@/assets/images/login_user.png" alt="" />
                <input v-model="username" placeholder="请输入用户名">
            </div>
            <div class="ipt">
                <img src="@/assets/images/login_lock.png" alt="" />
                <input v-model="password" type="password" placeholder="请输入密码">
            </div>
            <el-button class="btn" type="primary" @click="login">登录</el-button>
        </div>

        <!-- 强制修改密码 -->
        <el-dialog title="修改密码" v-model="passwordOpen" width="680px" append-to-body>
            <el-form ref="userRef" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="用户名" prop="username">
                            <el-input
                                v-model="form.username"
                                placeholder="请输入用户名"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="原密码" prop="oldPassword">
                            <el-input
                                v-model="form.oldPassword"
                                type="password"
                                placeholder="请输入原密码"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="新密码" prop="newPassword">
                            <el-input
                                v-model="form.newPassword"
                                type="password"
                                placeholder="请输入新密码"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="确认密码" prop="confirmPassword">
                            <el-input
                                v-model="form.confirmPassword"
                                placeholder="请再次确认密码"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 强制验证手机号 -->
        <el-dialog title="手机号验证" v-model="phoneOpen" width="680px" append-to-body>
            <el-form ref="phoneRef" :model="mobileForm" :rules="mobileRules" label-width="100px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="手机号" prop="mobileNumber">
                            <el-input
                                v-model="mobileForm.mobileNumber"
                                placeholder="请输入手机号"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="验证码" prop="verificationCode">
                            <el-input v-model="mobileForm.verificationCode" placeholder="请输入验证码" class="input-with-select">
                                <template #append>
                                    <el-button :disabled="countdown > 0" @click="sendVerificationCode">
                                        {{ countdown > 0 ? countdown + '秒后重新获取' : '获取验证码' }}
                                    </el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitPhoneForm">确 定</el-button>
                    <el-button @click="phoneCancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { useUserStore } from '@/store/user.js'
import { passwordChange, sendSmsCode, userUnlock } from '@/api/login'
import CryptoJS from 'crypto-js'
// const route = useRoute()
const router = useRouter()
const passwordOpen = ref(false)
const phoneOpen = ref(false)
// admin Qdport@2023! api  | admin  123456 old
const username = ref('')
const password = ref('')
const { proxy } = getCurrentInstance()
const countdown = ref(0) // 倒计时秒数

const form = ref({
    username: null,
    oldPassword: null,
    newPassword: null,
    confirmPassword: null
})
const mobileForm = ref({
    mobileNumber: null,
    verificationCode: null
})
const mobileRules = ref({
    mobileNumber: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
    verificationCode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
})
const rules = ref({
    username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
    oldPassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
    newPassword: [
        { required: true, message: '新密码不能为空', trigger: 'blur' },
        {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
            message: '新密码必须至少8位，且必须包含大小写字母、数字和特殊符号',
            trigger: 'blur'
        }
    ],
    confirmPassword: [
        { required: true, message: '请在此输入新密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== form.value.newPassword) {
                    console.log(value, form.value.newPassword, 'Lingci')
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
})

const login = () => {
    useUserStore()
        .login({
            username: username.value,
            password: password.value
        })
        .then(() => {
            router.push('/')
        }).catch((code) => {
            console.log('错误进来了', code)
            if (code === 204) {
                console.log('强制修改密码')
                password.value = ''
                passwordOpen.value = true
            } else if (code === 203) {
                password.value = ''
                phoneOpen.value = true
            }
        })
}

function submitForm() {
    proxy.$refs['userRef'].validate(valid => {
        if (valid) {
            passwordChange({
                userName: form.value.username,
                oldPassword: CryptoJS.MD5(form.value.oldPassword).toString(),
                newPassword: CryptoJS.MD5(form.value.newPassword).toString(),
                enterPassword: CryptoJS.MD5(form.value.confirmPassword).toString()
            }).then(res => {
                if (res.success) {
                    ElMessage({
                        message: '修改成功，请重新登录！',
                        type: 'success'
                    })
                    passwordOpen.value = false
                }
            })
        } else {
            console.log('检验不通过')
        }
    })
}

function cancel() {
    passwordOpen.value = false
    form.value = {
        username: null,
        oldPassword: null,
        newPassword: null,
        confirmPassword: null
    }
}

function sendVerificationCode() {
    // 这里实现发送验证码的逻辑
    if (!mobileForm.value.mobileNumber) return
    sendSmsCode({ mobile: mobileForm.value.mobileNumber }).then((res) => {
        if (res.success) {
            ElMessage({
                message: '验证码发生成功！',
                type: 'success'
            })
            // 发送成功后开始倒计时
            countdown.value = 60
            let interval = setInterval(() => {
                countdown.value--
                if (countdown.value <= 0) {
                    clearInterval(interval)
                }
            }, 1000)
        }
    })
}

function submitPhoneForm() {
    proxy.$refs['phoneRef'].validate(valid => {
        if (valid) {
            userUnlock({ mobile: mobileForm.value.mobileNumber, code: mobileForm.value.verificationCode }).then((res) => {
                if (res.success) {
                    ElMessage({
                        message: '校验成功，请重新登录',
                        type: 'success'
                    })
                    phoneOpen.value = false
                }
            })
        } else {
            console.log('校验不通过')
        }
    })
}

function phoneCancel() {
    phoneOpen.value = false
    mobileForm.value = {
        mobileNumber: null,
        verificationCode: null
    }
}
</script>

<style lang="scss" scoped>
.main {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  .back-image {
    height: 100%;
    width: 100%;
    z-index: -1;
    position: absolute;
    top: 0;
    left: 0;
  }

  .login-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .change-bar {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 16px;
      margin-bottom: 24px;

      .checked {
        color: #164497;
      }
    }

    .logo {
      width: 300px;
      height: 70px;
      margin-bottom: 64px;
    }

    .ipt {
      width: 470px;
      height: 60px;
      margin-top: 20px;
      background-color: white;
      border-radius: 58px;
      text-align: center;
      position: relative;

      img {
        position: absolute;
        left: 30px;
        top: 20px;
        width: 18px;
        height: 21px;
      }

      input {
        border: none;
        text-align: center;
        width: 80%;
        height: 100%;
        font-size: 18px;
      }

      input:focus {
        outline: none;
      }
    }

    .btn {
      width: 187px;
      height: 51px;
      background: #164497;
      border-radius: 10px 10px 10px 10px;
      opacity: 1;
      margin-top: 45px;
    }
  }
}
</style>
