<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>合同管理</h2>
        <p class="page-desc">管理门店合同信息，包括合同创建、更新、删除和月租明细管理</p>
      </div>
      <div class="header-right">
        <el-button
          type="success"
          icon="el-icon-data-analysis"
          @click="showStatisticsDialog"
        >
          费用统计
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
        >
          新增合同
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="门店" prop="storeId">
          <el-select
            v-model="queryParams.storeId"
            placeholder="请选择门店"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="store in storeList"
              :key="store.id"
              :label="store.fullName"
              :value="store.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="门店名称" prop="storeName">
          <el-input
            v-model="queryParams.storeName"
            placeholder="请输入门店名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input
            v-model="queryParams.category"
            placeholder="请输入分类"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="合同起始日期">
          <el-date-picker
            v-model="contractStartDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            style="width: 240px"
            @change="handleStartDateChange"
          />
        </el-form-item>
        <el-form-item label="合同结束日期">
          <el-date-picker
            v-model="contractEndDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            style="width: 240px"
            @change="handleEndDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <NCC-table
        v-loading="loading"
        :data="list"
        border
        stripe
        height="calc(100vh - 520px)"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column
          prop="storeName"
          label="门店名称"
          width="150"
        >
          <template slot-scope="scope">
            <div class="cell-with-icon">
              <i class="el-icon-office-building icon"></i>
              <span>{{ scope.row.storeName || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="标题"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.title || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="category"
          label="分类"
          width="120"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.category || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="tenantName"
          label="户名"
          width="120"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.tenantName || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="contractStartDate"
          label="合同起始日期"
          width="120"
        >
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.contractStartDate) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="contractEndDate"
          label="合同结束日期"
          width="120"
        >
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.contractEndDate) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="monthlyRent"
          label="月租"
          width="100"
          align="right"
        >
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.monthlyRent) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="paymentAmount"
          label="缴租金额"
          width="120"
          align="right"
        >
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.paymentAmount) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="paymentCycle"
          label="交租周期"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.paymentCycle ? scope.row.paymentCycle + '个月' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="nextPaymentDate"
          label="下次应交时间"
          width="120"
        >
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.nextPaymentDate) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="deposit"
          label="押金"
          width="100"
          align="right"
        >
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.deposit) || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="250"
          align="left"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row.id)"
            >
              查看
            </el-button>
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              icon="el-icon-money"
              @click="handleViewRentDetails(scope.row.id)"
            >
              明细
            </el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              style="color: #f56c6c"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </NCC-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.currentPage"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 表单弹窗 -->
    <form-dialog ref="formDialog" @refresh="getList" />

    <!-- 详情/明细弹窗 -->
    <rent-detail-dialog ref="rentDetailDialog" @refresh="getList" />

    <!-- 费用统计弹窗 -->
    <statistics-dialog ref="statisticsDialog" />
  </div>
</template>

<script>
import {
  getContractList,
  deleteContract
} from '@/api/extend/contract'
import { getStoreSelector } from '@/api/extend/store'
import FormDialog from './form-dialog.vue'
import RentDetailDialog from './rent-detail-dialog.vue'
import StatisticsDialog from './statistics-dialog.vue'
import Pagination from '@/components/Pagination'

