<!-- src/components/AccountSecurity.vue -->
<template>
  <div class="account-security">
    <h2>账号安全</h2>
    <div v-for="(item, index) in securityItems" :key="index" class="security-item">
      <div class="item-header">
        <span class="title">{{ item.title }}</span>
        <div v-if="item.title == '登录密码'">
          <button class="action-btn" :class="`color-${getActionColor(item.status)}`" @click="item.actionHandler">
            {{ item.actionText }}
          </button>
        </div>
        <div class="status" v-if="item.title !== '登录密码'">
          <component :is="getStatusIcon(item.status)" v-if="getStatusIcon(item.status)"
            :class="['icon', `color-${getStatusColor(item.status)}`]" />
          <span :class="['text', `color-${getStatusColor(item.status)}`]">
            {{ item.status === 'bound' ? '已绑定' : item.status === 'unverified' ? '未认证' : '未设置' }}
          </span>
          <span class="divider">|</span>
          <button class="action-btn" :class="`color-${getActionColor(item.status)}`" @click="item.actionHandler">
            {{ item.actionText }}
          </button>
        </div>
      </div>
      <p class="description">{{ item.description }}</p>
    </div>

    <!-- 设置密码弹窗 -->
    <a-modal v-model:visible="setPasswordModalVisible" title="设置密码" width="500px" :footer="null"
      @cancel="closeSetPasswordModal">
      <div style="padding: 24px 0;">
        <div style="margin-bottom: 24px; font-size: 16px; color: #333;">
          手机号：<span>{{ userPhone }}</span>
        </div>

        <div style="margin-bottom: 16px; display: flex; align-items: center; gap: 8px;">
          <span style="color: red;">*</span>
          <label style="font-size: 14px; color: #333;">手机验证码：</label>
          <a-input v-model:value="passwordForm.smsCode" placeholder="请输入验证码" style="flex: 1;" />
          <a-button type="primary" :disabled="isSending || countdown > 0" @click="sendSmsCode('password')"
            style="width: 120px;">
            {{ isSending || countdown > 0 ? `${countdown}s后重发` : '发送验证码' }}
          </a-button>
        </div>

        <div style="margin-bottom: 16px; display: flex; align-items: center; gap: 8px;">
          <span style="color: red;">*</span>
          <label style="font-size: 14px; color: #333;">设置新密码：</label>
          <a-input v-model:value="passwordForm.newPassword" placeholder="请输入8～16位包含数字和字母的密码" type="password"
            style="flex: 1;" />
        </div>

        <div style="margin-bottom: 16px; display: flex; align-items: center; gap: 8px;">
          <span style="color: red;">*</span>
          <label style="font-size: 14px; color: #333;">确认新密码：</label>
          <a-input v-model:value="passwordForm.confirmPassword" placeholder="请确认密码" type="password" style="flex: 1;" />
        </div>
      </div>

      <div style="text-align: right; padding: 16px 24px;">
        <a-button @click="closeSetPasswordModal" style="margin-right: 8px;">取消</a-button>
        <a-button type="primary" @click="savePassword">保存</a-button>
      </div>
    </a-modal>

    <!-- 修改手机号弹窗 -->
    <a-modal v-model:visible="editPhoneModalVisible" title="修改手机号" width="500px" :footer="null"
      @cancel="closeEditPhoneModal">
      <div style="padding: 24px 0;">
        <div style="margin-bottom: 24px; display: flex; align-items: center; gap: 8px;">
          <span style="color: red;">*</span>
          <label style="font-size: 14px; color: #333;">输入新手机号：</label>
          <a-select v-model:value="phoneForm.countryCode" style="width: 80px;" placeholder="+86">
            <a-select-option value="+86">+86</a-select-option>
            <a-select-option value="+852">+852</a-select-option>
            <a-select-option value="+853">+853</a-select-option>
          </a-select>
          <a-input v-model:value="phoneForm.newPhoneNumber" placeholder="请输入新手机号" style="flex: 1;" />
        </div>

        <div style="margin-bottom: 16px; display: flex; align-items: center; gap: 8px;">
          <span style="color: red;">*</span>
          <label style="font-size: 14px; color: #333;">手机验证码：</label>
          <a-input v-model:value="phoneForm.smsCode" placeholder="请输入验证码" style="flex: 1;" />
          <a-button type="primary" :disabled="isSending || countdown > 0" @click="sendSmsCode('phone')"
            style="width: 120px;">
            {{ isSending || countdown > 0 ? `${countdown}s后重发` : '发送验证码' }}
          </a-button>
        </div>

        <div style="margin-bottom: 16px; display: flex; align-items: center; gap: 8px;">
          <span style="color: red;">*</span>
          <label style="font-size: 14px; color: #333;">输入账号密码：</label>
          <a-input v-model:value="phoneForm.password" placeholder="请输入账号登录密码" type="password" style="flex: 1;" />
        </div>
      </div>

      <div style="text-align: right; padding: 16px 24px;">
        <a-button @click="closeEditPhoneModal" style="margin-right: 8px;">取消</a-button>
        <a-button type="primary" @click="savePhone">确定</a-button>
      </div>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onBeforeMount, computed } from 'vue';
