<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="1000px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 合同详情 -->
    <div v-if="contractInfo && viewMode === 'view'" class="contract-info">
      <h3>合同信息</h3>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="门店名称">
          {{ contractInfo.storeName || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="标题">
          {{ contractInfo.title || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="分类">
          {{ contractInfo.category || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="户名">
          {{ contractInfo.tenantName || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="合同起始日期">
          {{ formatDate(contractInfo.contractStartDate) || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="合同结束日期">
          {{ formatDate(contractInfo.contractEndDate) || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="月租">
          {{ formatMoney(contractInfo.monthlyRent) || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="缴租金额">
          {{ formatMoney(contractInfo.paymentAmount) || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="交租周期">
          {{ contractInfo.paymentCycle ? contractInfo.paymentCycle + '个月' : '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="押金">
          {{ formatMoney(contractInfo.deposit) || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="下次应交时间">
          {{ formatDate(contractInfo.nextPaymentDate) || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="提前提醒天数">
          {{ contractInfo.reminderDays || 0 }} 天
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ contractInfo.remarks || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="附件" :span="2">
          <div v-if="attachmentList.length > 0" class="attachment-list">
            <div
              v-for="(file, index) in attachmentList"
              :key="index"
              class="attachment-item"
            >
              <!-- 图片文件使用 el-image 预览 -->
              <el-image
                v-if="isImageFile(file)"
                :src="getFileUrl(file)"
                :preview-src-list="getImagePreviewList()"
                fit="cover"
                class="attachment-image"
                :initial-index="getImageIndex(file)"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <!-- 非图片文件显示文件名，点击预览 -->
              <div v-else class="file-item" @click="handlePreviewFile(file)">
                <i class="el-icon-document"></i>
                <span class="file-name">{{ file.name || file.fileId }}</span>
              </div>
            </div>
          </div>
          <span v-else>无</span>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 月租明细列表 -->
    <div class="rent-details">
      <div class="details-header">
        <h3>月租明细</h3>
        <el-button
          v-if="viewMode === 'rentDetails'"
          type="primary"
          size="small"
          icon="el-icon-refresh"
          @click="loadRentDetails"
        >
          刷新
        </el-button>
      </div>
      <el-table
        v-loading="detailsLoading"
        :data="rentDetailsList"
        border
        stripe
        max-height="400"
      >
        <el-table-column
          prop="paymentMonth"
          label="应缴月份"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.paymentMonth) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="dueDate"
          label="应缴日期"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.dueDate) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="dueAmount"
          label="应缴金额"
          width="120"
          align="right"
        >
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.dueAmount) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="isPaid"
          label="缴费状态"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.isPaid === 1 ? 'success' : 'warning'">
              {{ scope.row.isPaid === 1 ? '已缴费' : '未缴费' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="actualPaymentDate"
          label="实际缴费时间"
          width="160"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ formatDateTime(scope.row.actualPaymentDate) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="actualPaymentAmount"
          label="实际缴费金额"
          width="120"
          align="right"
        >
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.actualPaymentAmount) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="remarks"
          label="备注"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.remarks || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="120"
          align="left"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.isPaid === 0"
              type="text"
              icon="el-icon-money"
              @click="handleMarkPaid(scope.row)"
            >
              标记缴费
            </el-button>
            <span v-else style="color: #909399;">已缴费</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 标记缴费弹窗 -->
    <el-dialog
      title="标记缴费"
      :visible.sync="markPaidDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        ref="markPaidForm"
        :model="markPaidForm"
        :rules="markPaidRules"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="应缴金额">
          <span>{{ formatMoney(currentDetail.dueAmount) }}</span>
        </el-form-item>
        <el-form-item label="实际缴费时间" prop="actualPaymentDate">
          <el-date-picker
            v-model="markPaidForm.actualPaymentDate"
            type="datetime"
            placeholder="请选择实际缴费时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="实际缴费金额" prop="actualPaymentAmount">
          <el-input-number
            v-model="markPaidForm.actualPaymentAmount"
            :min="0"
            :precision="2"
            placeholder="请输入实际缴费金额"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="markPaidForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="markPaidDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleMarkPaidSubmit" :loading="markPaidLoading">
          确定
        </el-button>
      </div>
    </el-dialog>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getContractInfo,
  getRentDetails,
  markRentDetailPaid
} from '@/api/extend/contract'
import { getDownloadUrl } from '@/api/common'
import define from '@/utils/define'

export default {
  name: 'RentDetailDialog',
  data() {
    return {
      visible: false,
      viewMode: 'view', // 'view' 查看详情, 'rentDetails' 查看明细
      dialogTitle: '合同详情',
      contractInfo: null,
      rentDetailsList: [],
      detailsLoading: false,
      markPaidDialogVisible: false,
      markPaidLoading: false,
      currentDetail: {},
      markPaidForm: {
        id: '',
        actualPaymentDate: '',
        actualPaymentAmount: 0,
        remarks: ''
      },
      markPaidRules: {
        actualPaymentDate: [
          { required: true, message: '请选择实际缴费时间', trigger: 'change' }
        ],
        actualPaymentAmount: [
          { required: true, message: '请输入实际缴费金额', trigger: 'blur' },
          { type: 'number', min: 0, message: '实际缴费金额必须大于等于0', trigger: 'blur' }
        ]
      },
      contractId: null,
      attachmentList: [],
      define: define
    }
  },
  methods: {
    // 打开查看详情
    async openView(id) {
      this.viewMode = 'view'
      this.dialogTitle = '合同详情'
      this.contractId = id
      this.visible = true
      await this.loadContractInfo()
      await this.loadRentDetails()
    },
    // 打开查看月租明细
    async openRentDetails(id) {
      this.viewMode = 'rentDetails'
      this.dialogTitle = '月租明细'
      this.contractId = id
      this.visible = true
      await this.loadContractInfo()
      await this.loadRentDetails()
    },
    // 加载合同信息
    async loadContractInfo() {
      if (!this.contractId) return

      try {
        const response = await getContractInfo(this.contractId)
        if (response.code === 200 && response.data) {
          this.contractInfo = response.data
          // 解析附件
          if (response.data.attachment) {
            try {
              this.attachmentList = JSON.parse(response.data.attachment)
            } catch (e) {
              // 如果不是 JSON，可能是单个文件名
              if (response.data.attachment) {
                this.attachmentList = [
                  {
                    name: response.data.attachment,
                    fileId: response.data.attachment,
                    url: ''
                  }
                ]
              } else {
                this.attachmentList = []
              }
            }
          } else {
            this.attachmentList = []
          }
        } else {
          this.$message.error(response.msg || '获取合同信息失败')
        }
      } catch (error) {
        console.error('获取合同信息失败:', error)
        this.$message.error('获取合同信息失败')
      }
    },
    // 加载月租明细
    async loadRentDetails() {
      if (!this.contractId) return

      this.detailsLoading = true
      try {
        const response = await getRentDetails(this.contractId)
        if (response.code === 200 && response.data) {
          this.rentDetailsList = response.data || []
        } else {
          this.$message.error(response.msg || '获取月租明细失败')
        }
      } catch (error) {
        console.error('获取月租明细失败:', error)
        this.$message.error('获取月租明细失败')
      } finally {
        this.detailsLoading = false
      }
    },
    // 标记缴费
    handleMarkPaid(row) {
      this.currentDetail = row
      this.markPaidForm = {
        id: row.id,
        actualPaymentDate: this.formatDateTime(new Date()),
        actualPaymentAmount: row.dueAmount || 0,
        remarks: ''
      }
      this.markPaidDialogVisible = true
    },
    // 提交标记缴费
    handleMarkPaidSubmit() {
      this.$refs.markPaidForm.validate(async (valid) => {
        if (!valid) return

        const submitData = {
          id: this.markPaidForm.id,
          actualPaymentDate: this.markPaidForm.actualPaymentDate.replace(' ', 'T'),
          actualPaymentAmount: this.markPaidForm.actualPaymentAmount,
          remarks: this.markPaidForm.remarks || ''
        }

        this.markPaidLoading = true
        try {
          const response = await markRentDetailPaid(submitData)
          if (response.code === 200) {
            this.$message.success('标记缴费成功')
            this.markPaidDialogVisible = false
            await this.loadRentDetails()
            await this.loadContractInfo()
            this.$emit('refresh')
          } else {
            this.$message.error(response.msg || '标记缴费失败')
          }
        } catch (error) {
          console.error('标记缴费失败:', error)
          this.$message.error(error.message || '标记缴费失败')
        } finally {
          this.markPaidLoading = false
        }
      })
    },
    // 关闭弹窗
    handleClose() {
      this.visible = false
      this.contractInfo = null
      this.rentDetailsList = []
      this.contractId = null
      this.attachmentList = []
      this.markPaidDialogVisible = false
      this.currentDetail = {}
      this.markPaidForm = {
        id: '',
        actualPaymentDate: '',
        actualPaymentAmount: 0,
        remarks: ''
      }
    },
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    // 格式化日期时间
    formatDateTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    // 格式化金额
    formatMoney(amount) {
      if (amount === null || amount === undefined) return ''
      return '¥' + Number(amount).toFixed(2)
    },
    // 判断是否为图片文件
    isImageFile(file) {
      if (!file.name && !file.url) return false
      const fileName = file.name || file.url || ''
      const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']
      const extension = this.getFileExtension(fileName)
      return imageExtensions.includes(extension.toLowerCase())
    },
    // 获取文件扩展名
    getFileExtension(fileName) {
      if (!fileName) return ''
      const lastDot = fileName.lastIndexOf('.')
      return lastDot > -1 ? fileName.substring(lastDot + 1) : ''
    },
    // 获取文件URL
    getFileUrl(file) {
      if (file.url) {
        return file.url.startsWith('http') ? file.url : this.define.comUrl + file.url
      }
      // 如果没有url，尝试通过fileId获取
      if (file.fileId) {
        return this.define.comUrl + '/api/file/Download/contract/' + file.fileId
      }
      return ''
    },
    // 获取所有图片的预览列表
    getImagePreviewList() {
      return this.attachmentList
        .filter(file => this.isImageFile(file))
        .map(file => this.getFileUrl(file))
    },
    // 获取当前图片在预览列表中的索引
    getImageIndex(file) {
      const imageList = this.attachmentList.filter(f => this.isImageFile(f))
      return imageList.findIndex(f => (f.fileId === file.fileId || f.url === file.url))
    },
    // 预览文件（非图片文件）
    async handlePreviewFile(file) {
      if (!file.fileId) {
        this.$message.warning('文件ID不存在')
        return
      }
      try {
        const response = await getDownloadUrl('contract', file.fileId)
        if (response.code === 200 && response.data) {
          const fileUrl = this.define.comUrl + response.data.url
          // 在新窗口打开预览
          window.open(fileUrl, '_blank')
        } else {
          this.$message.error(response.msg || '获取预览链接失败')
        }
      } catch (error) {
        console.error('预览文件失败:', error)
        this.$message.error('预览文件失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.contract-info {
  margin-bottom: 20px;

  h3 {
    margin: 0 0 12px 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
}

.rent-details {
  .details-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    h3 {
      margin: 0;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }
  }
}

.dialog-footer {
  text-align: right;
}

.attachment-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.attachment-item {
  .attachment-image {
    width: 100px;
    height: 100px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    overflow: hidden;

    ::v-deep .el-image__inner {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .image-slot {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      background: #f5f7fa;
      color: #909399;
      font-size: 24px;
    }
  }

  .file-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
      background-color: #ecf5ff;
    }

    .el-icon-document {
      color: #409eff;
      font-size: 18px;
    }

    .file-name {
      color: #606266;
      font-size: 14px;

      &:hover {
        color: #409eff;
      }
    }
  }
}
</style>

