<template>
  <view class="container">
    <u-sticky offsetTop="0rpx" customNavHeight="0rpx">

      <view class="sticky-container">
        <view class="search-view">
          <u-input v-model="queryParams.creditCardName" border="false" type="select" @click="handleCreditCard" placeholder="请选择信用卡" suffixIcon="search"
            suffixIconStyle="color: #909399" class="search-input">
          </u-input>
          <view class="add-btn" @click="handleAdd()">
            <uni-icons type="plusempty" size="18" color="#667eea"></uni-icons>
            <text>新增</text>
          </view>
        </view>
        
        <view class="filter-view">
          <view class="filter-title">账单状态：</view>
          <view class="type-list">
            <view class="type-item" :class="!queryParams.billState ? 'active' : ''" @click="selectStatus('')">
              <text>全部</text>
            </view>
            <view v-for="item in billStateList" :key="item.dictValue" class="type-item"
              :class="queryParams.billState === item.dictValue ? 'active' : ''" @click="selectStatus(item.dictValue)">
              <text>{{ item.dictLabel }}</text>
            </view>
          </view>
        </view>
      </view>
    </u-sticky>
    <u-list @scrolltolower="loadmore" :spaceHeight="116" lowerThreshold="100">
      <u-list-item v-for="(item, index) in listData" :key="index">
        <view class="list-item" @click="enterDetails(item)">
          <view class="item-header">
            <view class="header-row">
              <view class="card-icon">
                <uni-icons type="wallet-filled" size="20" color="#ffffff"></uni-icons>
              </view>
              <text class="card-name">{{ item.bankNameCode }}</text>
              <view class="bill-state-tag" v-if="item.billState" :class="getBillStateClass(item.billState)">
                <text>{{ dictStr(item.billState, billStateList) }}</text>
              </view>
              <text class="bill-amount">{{ item.billAmount }}元</text>
            </view>
            <view class="info-row">
              <text class="time-text">账单日 {{ item.billDate }}</text>
              <view class="available-amount">
                <text class="amount-label">可用</text>
                <text class="amount-value">{{ item.availableLimit }}元</text>
              </view>
            </view>
          </view>
          
          <view class="card-body">
            <view class="info-item">
              <text class="info-label">还款日</text>
              <text class="info-value">{{ item.repaymentDay }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">账单周期</text>
              <text class="info-value">{{ item.billDatePeriod }}</text>
            </view>
          </view>
          
          <view class="last-trans-section" v-if="auth.hasPermi('invest:posmachine:list')">
            <view class="info-item">
              <text class="info-label">最近交易时间</text>
              <text class="info-value">{{ item.recentDealTime || '-' }}</text>
            </view>
          </view>
          
          <view class="stats-body" v-if="auth.hasPermi('invest:posmachine:list')">
            <view class="stats-row">
              <view class="stats-item">
                <text class="stats-label">POS机刷卡</text>
                <text class="stats-value">{{ item.posCount || 0 }}次</text>
              </view>
              <view class="stats-item">
                <text class="stats-label">日常支出</text>
                <text class="stats-value">{{ item.dailyExpensesCount || 0 }}次</text>
              </view>
              <view class="stats-item">
                <text class="stats-label">POS占比</text>
                <text class="stats-value percent">{{ item.posRate || 0 }}</text>
              </view>
            </view>
          </view>
          
          <view class="operate" @click.stop>
            <view class="btn-detail" @click="enterDetails(item)">
              <uni-icons type="list" size="16" color="#52c41a"></uni-icons>
              <text>账单明细</text>
            </view>
            <view class="btn-edit" @click="handleEdit(item)">
              <uni-icons type="compose" size="16" color="#667eea"></uni-icons>
              <text>修改</text>
            </view>
            <view class="btn-delete" @click="handleDelete(item)">
              <uni-icons type="trash" size="16" color="#f5576c"></uni-icons>
              <text>删除</text>
            </view>
          </view>
        </view>
      </u-list-item>
      <view>
      </view>
      <u-loadmore :status="status" loadingIcon="semicircle" height="88" fontSize="32rpx" @loadmore="loadmore" />
    </u-list>
    <u-picker itemHeight="88" :show="settingPickShow" :columns="settingColumns" keyName="settingName"
      @confirm="settingConfirm" @cancel="settingCancel"></u-picker>
      <u-picker itemHeight="88" :show="showCreditCard" :columns="bankCardLendList" keyName="nameCode" @cancel="handleCreditCardCancel"
        @confirm="handleCreditCardConfirm"></u-picker>
  </view>
  <!-- 悬停按钮返回工作台-->
  <suspend></suspend>
  <refresh></refresh>
</template>

<script setup>
import { listCreditCardBill, delCreditCardBill } from '@/api/invest/creditCardBill'
import { getDicts } from '@/api/system/dict/data.js'
import auth from "@/plugins/auth"; // 建议使用auth进行鉴权操作
import { listAccounts } from '@/api/invest/accounts'
import {onLoad,onShow} from "@dcloudio/uni-app";
    // 计算属性与监听属性是在vue中而非uniap中 需要注意！！！
import {reactive ,toRefs,ref,computed }from "vue";
const pageNum = ref(1)
const listData = ref([])
const isShow = ref(false)
const status = ref('loadmore')
const billStateList = ref([])
const settingPickShow = ref(false)
const settingColumns = ref([])
const showCreditCard = ref(false)
const bankCardLendList = ref([])
const data = reactive({
  queryBankCardLendParams: {
    pageNum: 1,
    type: '2',
    status: '1',
    pageSize: 100
  },
  queryParams: {
    creditCardId: null,
    name: '',
    type: '',
    billState: '0' // 默认未出账单
  } 
})
const { queryBankCardLendParams, queryParams} = toRefs(data)	
onLoad(() => {
    getDict()
    getList()
  });

 onShow(() => {
    if (isShow.value) {
      listData.value=[]
      getList()
      isShow.value = false
    }
  });

function loadmore() {
      pageNum.value += 1
      if (status.value == 'loadmore') {
        getList()
      }
    }
function getList() {
      status.value = 'loading'
      listCreditCardBill({ pageSize: 10, pageNum: pageNum.value, ...queryParams.value }).then(res => {
        listData.value = listData.value.concat(res.rows)
        if (listData.value.length < res.total) {
          status.value = 'loadmore'
        } else {
          status.value = 'nomore'
        }
      }).catch(() => {
        status.value = 'nomore'
      })
    }
function   getDict() {
  listAccounts(queryBankCardLendParams.value).then((response) => {
        bankCardLendList.value = [response.rows] 
      })
      // 账单状态
      getDicts('bill_state').then(res => {
        billStateList.value = res.data
      })
    }
    
function settingConfirm(e) {
      queryParams.value.settingId = e.value[0].settingId
      queryParams.value.settingName = e.value[0].settingName
      settingPickShow.value = false
    }
function settingCancel() {
      settingPickShow.value = false
    }
function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
    }