export default {
  name: 'ContractManagement',
  components: {
    FormDialog,
    RentDetailDialog,
    StatisticsDialog,
    Pagination
  },
  data() {
    return {
      loading: false,
      list: [],
      total: 0,
      storeList: [],
      contractStartDateRange: null,
      contractEndDateRange: null,
      queryParams: {
        currentPage: 1,
        pageSize: 20,
        sidx: 'createTime',
        sort: 'desc',
        storeId: '',
        storeName: '',
        category: '',
        title: '',
        contractStartDateBegin: '',
        contractStartDateEnd: '',
        contractEndDateBegin: '',
        contractEndDateEnd: '',
        isEffective: 1
      }
    }
  },
  created() {
    this.getStoreList()
    this.getList()
  },
  methods: {
    // 获取门店列表
    async getStoreList() {
      try {
        const response = await getStoreSelector()
        if (response.code === 200 && response.data) {
          this.storeList = response.data.list || []
        }
      } catch (error) {
        console.error('获取门店列表失败:', error)
        this.storeList = []
      }
    },
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const params = {
          currentPage: this.queryParams.currentPage,
          pageSize: this.queryParams.pageSize,
          sidx: this.queryParams.sidx,
          sort: this.queryParams.sort,
          storeId: this.queryParams.storeId || '',
          storeName: this.queryParams.storeName || '',
          category: this.queryParams.category || '',
          title: this.queryParams.title || '',
          contractStartDateBegin: this.queryParams.contractStartDateBegin || '',
          contractStartDateEnd: this.queryParams.contractStartDateEnd || '',
          contractEndDateBegin: this.queryParams.contractEndDateBegin || '',
          contractEndDateEnd: this.queryParams.contractEndDateEnd || '',
          isEffective: this.queryParams.isEffective
        }

        const response = await getContractList(params)

        if (response.code === 200) {
          this.list = response.data.list || []
          this.total =
            (response.data.pagination && response.data.pagination.total) || 0
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取列表失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    // 搜索
    handleQuery() {
      this.queryParams.currentPage = 1
      this.getList()
    },
    // 重置搜索
    resetQuery() {
      this.contractStartDateRange = null
      this.contractEndDateRange = null
      this.queryParams = {
        currentPage: 1,
        pageSize: 20,
        sidx: 'createTime',
        sort: 'desc',
        storeId: '',
        storeName: '',
        category: '',
        title: '',
        contractStartDateBegin: '',
        contractStartDateEnd: '',
        contractEndDateBegin: '',
        contractEndDateEnd: '',
        isEffective: 1
      }
      this.getList()
    },
    // 处理合同起始日期范围变化
    handleStartDateChange(value) {
      if (value && value.length === 2) {
        this.queryParams.contractStartDateBegin = value[0]
        this.queryParams.contractStartDateEnd = value[1]
      } else {
        this.queryParams.contractStartDateBegin = ''
        this.queryParams.contractStartDateEnd = ''
      }
    },
    // 处理合同结束日期范围变化
    handleEndDateChange(value) {
      if (value && value.length === 2) {
        this.queryParams.contractEndDateBegin = value[0]
        this.queryParams.contractEndDateEnd = value[1]
      } else {
        this.queryParams.contractEndDateBegin = ''
        this.queryParams.contractEndDateEnd = ''
      }
    },
    // 新增
    handleAdd() {
      this.$refs.formDialog.openAdd()
    },
    // 编辑
    handleEdit(id) {
      this.$refs.formDialog.openEdit(id)
    },
    // 查看详情
    handleView(id) {
      this.$refs.rentDetailDialog.openView(id)
    },
    // 查看月租明细
    handleViewRentDetails(id) {
      this.$refs.rentDetailDialog.openRentDetails(id)
    },
    // 删除
    handleDelete(id) {
      this.$confirm('确定要删除这条合同吗？删除后该合同的所有月租明细也会被删除。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const response = await deleteContract(id)
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.getList()
            } else {
              this.$message.error(response.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message.error('删除失败')
          }
        })
        .catch(() => {})
    },
    // 格式化日期
    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}`
    },
    // 格式化金额
    formatMoney(amount) {
      if (amount === null || amount === undefined) return ''
      return '¥' + Number(amount).toFixed(2)
    },
    // 显示统计弹窗
    showStatisticsDialog() {
      this.$refs.statisticsDialog.open()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background: #f5f5f5;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

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

    .page-desc {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .header-right {
    display: flex;
    gap: 12px;
  }
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.cell-with-icon {
  display: flex;
  align-items: center;
  gap: 6px;

  .icon {
    color: #409eff;
    font-size: 16px;
  }
}

// 表格样式优化
::v-deep .el-table {
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
  }

  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}
</style>