import {
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  CloseOutlined,
  SaveOutlined,
} from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
// 在 <script setup> 中引入 router
import { useRouter } from 'vue-router';
import { updatePassword, updatePhoneNumber } from '@/apis/modules/login';

const router = useRouter();
const userPhone = ref('')
onBeforeMount(() => {
  // 模拟获取用户手机号
  console.log(1111)
  userPhone.value = JSON.parse(localStorage.getItem('userInfo') || '{}').phone
})
const getStatusIcon = (status: SecurityItem['status']) => {
  switch (status) {
    case 'bound':
      return CheckCircleOutlined;
    case 'unverified':
    case 'unset':
      return ExclamationCircleOutlined;
    default:
      return null;
  }
};

const getStatusColor = (status: SecurityItem['status']) => {
  switch (status) {
    case 'bound':
      return 'green';
    case 'unverified':
    case 'unset':
      return 'red';
    default:
      return 'gray';
  }
};

const getActionColor = (status: SecurityItem['status']) => {
  return 'blue'; // 统一蓝色即可
};


// 安全项接口
interface SecurityItem {
  title: string;
  description: string;
  status?: 'unset' | 'bound' | 'unverified' | 'verified';
  actionText?: string;
  actionHandler: () => void;
}
const securityItems = computed<SecurityItem[]>(() => [
  {
    title: '登录密码',
    description: '安全性高的密码可以使账号更安全。建议您定期更换密码，设置一个包含字母和数字且长度超过8位的密码',
    status: 'bound',
    actionText: '修改密码',
    actionHandler: () => openSetPasswordModal(),
  },
  {
    title: '手机号',
    description: userPhone.value ? '您已绑定了手机178****5075您的手机号可以直接用于登录、找回密码等' : '未绑定手机',
    status: userPhone.value ? 'bound' : 'unset',
    actionText: userPhone.value ? '修改手机号' : '绑定手机号',
    actionHandler: () => openEditPhoneModal(),
  },
  {
    title: '实名认证',
    description: '实名认证后可以使用AutoDL更完整的功能，如打开实例的自定义服务等',
    status: 'unverified',
    actionText: '立即认证',
    actionHandler: () => {
      router.push('/layout/admin/realnameAuth');
    },
  },
]);
// const securityItems = ref<SecurityItem[]>([
//   {
//     title: '登录密码',
//     description: '安全性高的密码可以使账号更安全。建议您定期更换密码，设置一个包含字母和数字且长度超过8位的密码',
//     status: 'bound',
//     actionText: '修改密码',
//     actionHandler: () => openSetPasswordModal(),
//   },
//   {
//     title: '手机号',
//     description: userPhone.value?'您已绑定了手机178****5075您的手机号可以直接用于登录、找回密码等':'未绑定手机',
//     status: userPhone.value?'bound':'unset',
//     actionText: userPhone.value?'修改手机号':'绑定手机号',
//     actionHandler: () => openEditPhoneModal(),
//   },
//   {
//     title: '实名认证',
//     description: '实名认证后可以使用AutoDL更完整的功能，如打开实例的自定义服务等',
//     status: 'unverified',
//     actionText: '立即认证',
//     actionHandler: () => {
//       router.push('/layout/admin/realnameAuth');
//     },
//   },

// ]);

// 设置密码弹窗
const setPasswordModalVisible = ref(false);
const editPhoneModalVisible = ref(false);
// 新增：用于控制实名认证弹窗
const realNameModalVisible = ref(false);

// 打开实名认证弹窗
const openRealNameAuthModal = () => {
  realNameModalVisible.value = true;
};

// 关闭实名认证弹窗
const closeRealNameAuthModal = () => {
  realNameModalVisible.value = false;
};

// 表单数据
const passwordForm = reactive({
  phone: userPhone.value,
  smsCode: '',
  newPassword: '',
  confirmPassword: '',
});

