<template>
  <div class="wraper" v-loading="loading">
    <div v-if="!loading" class="card-content">
      <el-row class="input-group" align="middle" :gutter="20">
        <el-col :span="6" class="input-label">手机号</el-col>
        <el-col :span="12" class="input-value">{{ securityData.phone }}</el-col>
        <el-col :span="6" class="action">
          <span v-if="securityData.phone">
            <el-button type="text" @click="openDialog('phone', 'unbind')">
              解绑
            </el-button>
            <el-button type="text" @click="openDialog('phone', 'change')">
              换绑
            </el-button>
          </span>
          <span v-else>
            <el-button
              type="text"
              style="color: orange"
              @click="openDialog('phone', 'bind')">
              绑定手机号
            </el-button>
          </span>
        </el-col>
      </el-row>
      <el-divider />
      <el-row class="input-group" align="middle" :gutter="20">
        <el-col :span="6" class="input-label">邮箱</el-col>
        <el-col :span="12" class="input-value">
          {{ securityData.mailbox }}
        </el-col>
        <el-col :span="6" class="action">
          <span v-if="securityData.mailbox">
            <el-button type="text" @click="openDialog('mailbox', 'unbind')">
              解绑
            </el-button>
            <el-button type="text" @click="openDialog('mailbox', 'change')">
              换绑
            </el-button>
          </span>
          <span v-else>
            <el-button
              type="text"
              style="color: orange"
              @click="openDialog('mailbox', 'bind')">
              绑定邮箱
            </el-button>
          </span>
        </el-col>
      </el-row>
      <el-divider />
      <el-row class="input-group" align="middle" :gutter="20">
        <el-col :span="6" class="input-label">超级密码</el-col>
        <el-col :span="12" class="input-value">
          {{ securityData.superPassword ? '******' : '' }}
        </el-col>
        <el-col :span="6" class="action">
          <span v-if="securityData.superPassword">
            <el-button
              type="text"
              @click="openDialog('superPassword', 'password')">
              修改超级密码
            </el-button>
          </span>
          <span v-else>
            <el-button
              type="text"
              style="color: orange"
              @click="handleAddSuperPassword">
              设置超级密码
            </el-button>
          </span>
        </el-col>
      </el-row>
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="400px"
      class="dialog"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      @close="resetForm">
      <el-form
        :model="dialogForm"
        :rules="dialogRules"
        ref="dialogForm"
        :label-width="
          dialogType === 'password' || dialogType === 'addPassword'
            ? '110px'
            : '80px'
        ">
        <el-form-item
          v-if="currentMethod === 'phone'"
          label="手机号"
          prop="phone">
          <el-input
            v-model="dialogForm.phone"
            placeholder="请输入手机号"
            :disabled="dialogType !== 'bind'"
            clearable
            maxlength="11"
            size="small" />
        </el-form-item>
        <el-form-item
          v-if="currentMethod === 'mailbox'"
          label="邮箱"
          prop="mailbox">
          <el-input
            v-model="dialogForm.mailbox"
            placeholder="请输入邮箱"
            :disabled="dialogType !== 'bind'"
            clearable
            size="small" />
        </el-form-item>
        <el-form-item
          v-if="currentMethod !== 'superPassword'"
          label="验证码"
          prop="code">
          <div style="display: flex; align-items: center; gap: 10px">
            <el-input
              v-model="dialogForm.code"
              placeholder="请输入验证码"
              clearable
              maxlength="6"
              size="small" />
            <el-button
              size="small"
              @click="sendVerificationCode"
              :loading="countdownConfig[currentMethod]?.loading">
              {{
                countdownConfig[currentMethod]?.loading
                  ? `${countdownConfig[currentMethod].countdown}s后重发`
                  : '发送验证码'
              }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item
          v-if="
            (dialogType === 'password' && currentMethod === 'superPassword') ||
            currentMethod === 'superPassword'
          "
          :label="dialogType === 'password' ? '原超级密码' : '超级密码'"
          prop="superPassword">
          <el-input
            v-model="dialogForm.superPassword"
            :placeholder="
              dialogType === 'password' ? '请输入原超级密码' : '请输入超级密码'
            "
            clearable
            show-password
            size="small" />
        </el-form-item>
        <el-form-item
          v-if="dialogType === 'password' || dialogType === 'addPassword'"
          label="新超级密码"
          prop="newSuperPassword1">
          <el-input
            v-model="dialogForm.newSuperPassword1"
            placeholder="请输入新超级密码"
            clearable
            show-password
            size="small" />
        </el-form-item>
        <el-form-item
          v-if="dialogType === 'password' || dialogType === 'addPassword'"
          label="确认超级密码"
          prop="newSuperPassword2">
          <el-input
            v-model="dialogForm.newSuperPassword2"
            placeholder="请再次输入新超级密码"
            clearable
            show-password
            size="small" />
        </el-form-item>
      </el-form>
      <el-divider v-if="dialogType !== 'bind'">其他验证方式</el-divider>
      <div v-if="dialogType !== 'bind'" class="check">
        <el-button
          icon="el-icon-mobile-phone"
          type="warning"
          size="small"
          v-if="currentMethod !== 'phone' && securityData.phone"
          @click="currentMethod = 'phone'"
          style="width: 100%">
          手机验证
        </el-button>
        <el-button
          icon="el-icon-message"
          type="success"
          size="small"
          v-if="currentMethod !== 'mailbox' && securityData.mailbox"
          @click="currentMethod = 'mailbox'"
          style="width: 100%">
          邮箱验证
        </el-button>
        <el-button
          icon="el-icon-lock"
          type="info"
          size="small"
          v-if="
            currentMethod !== 'superPassword' &&
            dialogType !== 'addPassword' &&
            securityData.superPassword
          "
          @click="currentMethod = 'superPassword'"
          style="width: 100%">
          超级密码验证
        </el-button>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取消</el-button>
        <el-button type="primary" @click="handleSubmit" size="small">
          {{ dialogType === 'change' ? '下一步' : '确定' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from '../../common/api/axios'

export default {
  name: 'sysSecuritySettings',
  data() {
    return {
      securityData: { phone: '', mailbox: '', superPassword: '' },
      loading: true,
      dialogVisible: false,
      currentTarget: '',
      currentMethod: '',
      dialogType: '',
      dialogForm: {
        phone: '',
        mailbox: '',
        code: '',
        superPassword: '',
        newSuperPassword1: '',
        newSuperPassword2: ''
      },
      countdownConfig: {
        phone: { countdown: 0, loading: false, timer: null },
        mailbox: { countdown: 0, loading: false, timer: null }
      },
      methodMap: {
        phone: { name: '手机号', method: '手机' },
        mailbox: { name: '邮箱', method: '邮箱' },
        superPassword: { name: '超级密码', method: '超级密码' }
      },
      dialogRules: {}
    }
  },
  computed: {
    dialogTitle() {
      if (
        this.dialogType === 'change' &&
        this.currentTarget === 'superPassword'
      ) {
        return '身份验证'
      }
      const targetName = this.methodMap[this.currentTarget]?.name || '超级密码'
      const actionMap = {
        bind: this.securityData[this.currentTarget]
          ? `绑定新安全${targetName}`
          : `绑定安全${targetName}`,
        unbind: `解绑安全${targetName}`,
        change: `验证原安全${targetName}`,
        password: '修改超级密码',
        addPassword: '新增超级密码'
      }
      return actionMap[this.dialogType] || '操作'
    }
  },
  mounted() {
    this.getList()
  },
  watch: {
    currentMethod() {
      this.$nextTick(() => this.$refs.dialogForm?.clearValidate())
    }
  },
  methods: {
    validateNewPassword(rule, value, callback) {
      if (value !== this.dialogForm.newSuperPassword1) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
    async getList() {
      this.loading = true
      try {
        const res = await axios.post('sysSecuritySettings/list_page', {
          pageSize: 100,
          currentPage: 1
        })
        if (res.code === 200 && res.data.records?.length > 0) {
          this.securityData = { ...res.data.records[0] }
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    handleAddSuperPassword() {
      const verificationMethod =
        this.securityData.phone || this.securityData.mailbox
      if (!verificationMethod) {
        this.$message.warning('请先绑定手机或邮箱，才能进行此操作')
        return
      }
      this.openDialog(verificationMethod, 'addPassword')
    },
    openDialog(method, type, targetOverride = null) {
      this.currentMethod =
        type === 'addPassword'
          ? this.securityData.phone
            ? 'phone'
            : 'mailbox'
          : method
      this.currentTarget = targetOverride || method
      this.dialogType = type
      this.dialogForm = {
        phone: type === 'bind' ? '' : this.securityData.phone || '',
        mailbox: type === 'bind' ? '' : this.securityData.mailbox || '',
        code: '',
        superPassword: '',
        newSuperPassword1: '',
        newSuperPassword2: ''
      }
      this.dialogRules = this.getDialogRules(this.currentMethod, type)
      this.dialogVisible = true

      this.$nextTick(() => this.$refs.dialogForm?.clearValidate())
    },
    getDialogRules(method, type) {
      if (type === 'addPassword') {
        return {
          code: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
            {
              pattern: /^[0-9]{6}$/,
              message: '请输入6位数字验证码',
              trigger: 'blur'
            }
          ],
          newSuperPassword1: [
            { required: true, message: '请输入新超级密码', trigger: 'blur' }
          ],
          newSuperPassword2: [
            {
              required: true,
              message: '请再次输入新超级密码',
              trigger: 'blur'
            },
            { validator: this.validateNewPassword, trigger: 'blur' }
          ]
        }
      }
      const rules = {
        phone:
          type === 'bind' && method === 'phone'
            ? [
                { required: true, message: '请输入手机号', trigger: 'blur' },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入正确的手机号',
                  trigger: 'blur'
                }
              ]
            : [],
        mailbox:
          type === 'bind' && method === 'mailbox'
            ? [
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                {
                  pattern:
                    /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.(com|cn|net|org|edu|gov|io)$/,
                  message: '请输入正确的邮箱',
                  trigger: 'blur'
                }
              ]
            : [],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          {
            pattern: /^[0-9]{6}$/,
            message: '请输入6位数字验证码',
            trigger: 'blur'
          }
        ],
        superPassword: [
          {
            required: true,
            message: `请输入${type === 'password' ? '原超级密码' : '超级密码'}`,
            trigger: 'blur'
          }
        ],
        newSuperPassword1: [
          { required: true, message: '请输入新超级密码', trigger: 'blur' }
        ],
        newSuperPassword2: [
          {
            required: true,
            message: '请再次输入新超级密码',
            trigger: 'blur'
          },
          { validator: this.validateNewPassword, trigger: 'blur' }
        ]
      }
      return rules
    },
    async sendVerificationCode() {
      this.$refs.dialogForm.validateField(this.currentMethod, async (error) => {
        if (error) return
        const config = this.countdownConfig[this.currentMethod]
        if (!config) return
        if (config.timer) clearTimeout(config.timer)
        config.loading = true
        config.countdown = 60
        const countdownFn = () => {
          if (config.countdown > 0) {
            config.countdown--
            config.timer = setTimeout(countdownFn, 1000)
          } else {
            config.loading = false
            config.timer = null
          }
        }
        countdownFn()
        try {
          const url =
            this.currentMethod === 'phone'
              ? '/sysSecuritySettings/sendPhoneCode'
              : `/sysSecuritySettings/sendEmailCode?email=${this.dialogForm.mailbox}&operateType=${this.dialogTitle}`
          const res = await axios({
            method: this.currentMethod === 'phone' ? 'post' : 'get',
            url,
            data:
              this.currentMethod === 'phone'
                ? {
                    phone: this.dialogForm.phone,
                    operateType: this.dialogTitle
                  }
                : null
          })
          if (res.code !== 200) throw new Error('发送失败')
          this.$message.success('验证码发送成功')
        } catch (error) {
          config.loading = false
          config.countdown = 0
          if (config.timer) clearTimeout(config.timer)
          config.timer = null
          this.$message.error('验证码发送失败')
        }
      })
    },
    async handleSubmit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (!valid) return
        try {
          const actionConfig = {
            bind: {
              url: '/sysSecuritySettings/changeBinding',
              message: '绑定成功'
            },
            unbind: { url: '/sysSecuritySettings/unbind', message: '解绑成功' },
            change: { url: '/sysSecuritySettings/check', message: '验证成功' },
            password: {
              url: '/sysSecuritySettings/updatePassword',
              message: '超级密码修改成功'
            },
            addPassword: {
              url: '/sysSecuritySettings/updatePassword',
              message: '超级密码修改成功'
            }
          }
          const { url, message } = actionConfig[this.dialogType]
          const filteredForm = Object.fromEntries(
            Object.entries(this.dialogForm).filter(([, v]) => v)
          )
          const res = await axios.post(url, {
            ...filteredForm,
            checkType: this.currentMethod,
            unbindType: this.currentTarget,
            operateType: this.dialogTitle
          })
          if (res.code !== 200) throw new Error('操作失败')
          this.$message.success(message)
          if (this.dialogType !== 'change') this.getList()
          this.dialogVisible = false
          if (this.dialogType === 'change') {
            this.openDialog(this.currentTarget, 'bind')
          }
        } catch (error) {
          this.$message.error('操作失败')
        }
      })
    },
    resetForm() {
      this.$refs.dialogForm?.resetFields()
      this.dialogForm = {
        phone: '',
        mailbox: '',
        code: '',
        superPassword: '',
        newSuperPassword1: '',
        newSuperPassword2: ''
      }
    }
  }
}
</script>

<style scoped>
.wraper {
  background: #fff;
  display: flex;
  flex-direction: column;
  height: 100%;
  align-items: center;
  padding: 10px;
}
.input-group {
  margin: 10px 0;
  display: flex;
  align-items: center;
}
.input-label {
  text-align: left;
  color: #494747;
  font-weight: 500;
}
.input-value {
  text-align: right;
  color: #333;
  word-break: break-all;
}
.action {
  text-align: right;
}
.card-content {
  width: 600px;
  flex: 1;
  display: flex;
  flex-direction: column;
  margin: 100px 0 400px 0;
  border: 1px solid rgb(235, 232, 232);
  padding: 60px;
  border-radius: 30px;
  box-shadow: 0 8px 24px 0 rgba(0, 0, 0, 0.12),
    0 1.5px 6px 0 rgba(0, 0, 0, 0.08);
}
.el-divider {
  background-color: #dcdfe6c2;
}
.card-content .el-divider--horizontal {
  margin: 5px;
}
.el-dialog {
  padding: 20px 15px 20px 10px;
  border-radius: 5px;
}
.dialog .el-divider--horizontal {
  margin-top: 30px;
  width: 80%;
  margin-left: auto;
  margin-right: auto;
}
.dialog .el-divider__text {
  color: #8b8a8a;
}
.dialog-footer {
  margin-top: 10px;
}
.check {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  width: 80%;
  margin: 0 auto;
}
.check .el-button + .el-button {
  margin-left: 0;
}
</style>
