<template>
  <div class="rental-archive">
    <el-card>
      <template slot="header">
        <div class="card-header">
          <span>租赁档案</span>
        </div>
      </template>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="公寓">
          <el-select v-model="searchForm.apartmentId" placeholder="请选择公寓" @change="handleApartmentChange">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="apartment in apartments" :key="apartment.id" :label="apartment.name" :value="apartment.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间">
          <el-select v-model="searchForm.roomId" placeholder="请选择房间" :disabled="!searchForm.apartmentId">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="room in rooms" :key="room.id" :label="room.roomNumber" :value="room.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="searchForm.startDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="searchForm.endDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="在租" value="active"></el-option>
            <el-option label="已到期" value="expired"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="rentalList" style="width: 100%" v-loading="isLoading">
        <el-table-column prop="tenantName" label="租客" width="120"></el-table-column>
        <el-table-column label="房间" width="150">
          <template slot-scope="scope">
            {{ getApartmentName(scope.row.roomId) }} - {{ getRoomNumber(scope.row.roomId) }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120"></el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120"></el-table-column>
        <el-table-column prop="rent" label="租金(元/月)" width="120"></el-table-column>
        <el-table-column prop="deposit" label="押金(元)" width="120"></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '在租' : '已到期' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleRenew(scope.row)">续租</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog :title="rentalForm.id ? '编辑租赁记录' : '新增租赁记录'" :visible.sync="rentalDialogVisible" width="500px">
      <el-form :model="rentalForm" :rules="rentalRules" ref="rentalForm">
        <el-form-item label="租客姓名" prop="tenantName">
          <el-input v-model="rentalForm.tenantName" placeholder="请输入租客姓名"></el-input>
        </el-form-item>
        <el-form-item label="房间" prop="roomId">
          <el-select v-model="rentalForm.roomId" placeholder="请选择房间" style="width: 100%">
            <el-option v-for="room in allRooms" :key="room.id" :label="`${getApartmentName(room.id)} - ${room.roomNumber}`" :value="room.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="rentalForm.startDate" type="date" placeholder="选择开始日期" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="rentalForm.endDate" type="date" placeholder="选择结束日期" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="租金(元)" prop="rent">
          <el-input v-model.number="rentalForm.rent" placeholder="请输入租金"></el-input>
        </el-form-item>
        <el-form-item label="押金(元)" prop="deposit">
          <el-input v-model.number="rentalForm.deposit" placeholder="请输入押金"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="rentalForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="有效" value="active"></el-option>
            <el-option label="到期" value="expired"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="rentalForm.remark" type="textarea" rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rentalDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { rentalApi, apartmentApi, roomApi } from '../../api/api'

export default {
  name: 'RentalArchive',
  data() {
    return {
      rentalList: [],
      apartments: [],
      rooms: [],
      allRooms: [],
      isLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchForm: {
        apartmentId: '',
        roomId: '',
        startDate: '',
        endDate: '',
        status: ''
      },
      rentalDialogVisible: false,
      rentalForm: {
        id: '',
        roomId: '',
        tenantName: '',
        startDate: '',
        endDate: '',
        rent: '',
        deposit: '',
        status: 'active',
        remark: ''
      },
      rentalRules: {
        tenantName: [{ required: true, message: '请输入租客姓名', trigger: 'blur' }],
        roomId: [{ required: true, message: '请选择房间', trigger: 'change' }],
        startDate: [{ required: true, message: '请选择开始日期', trigger: 'blur' }],
        endDate: [{ required: true, message: '请选择结束日期', trigger: 'blur' }],
        rent: [{ required: true, message: '请输入租金', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.loadApartments()
    this.loadAllRooms()
    this.loadData()
  },
  methods: {
    async loadApartments() {
      try {
        const response = await apartmentApi.getAll()
        this.apartments = response.data || response
      } catch (error) {
        this.$message.error('加载公寓数据失败')
      }
    },
    async loadAllRooms() {
      try {
        const response = await roomApi.getAll()
        this.allRooms = response.data || response
      } catch (error) {
        this.$message.error('加载房间数据失败')
      }
    },
    async loadRooms() {
      if (!this.searchForm.apartmentId) {
        this.rooms = []
        return
      }
      try {
        const response = await roomApi.getAll({ apartmentId: this.searchForm.apartmentId })
        this.rooms = response.data || response
      } catch (error) {
        this.$message.error('加载房间数据失败')
      }
    },
    handleApartmentChange() {
      this.searchForm.roomId = ''
      this.loadRooms()
    },
    async loadData() {
      this.isLoading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize
        }

        if (this.searchForm.apartmentId) {
          params.apartmentId = this.searchForm.apartmentId
        }
        if (this.searchForm.roomId) {
          params.roomId = this.searchForm.roomId
        }
        if (this.searchForm.status) {
          params.status = this.searchForm.status
        }
        if (this.searchForm.startDate && Array.isArray(this.searchForm.startDate) && this.searchForm.startDate.length === 2) {
          params.startDateFrom = this.searchForm.startDate[0]
          params.startDateTo = this.searchForm.startDate[1]
        }
        if (this.searchForm.endDate && Array.isArray(this.searchForm.endDate) && this.searchForm.endDate.length === 2) {
          params.endDateFrom = this.searchForm.endDate[0]
          params.endDateTo = this.searchForm.endDate[1]
        }

        const response = await rentalApi.getAll(params)
        this.rentalList = response.data || response
        this.total = response.total || 0
      } catch (error) {
        this.$message.error('加载数据失败')
      } finally {
        this.isLoading = false
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },
    resetSearch() {
      this.searchForm = {
        apartmentId: '',
        roomId: '',
        startDate: '',
        endDate: '',
        status: ''
      }
      this.rooms = []
      this.currentPage = 1
      this.loadData()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.loadData()
    },
    handleCurrentChange(current) {
      this.currentPage = current
      this.loadData()
    },
    getApartmentName(roomId) {
      const room = this.allRooms.find(r => r.id == roomId)
      if (room) {
        const apartment = this.apartments.find(a => a.id == room.apartmentId)
        return apartment ? apartment.name : ''
      }
      return ''
    },
    getRoomNumber(roomId) {
      const room = this.allRooms.find(r => r.id == roomId)
      return room ? room.roomNumber : ''
    },
    handleEdit(rental) {
      this.rentalForm = {
        ...rental,
        startDate: rental.startDate ? new Date(rental.startDate) : '',
        endDate: rental.endDate ? new Date(rental.endDate) : ''
      }
      this.rentalDialogVisible = true
    },
    handleRenew(rental) {
      const oldEndDate = new Date(rental.endDate)
      const newStartDate = new Date(oldEndDate)

      const oldStartDate = new Date(rental.startDate)
      const monthsDiff = (oldEndDate.getFullYear() - oldStartDate.getFullYear()) * 12 + (oldEndDate.getMonth() - oldStartDate.getMonth())

      const newEndDate = new Date(newStartDate)
      newEndDate.setMonth(newEndDate.getMonth() + monthsDiff)

      this.rentalForm = {
        id: '',
        roomId: rental.roomId,
        tenantName: rental.tenantName,
        startDate: newStartDate,
        endDate: newEndDate,
        rent: rental.rent,
        deposit: rental.deposit,
        status: 'active',
        remark: '续租'
      }
      this.rentalDialogVisible = true
    },
    async handleSave() {
      try {
        if (this.rentalForm.id) {
          await rentalApi.update(this.rentalForm.id, this.rentalForm)
          this.$message.success('租赁记录更新成功')
        } else {
          await rentalApi.create(this.rentalForm)
          this.$message.success('租赁记录添加成功')
        }
        this.rentalDialogVisible = false
        this.loadData()
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    async handleDelete(id) {
      this.$confirm('确定要删除这条租赁记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(async () => {
        try {
          await rentalApi.delete(id)
          this.$message.success('租赁记录删除成功')
          this.loadData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.rental-archive {
  padding: 20px 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