const phoneForm = reactive({
  countryCode: '+86',
  newPhoneNumber: '',
  smsCode: '',
  password: '', // 登录密码
});

// 验证码倒计时
const countdown = ref(0);
const isSending = ref(false);

// 发送验证码
const sendSmsCode = (formType: 'password' | 'phone') => {
  if (isSending.value) return;
  isSending.value = true;
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      isSending.value = false;
      countdown.value = 0;
    }
  }, 1000);
  message.success('验证码已发送');
};

// 打开设置密码弹窗
const openSetPasswordModal = () => {
  resetPasswordForm();
  setPasswordModalVisible.value = true;
};

// 打开修改手机号弹窗
const openEditPhoneModal = () => {
  resetPhoneForm();
  editPhoneModalVisible.value = true;
};

// 关闭弹窗
const closeSetPasswordModal = () => {
  setPasswordModalVisible.value = false;
  resetPasswordForm();
};

const closeEditPhoneModal = () => {
  editPhoneModalVisible.value = false;
  resetPhoneForm();
};

// 重置表单
const resetPasswordForm = () => {
  passwordForm.smsCode = '';
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';
  countdown.value = 0;
  isSending.value = false;
};

const resetPhoneForm = () => {
  phoneForm.countryCode = '+86';
  phoneForm.newPhoneNumber = '';
  phoneForm.smsCode = '';
  phoneForm.password = '';
  countdown.value = 0;
  isSending.value = false;
};



// 保存密码
const savePassword = async () => {
  if (!passwordForm.smsCode) {
    message.error('请输入验证码');
    return;
  }
  if (!passwordForm.newPassword) {
    message.error('请输入新密码');
    return;
  }
  if (!passwordForm.confirmPassword) {
    message.error('请确认密码');
    return;
  }
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    message.error('两次输入的密码不一致');
    return;
  }
  if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/.test(passwordForm.newPassword)) {
    message.error('密码必须为8~16位，且包含字母和数字');
    return;
  }
  try {
    const passwordData = {
      phone: userPhone.value,
      code: passwordForm.smsCode,
      confirmPassword: passwordForm.confirmPassword,
      newPassword: passwordForm.newPassword
    };
    const res = await updatePassword(passwordData);
    message.success('密码设置成功！');
    setTimeout(() => {
      localStorage.clear();
      router.replace('/login');
    }, 1500);
    closeSetPasswordModal();
  } catch (error: any) {
    message.error(error);
  }

};

// 保存手机号
const savePhone = async () => {
  if (!phoneForm.newPhoneNumber) {
    message.error('请输入新手机号');
    return;
  }
  if (!/^\d{11}$/.test(phoneForm.newPhoneNumber)) {
    message.error('请输入有效的11位手机号');
    return;
  }
  if (!phoneForm.smsCode) {
    message.error('请输入验证码');
    return;
  }
  if (!phoneForm.password) {
    message.error('请输入账号登录密码');
    return;
  }
  try {
    const phoneData = {
      newPhone: phoneForm.newPhoneNumber,
      code: phoneForm.smsCode,
      Password: phoneForm.password
    };
    await updatePhoneNumber(phoneData);
    message.success('手机号修改成功！');
    closeEditPhoneModal();
    setTimeout(() => {
      localStorage.clear();
      router.replace('/login');
    }, 1500);
  } catch (error: any) {
    message.error(error);
  }
};
</script>
<style scoped>
.account-security {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  padding: 20px;
  background-color: #f9f9f9;
}

.account-security h2 {
  margin-top: 0;
  color: #333;
  font-size: 1.4em;
}

.security-item {
  border: 1px solid #ddd;
  border-radius: 6px;
  margin-bottom: 16px;
  padding: 16px;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.title {
  font-weight: bold;
  color: #333;
}

.status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.icon {
  font-size: 16px;
  line-height: 1;
}

.text {
  font-size: 14px;
  font-weight: normal;
}

.divider {
  color: #ccc;
  font-size: 14px;
}

.action-btn {
  background: none;
  border: none;
  color: #0066cc;
  cursor: pointer;
  font-size: 14px;
  padding: 0;
  margin-left: 8px;
  text-decoration: underline;
}

.action-btn:hover {
  text-decoration: none;
}

.color-green {
  color: #52c41a !important;
}

.color-red {
  color: #ff4d4f !important;
}

.color-blue {
  color: #0066cc !important;
}

.description {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}
</style>