<template>
  <div>
    <div class="margin-top flex justify-between">
      <div >
        <el-select v-model="simplifyCarFeeInfo.carId" @change="changeSimplifyCar">
          <el-option
            v-for="(item,index) in simplifyCarFeeInfo.ownerCars"
            :key="index"
            :label="item.carNum"
            :value="item.carId">
          </el-option>
        </el-select>
      </div>
      <div  v-if="simplifyCarFeeInfo.carId">
        <el-button type="primary" size="small" @click="_toBuyCarMonthCard">
          {{ $t('simplifyCarFee.buyMonthCard') }}
        </el-button>
        <el-button type="primary" size="small" @click="_openBatchPayCarFeeModal">
          {{ $t('simplifyCarFee.batchPayment') }}
        </el-button>
        <el-button type="primary" size="small" @click="_openSimplifyCarCreateFeeAddModal">
          {{ $t('simplifyCarFee.createFee') }}
        </el-button>
      </div>
    </div>

    <el-table
      :data="simplifyCarFeeInfo.fees"
      style="width: 100%; margin-top: 10px"
      border>
      <el-table-column prop="feeName" :label="$t('simplifyCarFee.feeItem')" align="center">
        <template #default="{row}">
          <span class="hand" @click="_viewCarFeeConfig(row)">{{row.feeName}}
            <i class="el-icon-info"></i>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="feeFlagName" :label="$t('simplifyCarFee.feeFlag')" align="center"></el-table-column>
      <el-table-column prop="feeTypeCdName" :label="$t('simplifyCarFee.feeType')" align="center"></el-table-column>
      <el-table-column prop="amountOwed" :label="$t('simplifyCarFee.amountReceivable')" align="center"></el-table-column>
      <el-table-column prop="startTime" :label="$t('simplifyCarFee.accountingTime')" align="center"></el-table-column>
      <el-table-column :label="$t('simplifyCarFee.receivablePeriod')" align="center">
        <template #default="{row}">
          {{_getEndTime(row)}}~<br />{{_getDeadlineTime(row)}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('simplifyCarFee.description')" align="center" width="150">
        <template #default="{row}">
          <div v-if="row.feeTypeCd == '888800010015' || row.feeTypeCd == '888800010016'">
            <div>{{ $t('simplifyCarFee.lastDegree') }}：{{row.preDegrees}}</div>
            <div>{{ $t('simplifyCarFee.currentDegree') }}：{{row.curDegrees}}</div>
            <div>{{ $t('simplifyCarFee.unitPrice') }}：{{row.squarePrice}}</div>
            <div>{{ $t('simplifyCarFee.additionalFee') }}：{{row.additionalAmount}}</div>
          </div>
          <div v-else-if="row.feeTypeCd == '888800010017'">
            <div>{{ $t('simplifyCarFee.algorithm') }}：{{_getAttrValue(row.feeAttrs,'390005')}}</div>
            <div>{{ $t('simplifyCarFee.usage') }}：{{_getAttrValue(row.feeAttrs,'390003')}}</div>
          </div>
          <div v-else>
            <div>{{ $t('simplifyCarFee.unitPrice') }}：{{row.squarePrice}}</div>
            <div>{{ $t('simplifyCarFee.fixedFee') }}：{{row.additionalAmount}}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="stateName" :label="$t('simplifyCarFee.status')" align="center"></el-table-column>
      <el-table-column :label="$t('simplifyCarFee.operation')" align="center">
        <template #default="{row}">
          <el-button type="text" v-if="row.state != '2009001' && hasPrivilege('502020082314267912')" @click="_simplifyCarPayFee(row)">
            {{ $t('simplifyCarFee.payment') }}
          </el-button>
          <el-button type="text" @click="_simplifyCarPayFeeHis(row)">
            {{ $t('simplifyCarFee.paymentHistory') }}
          </el-button>
          <el-dropdown>
            <el-button type="text">
              {{ $t('simplifyCarFee.moreOperations') }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="row.isDefault == 'F' && hasPrivilege('502020090604200029')" @click.native="_simplifyCarDeleteFee(row)">
                {{ $t('simplifyCarFee.cancelFee') }}
              </el-dropdown-item>
              <el-dropdown-item v-if="hasPrivilege('502021070488970005')" @click.native="_simplifyCarFinishFee(row)">
                {{ $t('simplifyCarFee.manualFinish') }}
              </el-dropdown-item>
              <el-dropdown-item v-if="row.state != '2009001' && hasPrivilege('502020090427190001')" @click.native="_simplifyCarEditFee(row)">
                {{ $t('simplifyCarFee.feeChange') }}
              </el-dropdown-item>
              <el-dropdown-item>
                <a target="_blank" :href="'/#/views/fee/feeDetail?feeId='+row.feeId">
                  {{ $t('simplifyCarFee.details') }}
                </a>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-row>
      <el-col :span="12">
        <div>{{ $t('simplifyCarFee.note1') }}</div>
        <div>{{ $t('simplifyCarFee.note2') }}</div>
      </el-col>
      <el-col :span="6">
        <span>{{ $t('simplifyCarFee.arrearsSubtotal') }}：{{simplifyCarFeeInfo.totalAmount}}</span>
      </el-col>
      <el-col :span="6">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <car-create-fee-add ref="carCreateFeeAdd" @success="handleNotify" />
    <delete-fee ref="deleteFee" @success="handleNotify"></delete-fee>
    <edit-fee ref="editFee" @success="handleNotify"></edit-fee>
    <finish-fee ref="finishFee" @success="handleNotify"></finish-fee>

  </div>
</template>

<script>
import { getCommunityId } from '@/api/community/communityApi'
import { listFee, queryOwnerCars } from '@/api/simplify/simplifyCarFeeApi'
import CarCreateFeeAdd from '@/components/fee/carCreateFeeAdd'
import DeleteFee from '@/components/fee/deleteFee'
import EditFee from '@/components/fee/editFee'
import FinishFee from '@/components/fee/finishFee'


export default {
  name: 'SimplifyCarFee',
  data() {
    return {
      simplifyCarFeeInfo: {
        fees: [],
        ownerCars: [],
        ownerId: '',
        name: '',
        carNum: '',
        carId: '',
        total: 0,
        records: 1,
        areaNum: '',
        num: '',
        parkingName: '',
        totalAmount: 0.0
      },
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  components: {
    CarCreateFeeAdd,
    DeleteFee,
    EditFee,
    FinishFee
  },
  created() {
    this.communityId = getCommunityId()

  },
  methods: {

    open(param) {
      this.handleSwitch(param)
    },
    handleSwitch(param) {
      if (param.ownerId == '') return
      this.clearSimplifyCarFeeInfo()
      Object.assign(this.simplifyCarFeeInfo, param)
      this.listOwnerCar()
        .then(() => {
          this.listSimplifyCarFee(this.currentPage, this.pageSize)
        })
        .catch(err => {
          this.$message.error(err)
        })
    },
    handleNotify() {
      this.listSimplifyCarFee(this.currentPage, this.pageSize)
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.listSimplifyCarFee(val, this.pageSize)
    },
    listSimplifyCarFee(page, row) {
      if (!this.simplifyCarFeeInfo.carId) return
      
      const params = {
        page,
        row,
        communityId: this.communityId,
        payerObjId: this.simplifyCarFeeInfo.carId
      }
      
      listFee(params).then(res => {
        this.simplifyCarFeeInfo.fees = res.data.fees
        this.total = res.data.records
        let totalAmount = 0.0
        res.data.fees.forEach(item => {
          totalAmount += parseFloat(item.amountOwed)
        })
        this.simplifyCarFeeInfo.totalAmount = totalAmount
      })
    },
    listOwnerCar() {
      return new Promise((resolve, reject) => {
        const params = {
          page: 1,
          row: 50,
          ownerId: this.simplifyCarFeeInfo.ownerId,
          carTypeCd: '1001',
          communityId: this.communityId
        }
        
        queryOwnerCars(params).then(res => {
          let _json = res.data;
          this.simplifyCarFeeInfo.ownerCars = _json.data
          if (_json.data.length > 0) {
            this.simplifyCarFeeInfo.carId = _json.data[0].carId
            this.simplifyCarFeeInfo.carNum = _json.data[0].carNum
            this.simplifyCarFeeInfo.num = _json.data[0].num
            this.simplifyCarFeeInfo.parkingName = `${_json.data[0].areaNum}${this.$t('simplifyCarFee.parkingLot')}${_json.data[0].num}${this.$t('simplifyCarFee.parkingSpace')}`
            resolve(_json.data)
          } else {
            reject(this.$t('simplifyCarFee.noParkingSpace'))
          }
        }).catch(err => {
          reject(err)
        })
      })
    },
    changeSimplifyCar() {
      const car = this.simplifyCarFeeInfo.ownerCars.find(item => item.carId === this.simplifyCarFeeInfo.carId)
      if (!car) return
      
      this.simplifyCarFeeInfo.carNum = car.carNum
      this.simplifyCarFeeInfo.num = car.num
      this.simplifyCarFeeInfo.parkingName = `${car.areaNum}${this.$t('simplifyCarFee.parkingLot')}${car.num}${this.$t('simplifyCarFee.parkingSpace')}`
      this.listSimplifyCarFee(this.currentPage, this.pageSize)
    },
    clearSimplifyCarFeeInfo() {
      this.simplifyCarFeeInfo = {
        fees: [],
        ownerCars: [],
        ownerId: '',
        name: '',
        carNum: '',
        carId: '',
        total: 0,
        records: 1,
        areaNum: '',
        num: '',
        parkingName: '',
        totalAmount: 0.0
      }
    },
    _getEndTime(fee) {
      return fee.state == '2009001' ? '-' : fee.endTime
    },
    _getDeadlineTime(fee) {
      if (fee.amountOwed == 0 && fee.endTime == fee.deadlineTime) return '-'
      if (fee.state == '2009001') return '-'
      return fee.deadlineTime
    },
    _getAttrValue(attrs, code) {
      const attr = attrs.find(item => item.specCd === code)
      return attr ? attr.value : ''
    },
    _simplifyCarGetFeeOwnerInfo(attrs) {
      const ownerName = this._getAttrValue(attrs, '390008')
      const ownerLink = this._getAttrValue(attrs, '390009')
      return `${this.$t('simplifyCarFee.owner')}：${ownerName},${this.$t('simplifyCarFee.phone')}：${ownerLink}`
    },
    _simplifyCarPayFee(fee) {
      this.$router.push(`/views/fee/payFeeOrder?feeId=${fee.feeId}`)
    },
    _simplifyCarPayFeeHis(fee) {

      this.$router.push({
        path: '/views/fee/propertyFee',
        query: fee
      })
    },
    _simplifyCarEditFee(fee) {
      fee.maxEndTime = this._getAttrValue(fee.feeAttrs, '390010')
      this.$refs.editFee.open(fee)
    },
    _simplifyCarDeleteFee(fee) {
      this.$refs.deleteFee.open({
        communityId: getCommunityId(),
        feeId: fee.feeId
      })
    },
    _openSimplifyCarCreateFeeAddModal() {
      this.$refs.carCreateFeeAdd.open({ isMore: false, car: this.simplifyCarFeeInfo })
    },
    _simplifyCarFinishFee(fee) {
      this.$refs.finishFee.open({
        communityId: getCommunityId(),
        feeId: fee.feeId
      })
    },
    _toBuyCarMonthCard() {
      this.$router.push(`/views/fee/buyCarMonthCard?carNum=${this.simplifyCarFeeInfo.carNum}`)
    },
    _openBatchPayCarFeeModal() {
      this.$router.push(`/views/fee/batchPayFeeOrder?ownerId=${this.simplifyCarFeeInfo.ownerId}&payerObjType=6666`)
    },
    _viewCarFeeConfig(fee) {
      // Implement view fee config logic
      console.log(fee)
    }
  }
}
</script>

<style scoped>
.hand {
  cursor: pointer;
}
.margin-top {
  margin-top: 10px;
}
</style>