function selectStatus(value) {
      queryParams.value.billState = value
      pageNum.value = 1
      listData.value = []
      getList()
    }
    function handleCreditCard() {
        if (bankCardLendList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '信用卡为空  ', type: 'warning'
          })
        } else {
          showCreditCard.value = true
        }
     }
  function   handleCreditCardConfirm(e) {
    queryParams.value.creditCardName = e.value[0].nameCode
    queryParams.value.creditCardId= e.value[0].id
        showCreditCard.value = false
        pageNum.value = 1
      listData.value = []
      getList()
  }
 function handleCreditCardCancel() {
       showCreditCard.value = false
  }
    function resetQuery() {
        queryParams.value.name = ''
        queryParams.value.creditCardName = ''
        queryParams.value.creditCardId = ''
        queryParams.value.billState = ''
        queryParams.value.type = ''
        pageNum.value = 1
        listData.value = []
        getList()
    }
    
    const getBillStateClass = (billState) => {
      // 根据实际的字典值判断
      // 通常: 0-未出账单, 1-已出账单, 2-已还款等
      if (billState === '0') {
        return 'status-unpaid'  // 未出账单 - 橙色
      } else if (billState === '1') {
        return 'status-billed'  // 已出账单 - 绿色
      } else {
        return 'status-paid'    // 已还款等其他状态 - 蓝色
      }
    }
    
    function enterDetails(item) {
      uni.navigateTo({ url: `/pages/work/bill/creditCardBill/details?id=${item.creditCardId}&billDatePeriod=${item.billDatePeriod}` })
    }
    function handleEdit(item) {
      uni.navigateTo({ url: `/pages/work/bill/creditCardBill/addEdit?id=${item.id}` })
      isShow.value = true
    }
    function handleAdd() {
      uni.navigateTo({ url: `/pages/work/bill/creditCardBill/addEdit` })
      isShow.value = true
    }
    
    function handleDelete(item) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条记录吗？',
        confirmText: '删除',
        cancelText: '取消',
        confirmColor: '#f5576c',
        cancelColor: '#909399',
        success: function (res) {
          if (res.confirm) {
            delCreditCardBill(item.id).then(() => {
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
              pageNum.value = 1
              listData.value = []
              getList()
            })
          }
        }
      });
    }
	
