<template>
  <div class="profile-page">
    <div class="page-header">
      <h2>个人信息</h2>
    </div>

    <div class="profile-content">
      <!-- 个人信息卡片 -->
      <el-card class="profile-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>

        <el-form
          ref="profileFormRef"
          :model="profileForm"
          :rules="profileRules"
          label-width="100px"
          class="profile-form"
        >
          <!-- 头像上传 -->
          <el-form-item label="头像">
            <div class="avatar-upload">
              <div class="avatar-container">
                <el-image
                  v-if="profileForm.avatar"
                  :src="getImageUrl(profileForm.avatar)"
                  fit="cover"
                  class="avatar-preview"
                />
                <div v-else class="avatar-placeholder">
                  <el-icon><User /></el-icon>
                </div>
              </div>
              <ImageUpload
                v-model="profileForm.avatar"
                :limit="1"
                :multiple="false"
                class="avatar-uploader"
              >
                <el-button type="primary" size="small">
                  <el-icon><Upload /></el-icon>
                  更换头像
                </el-button>
              </ImageUpload>
            </div>
          </el-form-item>

          <!-- 基本信息 -->
          <el-form-item label="手机号">
            <el-input
              v-model="profileForm.phone"
              disabled
              placeholder="手机号码"
            />
          </el-form-item>

          <el-form-item label="客户姓名" prop="customer_name">
            <el-input
              v-model="profileForm.customer_name"
              placeholder="请输入客户姓名"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="真实姓名" prop="real_name">
            <el-input
              v-model="profileForm.real_name"
              placeholder="请输入真实姓名"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="公司全称" prop="company_name">
            <el-input
              v-model="profileForm.company_name"
              placeholder="请输入公司全称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="个人介绍" prop="personal_intro">
            <el-input
              v-model="profileForm.personal_intro"
              type="textarea"
              :rows="4"
              placeholder="请输入个人介绍"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="身份码">
            <el-input
              v-model="profileForm.identity_code"
              disabled
              placeholder="系统自动生成"
            />
          </el-form-item>

          <el-form-item label="推荐人身份码">
            <el-input
              v-model="profileForm.referrer_identity_code"
              disabled
              placeholder="推荐人身份码"
            />
          </el-form-item>

          <!-- 证件图片 -->
          <el-form-item label="营业执照">
            <ImageUpload
              v-model="profileForm.business_license"
              :limit="1"
              :multiple="false"
            />
          </el-form-item>

          <el-form-item label="身份证正面">
            <ImageUpload
              v-model="profileForm.id_card_front"
              :limit="1"
              :multiple="false"
            />
          </el-form-item>

          <el-form-item label="身份证反面">
            <ImageUpload
              v-model="profileForm.id_card_back"
              :limit="1"
              :multiple="false"
            />
          </el-form-item>

          <!-- 收款码 -->
          <el-form-item label="主收款码">
            <ImageUpload
              v-model="profileForm.main_payment_code"
              :limit="1"
              :multiple="false"
            />
          </el-form-item>

          <el-form-item label="副收款码">
            <ImageUpload
              v-model="profileForm.backup_payment_code"
              :limit="1"
              :multiple="false"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="submitting" @click="updateProfile">
              保存修改
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 修改密码卡片 -->
      <el-card class="password-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>修改密码</span>
          </div>
        </template>

        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
          class="password-form"
        >
          <el-form-item label="当前密码" prop="current_password">
            <el-input
              v-model="passwordForm.current_password"
              type="password"
              placeholder="请输入当前密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="新密码" prop="new_password">
            <el-input
              v-model="passwordForm.new_password"
              type="password"
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirm_password">
            <el-input
              v-model="passwordForm.confirm_password"
              type="password"
              placeholder="请确认新密码"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="passwordSubmitting" @click="updatePassword">
              修改密码
            </el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Upload } from '@element-plus/icons-vue'
import axios from 'axios'
import { useAuthStore } from '@/stores/auth'
import ImageUpload from '@/components/ImageUpload.vue'

const authStore = useAuthStore()

// 响应式数据
const submitting = ref(false)
const passwordSubmitting = ref(false)
const profileFormRef = ref()
const passwordFormRef = ref()

// 个人信息表单
const profileForm = reactive({
  phone: '',
  customer_name: '',
  real_name: '',
  avatar: '',
  company_name: '',
  personal_intro: '',
  identity_code: '',
  referrer_identity_code: '',
  business_license: '',
  id_card_front: '',
  id_card_back: '',
  main_payment_code: '',
  backup_payment_code: ''
})

