<template>
  <view class="tenant-detail-page">
    <view class="custom-nav safe-area-top">
      <view class="nav-content">
        <view class="nav-btn" @click="goBack">
          <uni-icons type="left" size="22" color="#1E293B"></uni-icons>
        </view>
        <text class="nav-title">租客详情</text>
        <view class="nav-btn" @click="editTenant">
          <uni-icons type="compose" size="22" color="#2563EB"></uni-icons>
        </view>
      </view>
    </view>

    <scroll-view scroll-y class="detail-content" v-if="tenant.id">
      <view class="tenant-header">
        <view class="tenant-avatar">
          <text>{{tenant.name.charAt(0)}}</text>
        </view>
        <text class="tenant-name">{{tenant.name}}</text>
        <view class="status-badge" :class="tenant.status">{{tenant.statusText}}</view>
      </view>

      <view class="info-section">
        <view class="section-title">基本信息</view>
        <view class="info-card">
          <view class="info-item">
            <text class="label">联系电话</text>
            <view class="value-with-action">
              <text class="value">{{tenant.phone}}</text>
              <view class="action-btn" @click="callTenant">
                <uni-icons type="phone-filled" size="18" color="#FFFFFF"></uni-icons>
              </view>
            </view>
          </view>
          <view class="info-divider"></view>
          <view class="info-item" v-if="tenant.idCard">
            <text class="label">身份证号</text>
            <text class="value">{{maskIdCard(tenant.idCard)}}</text>
          </view>
          <view class="info-divider" v-if="tenant.idCard"></view>
          <view class="info-item">
            <text class="label">注册时间</text>
            <text class="value">{{tenant.createTime || '--'}}</text>
          </view>
        </view>
      </view>

      <view class="info-section">
        <view class="section-title">租赁统计</view>
        <view class="stats-grid">
          <view class="stat-box">
            <text class="stat-value">{{tenant.activeRentals}}</text>
            <text class="stat-label">在租房间</text>
          </view>
          <view class="stat-box">
            <text class="stat-value">{{tenant.totalRentals}}</text>
            <text class="stat-label">历史租赁</text>
          </view>
        </view>
      </view>

      <view class="info-section" v-if="rentals.length > 0">
        <view class="section-title">租赁记录</view>
        <view class="rental-list">
          <view v-for="(item, index) in rentals" :key="index" class="rental-item" @click="viewRentalDetail(item)">
            <view class="rental-header">
              <text class="room-info">{{item.apartmentName}} {{item.roomNumber}}</text>
              <view class="rental-status" :class="item.status">{{item.statusText}}</view>
            </view>
            <view class="rental-period">{{item.startDate}} ~ {{item.endDate}}</view>
            <view class="rental-price">¥{{item.rent}}/月</view>
          </view>
        </view>
      </view>

      <view class="action-section">
        <view class="action-btn danger" @click="deleteTenant">
          <uni-icons type="trash" size="20" color="#FFFFFF"></uni-icons>
          <text>删除租客</text>
        </view>
      </view>

      <view class="safe-area-bottom" style="height: 40rpx;"></view>
    </scroll-view>

    <view class="loading-state" v-else-if="isLoading">
      <uni-load-more status="loading"></uni-load-more>
    </view>

    <view class="empty-state" v-else>
      <uni-icons type="personadd-filled" size="80" color="#CBD5E1"></uni-icons>
      <text class="empty-text">租客不存在</text>
      <button class="back-btn" @click="goBack">返回</button>
    </view>
  </view>
</template>

<script>
  import renterApi from '@/api/renter.js'
  import rentalApi from '@/api/rental.js'
  
  export default {
    data() {
      return {
        tenantId: null,
        isLoading: false,
        tenant: {},
        rentals: []
      }
    },
    onLoad(options) {
      if (options.id) {
        this.tenantId = options.id
        this.loadTenantDetail(options.id)
        this.loadTenantRentals(options.id)
      }
    },
    methods: {
      async loadTenantDetail(id) {
        this.isLoading = true
        try {
          const res = await renterApi.getDetail(id)
          if (res.data) {
            const data = res.data
            this.tenant = {
              id: data.id,
              name: data.name,
              phone: data.phone,
              idCard: data.idCard,
              status: data.status || 'active',
              statusText: data.status === 'active' ? '在租中' : '已退租',
              activeRentals: data.activeRentals || 0,
              totalRentals: data.totalRentals || 0,
              createTime: data.createTime
            }
          }
        } catch (error) {
          console.error('加载租客详情失败:', error)
          uni.showToast({ title: '加载失败', icon: 'none' })
        } finally {
          this.isLoading = false
        }
      },
      async loadTenantRentals(tenantId) {
        try {
          const res = await rentalApi.getList({ renterId: tenantId, pageSize: 999 })
          if (res.data) {
            this.rentals = res.data.map(item => ({
              id: item.id,
              apartmentName: item.Room?.Apartment?.name || '--',
              roomNumber: item.Room?.roomNumber || '--',
              startDate: item.startDate,
              endDate: item.endDate,
              rent: item.rent,
              status: item.status,
              statusText: this.getStatusText(item.status)
            }))
          }
        } catch (error) {
          console.error('加载租赁记录失败:', error)
        }
      },
      editTenant() {
        uni.navigateTo({ url: `/pages/tenant-add/tenant-add?id=${this.tenantId}&mode=edit` })
      },
      callTenant() {
        if (this.tenant.phone) {
          uni.makePhoneCall({ phoneNumber: this.tenant.phone })
        }
      },
      maskIdCard(idCard) {
        if (!idCard || idCard.length < 8) return idCard
        return idCard.substring(0, 4) + '********' + idCard.substring(idCard.length - 4)
      },
      viewRentalDetail(item) {
        uni.navigateTo({ url: `/pages/rental-detail/rental-detail?id=${item.id}` })
      },
      deleteTenant() {
        uni.showModal({
          title: '确认删除',
          content: `确定要删除租客"${this.tenant.name}"吗？`,
          confirmColor: '#EF4444',
          success: async (res) => {
            if (res.confirm) {
              try {
                await renterApi.delete(this.tenantId)
                uni.showToast({ title: '删除成功', icon: 'success' })
                setTimeout(() => uni.navigateBack(), 1500)
              } catch (error) {
                uni.showToast({ title: '删除失败', icon: 'none' })
              }
            }
          }
        })
      },
      goBack() {
        uni.navigateBack()
      },
      getStatusText(status) {
        const map = { active: '在租', expired: '已到期', terminated: '已终止' }
        return map[status] || status
      }
    }
  }