</script>

<style lang="scss" scoped>
page {
  height: 100%;
  overflow: auto;
}

.container {
  background-color: #f5f7fa;
}

.sticky-container {
  background-color: #f5f7fa;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.btnAdd {
      width: 146rpx;
      height: 56rpx;
      line-height: 56rpx;
      border-radius: 8rpx;
      display:float;
      text-align: center;
    }

.search-view {
  padding: 12rpx 32rpx;
  background-color: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  z-index: 100;

  .search-input {
    background: rgba(102, 126, 234, 0.08);
    color: #333333;
    flex: 1;
    margin-right: 16rpx;
    border-radius: 24rpx;
    border: 2rpx solid rgba(102, 126, 234, 0.3);
  }
  
  .add-btn {
    display: flex;
    align-items: center;
    gap: 6rpx;
    padding: 12rpx 24rpx;
    background: rgba(102, 126, 234, 0.08);
    border-radius: 24rpx;
    border: 2rpx solid rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
    flex-shrink: 0;
    
    &:active {
      transform: scale(0.95);
      background: rgba(102, 126, 234, 0.12);
    }
    
    text {
      color: #667eea;
      font-size: 28rpx;
      font-weight: 600;
    }
    
    uni-icons {
      color: #667eea;
    }
  }
}

.filter-view {
  padding: 16rpx 32rpx 20rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  gap: 16rpx;
  
  .filter-title {
    color: #333333;
    font-size: 28rpx;
    font-weight: 600;
    flex-shrink: 0;
  }
  
  .type-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
    flex: 1;
    
    .type-item {
      padding: 0 24rpx;
      height: 60rpx;
      line-height: 60rpx;
      border-radius: 30rpx;
      font-size: 26rpx;
      color: #666666;
      background: #f5f7fa;
      border: 2rpx solid transparent;
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.95);
      }
      
      &.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #ffffff;
        font-weight: 600;
        box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
      }
    }
  }
}