// 密码修改表单
const passwordForm = reactive({
  current_password: '',
  new_password: '',
  confirm_password: ''
})

// 个人信息验证规则
const profileRules = {
  customer_name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { max: 50, message: '客户姓名不能超过50个字符', trigger: 'blur' }
  ],
  real_name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { max: 50, message: '真实姓名不能超过50个字符', trigger: 'blur' }
  ],
  company_name: [
    { max: 100, message: '公司名称不能超过100个字符', trigger: 'blur' }
  ],
  personal_intro: [
    { max: 500, message: '个人介绍不能超过500个字符', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  current_password: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' },
    { max: 20, message: '密码长度不能超过20个字符', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.new_password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取当前用户信息
const getCurrentUser = async () => {
  try {
    const response = await axios.get('/current-user')
    
    if (response.data.success) {
      const userData = response.data.data
      Object.assign(profileForm, {
        phone: userData.phone || '',
        customer_name: userData.customer_name || '',
        real_name: userData.real_name || '',
        avatar: userData.avatar || '',
        company_name: userData.company_name || '',
        personal_intro: userData.personal_intro || '',
        identity_code: userData.identity_code || '',
        referrer_identity_code: userData.referrer_identity_code || '',
        business_license: userData.business_license_image || '',
        id_card_front: userData.id_card_front_image || '',
        id_card_back: userData.id_card_back_image || '',
        main_payment_code: userData.main_payment_qr_image || '',
        backup_payment_code: userData.sub_payment_qr_image || ''
      })
    }
  } catch (error) {
    console.error('获取用户信息失败：', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 获取图片完整URL
const getImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `${window.location.origin}${url}`
}

// 更新个人信息
const updateProfile = async () => {
  if (!profileFormRef.value) return
  
  const valid = await profileFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  submitting.value = true
  
  try {
    const response = await axios.put('/update-profile', {
      customer_name: profileForm.customer_name,
      real_name: profileForm.real_name,
      avatar: profileForm.avatar,
      company_name: profileForm.company_name,
      personal_intro: profileForm.personal_intro,
      business_license: profileForm.business_license,
      id_card_front: profileForm.id_card_front,
      id_card_back: profileForm.id_card_back,
      main_payment_code: profileForm.main_payment_code,
      backup_payment_code: profileForm.backup_payment_code
    })
    
    if (response.data.success) {
      ElMessage.success('个人信息更新成功')
      // 更新全局用户信息
      authStore.updateUserInfo(response.data.data)
    }
  } catch (error) {
    console.error('更新个人信息失败：', error)
    ElMessage.error('更新个人信息失败')
  } finally {
    submitting.value = false
  }
}

// 修改密码
const updatePassword = async () => {
  if (!passwordFormRef.value) return
  
  const valid = await passwordFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  passwordSubmitting.value = true
  
  try {
    const response = await axios.put('/change-password', {
      current_password: passwordForm.current_password,
      new_password: passwordForm.new_password
    })
    
    if (response.data.success) {
      ElMessage.success('密码修改成功')
      resetPasswordForm()
      
      // 提醒用户重新登录
      await ElMessageBox.confirm(
        '密码已修改成功，为了安全起见，请重新登录。',
        '提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '稍后再说',
          type: 'success'
        }
      )
      
      // 退出登录
      authStore.logout()
    }
  } catch (error) {
    console.error('修改密码失败：', error)
    const message = error.response?.data?.message || '修改密码失败'
    ElMessage.error(message)
  } finally {
    passwordSubmitting.value = false
  }
}

// 重置密码表单
const resetPasswordForm = () => {
  Object.assign(passwordForm, {
    current_password: '',
    new_password: '',
    confirm_password: ''
  })
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}

// 组件挂载后获取用户信息
onMounted(() => {
  getCurrentUser()
})
</script>

<style scoped>
.profile-page {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.profile-card,
.password-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: 600;
  color: #303133;
}

.profile-form,
.password-form {
  max-width: 600px;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-container {
  position: relative;
}

.avatar-preview {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 2px solid #e4e7ed;
}

.avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 2px dashed #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  color: #c0c4cc;
  font-size: 24px;
}

.avatar-uploader {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-form,
  .password-form {
    max-width: 100%;
  }
  
  .avatar-upload {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>