<template>
  <view class="min-height bg-gray-light">
    <view class="p-20 bg-white flex justify-between items-center text-30" @click="showRoom = true">
      <template v-if="currentRoom">
        <text>{{ currentRoom.title }}</text>
        <u-icon name="arrow-right"/>
      </template>
    </view>
    <view class="p-10">
      <u-subsection :list="subsection" :current="billState" mode="button" @change="onChangeSubsection"/>
      <template v-if="billList.length">
        <view v-for="(item, index) in billList" :key="index"
              class="card flex flex-col justify-center items-center my-20">
          <view class="flex justify-between items-center mb-15 w-100p">
            <view class="flex justify-start items-center" @click="changeSelect(index)">
              <u-icon v-if="billState === 0" :name="item.selected ? 'checkmark-circle-fill' : 'checkmark-circle'"
                      :color="item.selected ? MAIN() : '#999'"/>
              <text class="text-25 font-bold">{{ item.month }}</text>
            </view>
            <view class="flex justify-end items-center" @click="changeShow(index)">
              <text class="text-orange text-28 font-bold mr-10">￥{{ item.totalAmount }}</text>
              <u-icon :name="item.show ? 'arrow-down' : 'arrow-right'"/>
            </view>
          </view>
          <view class="p-20 bg-gray-light rounded w-85p p-15 flex flex-col justify-center items-center"
                v-if="item.show">
            <view class="flex flex-col justify-center items-center w-100p mb-20" v-for="(bill, billIndex) in item.bills"
                  :key="billIndex">
              <view class="flex justify-between items-center w-100p mb-15 text-25">
                <text class="font-bold">{{ bill.feeItemName }}</text>
                <text class="font-bold text-orange">￥{{ bill.billAmount }}</text>
              </view>
              <view class="flex justify-between items-center w-100p mb-15 text-25 text-gray">
                <text>{{ bill.feeStandardExplain }}</text>
              </view>
              <view class="flex justify-between items-center w-100p mb-15 text-25 text-gray">
                <text>{{ bill.billName }}</text>
              </view>
              <view class="flex justify-between items-center w-100p mb-15 text-25 ">
                <text class="text-gray">缴费数量({{ bill.amount }})*单价({{ bill.feeStandardValue }})</text>
                <text>￥{{ bill.billAmount }}</text>
              </view>
              <template v-if="bill.feeStandardExplain.includes('电费') || bill.feeStandardExplain.includes('水费')">
                <view class="flex justify-between items-center w-100p mb-15 text-25 text-gray">
                  <text class="text-gray">上期抄表数:</text>
                  <text>{{ bill.lastMeterNum }}</text>
                </view>
                <view class="flex justify-between items-center w-100p mb-15 text-25 text-gray">
                  <text class="text-gray">本期抄表数:</text>
                  <text>{{ bill.nowMeterNum }}</text>
                </view>
              </template>
              <view class="flex justify-between items-center w-100p mb-15 text-25 text-green" v-if="!!bill.payItem">
                <text>支付时间:</text>
                <text>{{ dayjs(bill.payItem.payTime).format('YYYY-MM-DD HH:mm:ss') }}</text>
              </view>
            </view>
          </view>
        </view>
      </template>
      <view class="flex flex-col justify-center items-center mt-50" v-else>
        <u-icon name="/static/empty-bill.png" size="200rpx"/>
        <text class="text-gray mt-20">暂无账单</text>
      </view>
    </view>
    <view class="footer" v-if="billState === 0">
      <view class="m-30">
        <view class="bg-white circle p-30 flex justify-between items-center">
          <view class="flex justify-start items-center flex-1 mx-25">
            <text>合计:</text>
            <text class="text-orange text-30 font-bold ml-15">￥{{ totalAmount }}</text>
          </view>
          <view class=" flex-1 mx-25">
            <u-button type="primary" shape="circle" :disabled="totalAmount <= 0" @click="payBill">立即缴费</u-button>
          </view>
        </view>
      </view>
    </view>
    <u-picker :show="showRoom" :columns="[roomList]" keyName="title" @confirm="selectRoom"
              @cancel="showRoom = true"/>
  </view>
</template>

<script>
import {listBillReq, makePayReq} from "@/api/bill";
import {roomListReq} from "@/api/room";
import {MAIN} from "@/config/color";
import dayjs from "dayjs";

export default {
  computed: {
    dayjs() {
      return dayjs
    }
  },
  data() {
    return {
      roomList: [],
      billList: [],
      currentRoom: null,
      showRoom: false,
      totalAmount: 0,
      billState: 0,
      subsection: ['未缴费', '已缴费']
    }
  },
  methods: {
    MAIN() {
      return MAIN
    },
    goBack() {
      uni.navigateBack();
    },
    async getRoomList() {
      const {data} = await roomListReq()
      this.roomList = data.map(item => {
        item.title = ''
        if (item.villageName) item.title += item.villageName
        if (item.buildingName) item.title += `-${item.buildingName}`
        if (item.unitName) item.title += `-${item.unitName}`
        if (item.roomNumber) item.title += `-${item.roomNumber}`
        return item
      })
      if (this.roomList.length) {
        this.currentRoom = this.roomList[0]
        await this.getBillData()
      }
    },
    changeShow(index) {
      this.billList[index].show = !this.billList[index].show
    },
    changeSelect(index) {
      this.billList[index].selected = !this.billList[index].selected
      this.calTotalAmount()
    },
    onChangeSubsection(val) {
      this.billState = val
      this.getBillData()
    },
    selectRoom({value}) {
      this.currentRoom = value[0]
      this.getBillData()
      this.showRoom = false
    },
    async getBillData() {
      this.billList = []
      this.totalAmount = 0
      const params = {
        roomIdList: this.currentRoom.baseRoomRoomCode,
        billState: this.billState + 2
      }
      try {
        const {data} = await listBillReq(params);
        this.billList = data.map(item => {
          item.show = true
          item.selected = true
          item.totalAmount = 0
          item.bills.map(bill => {
            item.totalAmount += bill.billAmount
            return bill
          })
          return item
        })
        this.calTotalAmount()
        console.log(this.billList)
      } catch (error) {
        console.error('获取账单数据失败：', error);
      }
    },
    calTotalAmount() {
      this.totalAmount = 0
      this.billList.map(item => {
        if (item.selected) {
          this.totalAmount += item.totalAmount
        }
      })
    },
    async payBill() {
      uni.showLoading({title: '支付中'})
      const idList = []
      this.billList.map(item => {
        if (item.selected) {
          item.bills.map(bill => {
            idList.push(bill.id)
          })
        }
      })
      const payRes = await makePayReq({
        idList
      }).finally(() => uni.hideLoading())
      const jsonData = JSON.parse(payRes.message)
      const miniPayReq = jsonData.miniPayRequest
      const _this = this
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: miniPayReq.timeStamp,
        nonceStr: miniPayReq.nonceStr,
        package: miniPayReq.package,
        signType: miniPayReq.signType,
        paySign: miniPayReq.paySign,
        success: function (res) {
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          });
          _this.getBillData()
        },
        fail: function (err) {
          console.log('支付失败', err);
        }
      })
    }
  },
  onLoad() {
    this.getRoomList();
  }
}
</script>

<style scoped lang="scss">
</style>