.list-item {
  margin: 0 24rpx 24rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);

  .item-header {
    display: flex;
    flex-direction: column;
    gap: 12rpx;
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

    .header-row {
      display: flex;
      align-items: center;
      gap: 10rpx;
    }

    .card-icon {
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.25);
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
    }

    .card-name {
      font-size: 28rpx;
      font-weight: 600;
      color: #ffffff;
      line-height: 1.3;
      flex: 1;
      min-width: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .bill-state-tag {
      padding: 4rpx 12rpx;
      border-radius: 10rpx;
      font-size: 22rpx;
      font-weight: 600;
      line-height: 1;
      flex-shrink: 0;
      margin-right: 10rpx;
      
      &.status-unpaid {
        background: rgba(250, 140, 22, 0.35);
        
        text {
          color: #ffffff;
        }
      }
      
      &.status-billed {
        background: rgba(82, 196, 26, 0.35);
        
        text {
          color: #ffffff;
        }
      }
      
      &.status-paid {
        background: rgba(24, 144, 255, 0.35);
        
        text {
          color: #ffffff;
        }
      }
    }

    .available-amount {
      display: flex;
      align-items: baseline;
      gap: 6rpx;
      flex-shrink: 0;
    }

    .amount-label {
      font-size: 22rpx;
      color: rgba(255, 255, 255, 0.75);
      font-weight: 400;
    }

    .amount-value {
      font-size: 32rpx;
      font-weight: 700;
      color: #52c41a;
      line-height: 1.2;
    }

    .bill-amount {
      font-size: 32rpx;
      font-weight: 700;
      color: #fa8c16;
      line-height: 1.2;
      flex-shrink: 0;
    }

    .info-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 12rpx;
      padding-top: 12rpx;
      border-top: 1rpx solid rgba(255, 255, 255, 0.2);
    }

    .time-text {
      font-size: 26rpx;
      color: rgba(255, 255, 255, 0.85);
      font-weight: 500;
      line-height: 1.3;
      flex: 1;
    }

  }

  .last-trans-section {
    padding: 0 24rpx 24rpx;
    background: #fff;
    
    .info-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 8rpx;
      min-width: 0;

      .info-label {
        font-size: 24rpx;
        color: #667eea;
        font-weight: 500;
        background: rgba(102, 126, 234, 0.08);
        padding: 6rpx 12rpx;
        border-radius: 8rpx;
        align-self: flex-start;
      }

      .info-value {
        font-size: 26rpx;
        color: #333;
        font-weight: 500;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .stats-body {
    padding: 20rpx 24rpx;
    background: #f5f7fa;
    display: flex;
    flex-direction: column;
    gap: 16rpx;
    border-top: 1rpx solid #e8edf3;
  }

  .stats-row {
    display: flex;
    gap: 24rpx;
    align-items: flex-start;
  }

  .stats-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8rpx;
    min-width: 0;
    align-items: flex-start;

    .stats-label {
      font-size: 22rpx;
      color: #667eea;
      font-weight: 500;
      background: rgba(102, 126, 234, 0.08);
      padding: 6rpx 12rpx;
      border-radius: 8rpx;
      white-space: nowrap;
    }

    .stats-value {
      font-size: 26rpx;
      color: #333;
      font-weight: 600;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
      
      &.percent {
        color: #667eea;
      }
    }
  }

  .card-body {
    padding: 24rpx;
    background: #fff;
    display: flex;
    gap: 16rpx;
  }

  .info-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8rpx;
    min-width: 0;

    .info-label {
      font-size: 22rpx;
      color: #667eea;
      font-weight: 500;
      background: rgba(102, 126, 234, 0.08);
      padding: 6rpx 12rpx;
      border-radius: 8rpx;
      align-self: flex-start;
    }

    .info-value {
      font-size: 26rpx;
      color: #333;
      font-weight: 500;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      
      &.highlight {
        color: #52c41a;
        font-weight: 600;
      }
    }
  }

  .operate {
    display: flex;
    justify-content: flex-end;
    padding: 16rpx 24rpx 24rpx;
    gap: 16rpx;

    .btn-detail,
    .btn-edit,
    .btn-delete {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6rpx;
      padding: 0 24rpx;
      height: 64rpx;
      border-radius: 12rpx;
      font-size: 26rpx;
      font-weight: 500;
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.95);
      }
    }
    
    .btn-detail {
      background: rgba(82, 196, 26, 0.1);
      color: #52c41a;
      border: 1rpx solid rgba(82, 196, 26, 0.3);
    }

    .btn-edit {
      background: rgba(102, 126, 234, 0.1);
      color: #667eea;
      border: 1rpx solid rgba(102, 126, 234, 0.3);
    }

    .btn-delete {
      background: rgba(245, 87, 108, 0.1);
      color: #f5576c;
      border: 1rpx solid rgba(245, 87, 108, 0.3);
    }
  }
}
</style>