<template>
  <div class="report-pay-fee-detail-container animated fadeInRight">
    <!-- 查询条件 -->
    <el-card class="search-card">
      <div slot="header" class="flex justify-between">
        <span>{{ $t('reportPayFeeDetail.search.title') }}</span>
        <el-button type="text" style="float: right; padding: 3px 0" @click="_moreCondition()">
          {{ reportPayFeeDetailInfo.moreCondition ? $t('reportPayFeeDetail.hide') : $t('reportPayFeeDetail.more') }}
        </el-button>
      </div>

      <el-row :gutter="20">
        <el-col :span="4">
          <el-date-picker v-model="reportPayFeeDetailInfo.conditions.startTime" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('reportPayFeeDetail.search.startTime')"
            style="width: 100%" />
        </el-col>

        <el-col :span="4">
          <el-date-picker v-model="reportPayFeeDetailInfo.conditions.endTime" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('reportPayFeeDetail.search.endTime')"
            style="width: 100%" @change="validateDate" />
        </el-col>

        <el-col :span="4">
          <el-select v-model="reportPayFeeDetailInfo.conditions.primeRate"
            :placeholder="$t('reportPayFeeDetail.search.paymentMethod')" style="width: 100%" clearable>
            <el-option v-for="(item, index) in reportPayFeeDetailInfo.primeRates" :key="index" :label="item.name"
              :value="item.statusCd" />
          </el-select>
        </el-col>

        <el-col :span="4">
          <el-select v-model="reportPayFeeDetailInfo.conditions.state"
            :placeholder="$t('reportPayFeeDetail.search.feeStatus')" style="width: 100%" clearable>
            <el-option v-for="(item, index) in reportPayFeeDetailInfo.states" :key="index" :label="item.name"
              :value="item.statusCd" />
          </el-select>
        </el-col>

        <el-col :span="4">
          <el-input v-model="reportPayFeeDetailInfo.conditions.payerObjName"
            :placeholder="$t('reportPayFeeDetail.search.roomOrCarNum')" clearable />
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="_queryMethod()">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="_resetMethod()">
            <i class="el-icon-refresh"></i>
            {{ $t('common.reset') }}
          </el-button>
        </el-col>
      </el-row>

      <!-- 更多查询条件 -->
      <el-row v-show="reportPayFeeDetailInfo.moreCondition" :gutter="20" style="margin-top: 20px">
        <el-col :span="4">
          <el-select v-model="reportPayFeeDetailInfo.conditions.feeTypeCd"
            :placeholder="$t('reportPayFeeDetail.search.feeType')" style="width: 100%" clearable
            @change="_selectConfig">
            <el-option v-for="(item, index) in reportPayFeeDetailInfo.feeTypeCds" :key="index" :label="item.name"
              :value="item.statusCd" />
          </el-select>
        </el-col>

        <el-col :span="4">
          <el-select v-model="reportPayFeeDetailInfo.conditions.configId"
            :placeholder="$t('reportPayFeeDetail.search.feeItem')" style="width: 100%" clearable>
            <el-option v-for="(item, index) in reportPayFeeDetailInfo.feeConfigDtos" :key="index" :label="item.feeName"
              :value="item.configId" />
          </el-select>
        </el-col>

        <el-col :span="4">
          <el-date-picker v-model="reportPayFeeDetailInfo.conditions.feeStartTime" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('reportPayFeeDetail.search.feeStartTime')"
            style="width: 100%" />
        </el-col>

        <el-col :span="4">
          <el-date-picker v-model="reportPayFeeDetailInfo.conditions.feeEndTime" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('reportPayFeeDetail.search.feeEndTime')"
            style="width: 100%" />
        </el-col>
      </el-row>

      <el-row v-show="reportPayFeeDetailInfo.moreCondition && reportPayFeeDetailInfo.communitys.length > 1" :gutter="20"
        style="margin-top: 20px">
        <el-col :span="4">
          <el-select v-model="reportPayFeeDetailInfo.conditions.communityId"
            :placeholder="$t('reportPayFeeDetail.search.community')" style="width: 100%" clearable
            @change="_changCommunity">
            <el-option v-for="(item, index) in reportPayFeeDetailInfo.communitys" :key="index" :label="item.name"
              :value="item.communityId" />
          </el-select>
        </el-col>
      </el-row>
    </el-card>

    <!-- 缴费明细表 -->
    <el-card class="table-card">
      <div slot="header" class="flex justify-between">
        <div>
          <span>{{ $t('reportPayFeeDetail.table.title') }}</span>
          <el-tooltip effect="dark" :content="$t('reportPayFeeDetail.table.tooltip')" placement="top">
            <i class="el-icon-info" style="margin-left: 10px; cursor: pointer"></i>
          </el-tooltip>
        </div>
        <el-button type="primary" size="small" style="float: right" @click="_exportFee">
          {{ $t('common.export') }}
        </el-button>
      </div>

      <el-table :data="reportPayFeeDetailInfo.fees" border style="width: 100%" v-loading="loading">
        <el-table-column prop="oId" :label="$t('reportPayFeeDetail.table.orderNum')" align="center" />
        <el-table-column :label="$t('reportPayFeeDetail.table.roomOwner')" align="center" width="120">
          <template slot-scope="scope">
            <div>{{ scope.row.payerObjName }}/{{ scope.row.ownerName }}</div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('reportPayFeeDetail.table.feeTypeItem')" align="center">
          <template slot-scope="scope">
            {{ scope.row.feeTypeCdName }}>{{ scope.row.feeName }}
          </template>
        </el-table-column>
        <el-table-column prop="stateName" :label="$t('reportPayFeeDetail.table.feeStatus')" align="center" />
        <el-table-column prop="primeRate" :label="$t('reportPayFeeDetail.table.paymentMethod')" align="center" />
        <el-table-column :label="$t('reportPayFeeDetail.table.paymentPeriod')" align="center" width="150">
          <template slot-scope="scope">
            <div>{{ dateFormat(scope.row.startTime) }}</div>
            <div>~</div>
            <div>{{ dateFormat(scope.row.endTime) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" :label="$t('reportPayFeeDetail.table.paymentTime')" align="center" />
        <el-table-column prop="cashierName" :label="$t('reportPayFeeDetail.table.cashier')" align="center" />
        <el-table-column :label="$t('reportPayFeeDetail.table.payableAmount')" align="center">
          <template slot-scope="scope">
            {{ scope.row.payableAmount }}/{{ scope.row.receivableAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="receivedAmount" :label="$t('reportPayFeeDetail.table.receivedAmount')" align="center" />
        <el-table-column prop="withholdAmount" :label="$t('reportPayFeeDetail.table.withholdAmount')" align="center" />
        <el-table-column :label="$t('reportPayFeeDetail.table.preferentialAmount')" align="center">
          <template slot-scope="scope">
            {{ scope.row.preferentialAmount }}/{{ scope.row.deductionAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="giftAmount" :label="$t('reportPayFeeDetail.table.giftAmount')" align="center" />
        <el-table-column prop="lateFee" :label="$t('reportPayFeeDetail.table.lateFee')" align="center" />
        <el-table-column prop="builtUpArea" :label="$t('reportPayFeeDetail.table.area')" align="center" />
        <el-table-column prop="psName" :label="$t('reportPayFeeDetail.table.parkingSpace')" align="center" />
        <el-table-column prop="remark" :label="$t('reportPayFeeDetail.table.remark')" align="center" width="100" />
      </el-table>

      <!-- 统计信息 -->
      <el-row class="summary-row text-left">
        <el-col :span="24">
          <el-row>
            <el-col :span="2">{{ $t('reportPayFeeDetail.summary.subtotal') }}</el-col>
            <el-col :span="4">
              <div>{{ $t('reportPayFeeDetail.summary.receivable') }}: {{ reportPayFeeDetailInfo.totalReceivableAmount }}
                {{
                  $t('reportPayFeeDetail.summary.yuan') }}</div>
              <div>{{ $t('reportPayFeeDetail.summary.received') }}: {{ reportPayFeeDetailInfo.totalReceivedAmount }} {{
                $t('reportPayFeeDetail.summary.yuan') }}</div>
            </el-col>
            <el-col :span="4">
              <div>{{ $t('reportPayFeeDetail.summary.preferential') }}: {{
                reportPayFeeDetailInfo.totalPreferentialAmount
                }}
                {{ $t('reportPayFeeDetail.summary.yuan') }}</div>
              <div>{{ $t('reportPayFeeDetail.summary.deduction') }}: {{ reportPayFeeDetailInfo.totalDeductionAmount }}
                {{
                  $t('reportPayFeeDetail.summary.yuan') }}</div>
            </el-col>
            <el-col :span="4">
              <div>{{ $t('reportPayFeeDetail.summary.gift') }}: {{ reportPayFeeDetailInfo.totalGiftAmount }} {{
                $t('reportPayFeeDetail.summary.yuan') }}</div>
              <div>{{ $t('reportPayFeeDetail.summary.lateFee') }}: {{ reportPayFeeDetailInfo.totalLateFee }} {{
                $t('reportPayFeeDetail.summary.yuan') }}</div>
            </el-col>
          </el-row>
          <el-row style="margin-top: 10px">
            <el-col :span="2">{{ $t('reportPayFeeDetail.summary.total') }}</el-col>
            <el-col :span="4">
              <div>{{ $t('reportPayFeeDetail.summary.receivable') }}: {{ reportPayFeeDetailInfo.allReceivableAmount }}
                {{
                  $t('reportPayFeeDetail.summary.yuan') }}</div>
              <div>{{ $t('reportPayFeeDetail.summary.received') }}: {{ reportPayFeeDetailInfo.allReceivedAmount }} {{
                $t('reportPayFeeDetail.summary.yuan') }}</div>
            </el-col>
            <el-col :span="4">
              <div>{{ $t('reportPayFeeDetail.summary.preferential') }}: {{ reportPayFeeDetailInfo.allPreferentialAmount
                }}
                {{ $t('reportPayFeeDetail.summary.yuan') }}</div>
              <div>{{ $t('reportPayFeeDetail.summary.deduction') }}: {{ reportPayFeeDetailInfo.allDeductionAmount }} {{
                $t('reportPayFeeDetail.summary.yuan') }}</div>
            </el-col>
            <el-col :span="4">
              <div>{{ $t('reportPayFeeDetail.summary.gift') }}: {{ reportPayFeeDetailInfo.allGiftAmount }} {{
                $t('reportPayFeeDetail.summary.yuan') }}</div>
              <div>{{ $t('reportPayFeeDetail.summary.lateFee') }}: {{ reportPayFeeDetailInfo.allLateFee }} {{
                $t('reportPayFeeDetail.summary.yuan') }}</div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <!-- 说明 -->
      <el-row class="text-left table-desc">
        <el-col :span="18">
          <div>{{ $t('reportPayFeeDetail.explanation.preferential') }}</div>
          <div>{{ $t('reportPayFeeDetail.explanation.deduction') }}</div>
          <div>{{ $t('reportPayFeeDetail.explanation.gift') }}</div>
          <div>{{ $t('reportPayFeeDetail.explanation.lateFee') }}</div>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <el-pagination :current-page.sync="currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="reportPayFeeDetailInfo.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>
  </div>
</template>

<script>
import { queryPayFeeDetail, exportData, listFeeConfigs } from '@/api/report/reportPayFeeDetailApi'
import { getDict } from '@/api/community/communityApi'
import { getCommunityId } from '@/api/community/communityApi'
import {
  listMyEnteredCommunitys
} from '@/api/report/dataReportApi'
import { dateFormat } from '@/utils/dateUtil'

export default {
  name: 'ReportPayFeeDetailList',
  data() {
    return {
      loading: false,
      currentPage: 1,
      pageSize: 10,
      reportPayFeeDetailInfo: {
        fees: [],
        total: 0,
        records: 1,
        moreCondition: false,
        primeRates: [],
        feeConfigDtos: [],
        states: [],
        feeTypeCds: [],
        floors: [],
        communitys: [],
        totalReceivableAmount: 0.0,
        totalReceivedAmount: 0.0,
        allReceivableAmount: 0.0,
        allReceivedAmount: 0.0,
        totalPreferentialAmount: 0.0,
        totalDeductionAmount: 0.0,
        totalLateFee: 0.0,
        totalGiftAmount: 0.0,
        allPreferentialAmount: 0.0,
        allDeductionAmount: 0.0,
        allLateFee: 0.0,
        allGiftAmount: 0.0,
        conditions: {
          floorId: '',
          roomNum: '',
          payerObjName: '',
          configId: '',
          primeRate: '',
          state: '',
          feeTypeCd: '',
          startTime: '',
          endTime: '',
          feeStartTime: '',
          feeEndTime: '',
          communityId: ''
        }
      }
    }
  },
  created() {
    this._initMethod()
  },
  methods: {
    async _initMethod() {
      this.reportPayFeeDetailInfo.conditions.communityId = getCommunityId()
      await this._loadStaffCommunitys()
      await this._listFees(1, this.pageSize)

      // 获取字典数据
      try {
        this.reportPayFeeDetailInfo.primeRates = await getDict('pay_fee_detail', 'prime_rate')
        this.reportPayFeeDetailInfo.states = await getDict('pay_fee_detail', 'state')
        this.reportPayFeeDetailInfo.feeTypeCds = await getDict('pay_fee_config', 'fee_type_cd')
      } catch (error) {
        console.error('获取字典数据失败:', error)
      }
    },

    async _listFees(page, rows) {
      this.loading = true
      try {
      const params = {
          ...this.reportPayFeeDetailInfo.conditions,
          page,
          row: rows
        }

        const { data, total, records, sumTotal } = await queryPayFeeDetail(params)

        if (data && data.length > 0) {
          this.reportPayFeeDetailInfo.fees = data.map(item => ({
            ...item,
            lateFee: (item.lateFee * -1).toFixed(2)
          }))
        }

        this.reportPayFeeDetailInfo.total = total
        this.reportPayFeeDetailInfo.records = records

        // 处理统计信息
        this._processSummaryData(sumTotal)
      } catch (error) {
        console.error('查询缴费明细失败:', error)
        this.$message.error(this.$t('reportPayFeeDetail.fetchError'))
      } finally {
        this.loading = false
      }
    },

    _processSummaryData(sumTotal) {
      const fields = [
        'totalReceivableAmount', 'totalReceivedAmount', 'allReceivableAmount', 'allReceivedAmount',
        'totalPreferentialAmount', 'totalDeductionAmount', 'totalLateFee', 'totalGiftAmount',
        'allPreferentialAmount', 'allDeductionAmount', 'allLateFee', 'allGiftAmount'
      ]

      fields.forEach(field => {
        this.reportPayFeeDetailInfo[field] = sumTotal[field]
          ? parseFloat(sumTotal[field]).toFixed(2)
          : '0.00'
      })
    },

    async _loadStaffCommunitys() {
      try {
        const params = {
          _uid: '123mlkdinkldldijdhuudjdjkkd',
          page: 1,
          row: 100
        }
        const { communitys } = await listMyEnteredCommunitys(params)
        this.reportPayFeeDetailInfo.communitys = communitys
      } catch (error) {
        console.error('获取小区列表失败:', error)
      }
    },

    async _selectConfig() {
      try {
        const params = {
          page: 1,
          row: 50,
          communityId: this.reportPayFeeDetailInfo.conditions.communityId,
          feeTypeCd: this.reportPayFeeDetailInfo.conditions.feeTypeCd,
          isFlag: "0"
        }
        const { feeConfigs } = await listFeeConfigs(params)
        this.reportPayFeeDetailInfo.feeConfigDtos = feeConfigs
      } catch (error) {
        console.error('获取费用项失败:', error)
      }
    },

    _moreCondition() {
      this.reportPayFeeDetailInfo.moreCondition = !this.reportPayFeeDetailInfo.moreCondition
    },

    async _exportFee() {
      try {
        const params = {
          ...this.reportPayFeeDetailInfo.conditions,
          pagePath: 'reportPayFeeDetail'
        }

        const { code, msg } = await exportData(params)

        this.$message.success(msg)
        if (code === 0) {
          this.$router.push('/pages/property/downloadTempFile?tab=下载中心')
        }
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error(this.$t('reportPayFeeDetail.exportError'))
      }
    },

    _changCommunity() {
      this._listFees(1, this.pageSize)
    },

    _queryMethod() {
      this._listFees(1, this.pageSize)
    },

    _resetMethod() {
      this.reportPayFeeDetailInfo.conditions = {
        floorId: '',
        roomNum: '',
        payerObjName: '',
        configId: '',
        primeRate: '',
        state: '',
        feeTypeCd: '',
        startTime: '',
        endTime: '',
        feeStartTime: '',
        feeEndTime: '',
        communityId: this.reportPayFeeDetailInfo.conditions.communityId
      }
      this._listFees(1, this.pageSize)
    },

    validateDate() {
      if (this.reportPayFeeDetailInfo.conditions.startTime &&
        this.reportPayFeeDetailInfo.conditions.endTime &&
        new Date(this.reportPayFeeDetailInfo.conditions.startTime) >=
        new Date(this.reportPayFeeDetailInfo.conditions.endTime)) {
        this.$message.error(this.$t('reportPayFeeDetail.dateError'))
        this.reportPayFeeDetailInfo.conditions.endTime = ''
      }
    },

    dateFormat,

    handleSizeChange(val) {
      this.pageSize = val
      this._listFees(this.currentPage, val)
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this._listFees(val, this.pageSize)
    }
  }
}
</script>

<style lang="scss" scoped>
.report-pay-fee-detail-container {
  padding: 20px;

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

  .table-card {
    margin-bottom: 20px;
  }

  .summary-row {
    margin: 20px 0;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .explanation-row {
    margin: 20px 0;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    color: #909399;
    font-size: 14px;
  }

  .el-pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style>