<template>
  <view
    :style="{
      background: `linear-gradient(to bottom, #ff803a 0, #ff803a ${getNavBarHeight() * 2}px, #F7F7F7 ${getNavBarHeight() * 2}px, #F7F7F7 100%)`,
    }"
    class="page"
  >
    <!-- 头部区域 -->
    <custom-nav-bar
      :fill="false"
      :show-back="true"
      background-color="#ff803a"
      title="收支明细"
      title-color="white"
    ></custom-nav-bar>
    <view :style="{ height: getNavBarHeight() + 'px' }" class="fill"></view>
    <view
      :style="{
        height: getNavBarHeight() + 'px',
        top: getNavBarHeight() + 'px',
        background: '#ff803a',
      }"
      class="header"
    >
      <view class="all-type">
        <image :src="commonEnum.TYPE_SELECT" class="all-type-img" @click="openPopup">
          <text>{{ expenseType }}</text>
        </image>
      </view>
      <view class="cash-flow">
        <view class="date">
          <view class="uni-list-cell">
            <view class="uni-list-cell-db">
              <picker
                :end="endDate"
                :value="date"
                fields="month"
                mode="date"
                @change="bindDateChange"
              >
                <view class="uni-input">{{ date }}</view>
              </picker>
            </view>
          </view>
          <image :src="commonEnum.DOWN_ICON"></image>
        </view>
        <view class="cash-flow-detail">支出￥{{ expenditures }} 入账￥{{ Recorded }}</view>
      </view>
    </view>
    <view :style="{ height: getNavBarHeight() + 'px' }" class="fill"></view>

    <!-- 卡片区域 -->
    <view v-if="loading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>
    <view v-else-if="cardList.length === 0" class="empty-container">
      <text class="empty-text">暂无数据</text>
    </view>
    <cash-flow-card v-for="(item, index) in cardList" v-else :key="index" :cardData="item" />
  </view>
  <!-- 底部弹窗 -->
  <uni-popup ref="popup" :mask-click="true" type="bottom">
    <view class="popup-content">
      <!-- 弹窗标题栏 -->
      <view class="popup-header">
        <text class="close-icon" @click="closePopup">✕</text>
        <text class="title">请选择类型</text>
      </view>

      <!-- “全部类型”按钮 -->
      <button class="all-types-btn" @click="selectType('全部类型')">全部类型</button>

      <!-- 支出分类网格 -->
      <view class="type-grid">
        <view
          v-for="(type, index) in expenseTypes"
          :key="index"
          class="type-item"
          @click="selectType(type)"
        >
          {{ type }}
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<script>
import commonEnum from '../../enum/commonEnum'
import { getNavBarHeight } from '../../utils/system'
import uniPopup from '../../uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
import CashFlowCard from '../../components/cashFlowCard/cashFlowCard.vue'
import { getBalanceLogList } from '../../api/balanceLog'
import CustomNavBar4 from '../../components/custom-nav-bar4/custom-nav-bar4.vue'