</script>

<style scoped>
  .tenant-detail-page {
    min-height: 100vh;
    background: #F8FAFC;
    display: flex;
    flex-direction: column;
  }
  .custom-nav {
    background: #FFFFFF;
    border-bottom: 2rpx solid #F1F5F9;
  }
  .nav-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 32rpx;
  }
  .nav-btn {
    width: 72rpx;
    height: 72rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
  }
  .nav-title {
    font-size: 34rpx;
    font-weight: 600;
    color: #1E293B;
  }
  .detail-content {
    flex: 1;
    padding: 24rpx 32rpx;
  }
  .tenant-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 48rpx 0;
    background: #FFFFFF;
    border-radius: 20rpx;
    margin-bottom: 24rpx;
  }
  .tenant-avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #2563EB 0%, #1D4ED8 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20rpx;
  }
  .tenant-avatar text {
    font-size: 48rpx;
    font-weight: 600;
    color: #FFFFFF;
  }
  .tenant-name {
    font-size: 40rpx;
    font-weight: 700;
    color: #1E293B;
    margin-bottom: 12rpx;
  }
  .status-badge {
    padding: 6rpx 20rpx;
    border-radius: 8rpx;
    font-size: 24rpx;
  }
  .status-badge.active {
    background: #D1FAE5;
    color: #059669;
  }
  .status-badge.inactive {
    background: #F3F4F6;
    color: #6B7280;
  }
  .info-section {
    margin-bottom: 24rpx;
  }
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #1E293B;
    margin-bottom: 16rpx;
  }
  .info-card {
    background: #FFFFFF;
    border-radius: 20rpx;
    padding: 0 24rpx;
  }
  .info-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 0;
  }
  .label {
    font-size: 28rpx;
    color: #64748B;
  }
  .value-with-action {
    display: flex;
    align-items: center;
    gap: 16rpx;
  }
  .value {
    font-size: 28rpx;
    color: #1E293B;
    font-weight: 500;
  }
  .action-btn {
    width: 56rpx;
    height: 56rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #10B981 0%, #059669 100%);
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .info-divider {
    height: 2rpx;
    background: #F1F5F9;
  }
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
  }
  .stat-box {
    background: #FFFFFF;
    border-radius: 16rpx;
    padding: 32rpx;
    text-align: center;
  }
  .stat-value {
    font-size: 48rpx;
    font-weight: 700;
    color: #2563EB;
    display: block;
    margin-bottom: 8rpx;
  }
  .stat-label {
    font-size: 26rpx;
    color: #64748B;
  }
  .rental-list {
    background: #FFFFFF;
    border-radius: 20rpx;
    padding: 0 24rpx;
  }
  .rental-item {
    padding: 24rpx 0;
    border-bottom: 2rpx solid #F1F5F9;
  }
  .rental-item:last-child {
    border-bottom: none;
  }
  .rental-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12rpx;
  }
  .room-info {
    font-size: 30rpx;
    font-weight: 600;
    color: #1E293B;
  }
  .rental-status {
    padding: 4rpx 12rpx;
    border-radius: 6rpx;
    font-size: 20rpx;
  }
  .rental-status.active {
    background: #D1FAE5;
    color: #059669;
  }
  .rental-status.expired {
    background: #FEF3C7;
    color: #D97706;
  }
  .rental-status.terminated {
    background: #FEE2E2;
    color: #DC2626;
  }
  .rental-period {
    font-size: 24rpx;
    color: #64748B;
    margin-bottom: 8rpx;
  }
  .rental-price {
    font-size: 28rpx;
    color: #EF4444;
    font-weight: 600;
  }
  .action-section {
    margin-top: 32rpx;
  }
  .action-btn.danger {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12rpx;
    background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%);
    height: 88rpx;
    border-radius: 16rpx;
  }
  .action-btn.danger text {
    font-size: 30rpx;
    font-weight: 600;
    color: #FFFFFF;
  }
  .loading-state, .empty-state {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 120rpx;
  }
  .empty-text {
    font-size: 30rpx;
    color: #64748B;
    margin: 24rpx 0 40rpx;
  }
  .back-btn {
    background: linear-gradient(135deg, #2563EB 0%, #1D4ED8 100%);
    color: #FFFFFF;
    font-size: 30rpx;
    font-weight: 600;
    padding: 24rpx 80rpx;
    border-radius: 16rpx;
    border: none;
  }
</style>