export default {
  name: 'CashFlowPage',
  components: { CustomNavBar4, uniPopup, CashFlowCard },
  data() {
    const currentDate = this.getDate()
    return {
      getNavBarHeight,
      expenseType: '全部类型',
      expenditures: '',
      Recorded: '',
      date: currentDate,
      startDate: this.getDate('start'),
      endDate: this.getDate('end'),
      expenseTypes: ['提现', '订单'],
      cardList: [],
      loading: false,
    }
  },
  computed: {
    commonEnum() {
      return commonEnum
    },
  },
  onLoad() {
    this.loadBalanceLogData()
  },
  methods: {
    // 日期选择变化处理
    bindDateChange: function (e) {
      this.date = e.detail.value
      this.loadBalanceLogData()
    },
    getDate(type) {
      const date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() + 1

      if (type === 'start') {
        year = year - 10
      } else if (type === 'end') {
        // 结束日期设为当前时间
        return new Date().toISOString().split('T')[0]
      }
      month = month > 9 ? month : '0' + month
      return `${year}-${month}`
    },
    // 打开弹窗
    openPopup() {
      this.$refs.popup.open()
    },
    // 关闭弹窗
    closePopup() {
      this.$refs.popup.close()
    },
    // 选择类型
    selectType(type) {
      console.log('选择的类型：', type)
      this.expenseType = type
      this.closePopup()
      this.loadBalanceLogData()
    },

    // 加载余额日志数据
    async loadBalanceLogData() {
      if (this.loading) return

      this.loading = true
      try {
        // 获取当前时间的格式化字符串
        const now = new Date()
        const endTime = now.toISOString().slice(0, 19).replace('T', ' ')

        const params = {
          beginCreateTime: this.date + '-01 00:00:01',
          endCreateTime: this.date + '-31 00:00:01',
        }

        console.log('查询参数:', {
          beginCreateTime: params.beginCreateTime,
          endCreateTime: params.endCreateTime,
        })

        // 根据选择的类型添加筛选条件
        if (this.expenseType !== '全部类型') {
          if (this.expenseType === '提现') {
            params.bstType = 'WITHDRAW'
            console.log('查询类型: 提现')
          } else if (this.expenseType === '订单') {
            params.bstType = 'ORDER'
            console.log('查询类型: 订单')
          } else if (this.expenseType === '其他') {
            console.log('查询类型: 其他 (前端过滤)')
          }
        } else {
          console.log('查询类型: 全部类型')
        }

        const response = await getBalanceLogList(params)
        console.log('API响应:', response)

        if (response.code === 200 && response.data) {
          this.processBalanceLogData(response.data)
        } else {
          console.error('获取数据失败:', response.msg)
          uni.showToast({
            title: response.msg || '获取数据失败',
            icon: 'none',
          })
        }
      } catch (error) {
        console.error('API调用失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none',
        })
      } finally {
        this.loading = false
      }
    },

    // 处理余额日志数据
    processBalanceLogData(data) {
      this.cardList = data.map(item => {
        // 计算当日总支出和总收入
        const totalExpense = Math.abs(item.totalExpense || 0)
        const totalIncome = item.totalIncome || 0

        // 处理余额日志列表
        let items = item.balanceLogList.map(log => {
          const createTime = new Date(log.createTime)
          const time = createTime.toTimeString().substring(0, 5) // 获取 HH:mm 格式

          return {
            title: this.getTitleByBstType(log.bstType),
            status: this.getStatusByBstType(log.bstType),
            time: time,
            orderNumber: log.bstId,
            amount: log.amount,
            bstType: log.bstType, // 保留原始类型用于过滤
          }
        })

        // 格式化日期显示
        const date = this.formatDateForDisplay(item.createTime)

        return {
          date: date,
          outflow: totalExpense,
          inflow: totalIncome,
          items: items,
        }
      })

      // 更新页面显示的支出和收入金额
      this.updateTotalAmounts()
    },

    // 根据业务类型获取标题
    getTitleByBstType(bstType) {
      const titleMap = {
        WITHDRAW: '提现',
        ORDER: '订单',
      }
      return titleMap[bstType] || '其他'
    },

    // 根据业务类型获取状态
    getStatusByBstType(bstType) {
      const statusMap = {
        WITHDRAW: '',
        ORDER: '',
      }
      return statusMap[bstType] || ''
    },

    // 格式化日期显示
    formatDateForDisplay(dateString) {
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${year}年${month}月${day}日`
    },

    // 更新总金额显示
    updateTotalAmounts() {
      let totalExpense = 0
      let totalIncome = 0

      this.cardList.forEach(card => {
        totalExpense += card.outflow
        totalIncome += card.inflow
      })

      this.expenditures = totalExpense.toFixed(2)
      this.Recorded = totalIncome.toFixed(2)
    },
  },
}
</script>
<style lang="scss" scoped>
.page {
  position: relative;
  height: 100vh;
}

.header {
  z-index: 999;
  //background: #13c622;
  position: fixed;
  top: 0;
  width: 100%;
  display: flex;
  flex-direction: column;
  padding-left: 40rpx;

  .all-type {
    position: relative;
    display: flex;
    width: 276rpx;
    height: 65rpx;

    &-img {
      width: 276rpx;
      height: 65rpx;
      display: flex;

      text {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 65rpx;
        color: #ffffff;
        line-height: 65rpx;
        //border: red 1px solid;
        align-items: center;
        justify-content: center;
        padding-left: 40rpx;
      }
    }
  }

  .cash-flow {
    display: flex;
    align-items: center;
    //border: red 1px solid;

    .date {
      display: flex;
      color: white;
      align-items: center;

      image {
        width: 19px;
        height: 25rpx;
      }
    }

    .cash-flow-detail {
      margin-left: 22rpx;
      color: white;
      font-size: 24rpx;
    }
  }
}

view {
  // border: #16ff00 1px solid;
}

/* 弹窗内容样式 */
.popup-content {
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
  padding: 20rpx;
}

/* 弹窗标题栏 */
.popup-header {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  padding: 20rpx 0;
  border-bottom: #b8bed1 solid 1px;
  margin-bottom: 20rpx;
}

.close-icon {
  position: absolute;
  left: 20rpx;
  font-size: 32rpx;
  color: #999;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

/* “全部类型”按钮 */
.all-types-btn {
  background-color: #ff803a;
  color: #f5f5f5;
  //border-radius: 50rpx;
  margin: 0 0;
  width: 48%;
  height: 100rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 支出分类网格 */
.type-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 20rpx 0;
}

.type-item {
  width: 48%;
  height: 100rpx;
  background-color: #fff;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  box-shadow: #ff803a 0 2rpx 8rpx;
}

/* 加载和空状态样式 */
.loading-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;
  margin: 40rpx;
}

.loading-text,
.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>
