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

      <view class="search-view">
        <u--input v-model="queryParams.name" border="false" placeholder="请输入信用卡名称" class="search-input"
          @blur="searchBlur" suffixIcon="search" suffixIconStyle="color: #909399">
        </u--input>
        <view class="add-btn" @click="handleAdd()">
          <uni-icons type="plusempty" size="18" color="#667eea"></uni-icons>
          <text>新增</text>
        </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="vip-filled" size="20" color="#ffffff"></uni-icons>
              </view>
              <text class="card-name">{{ item.name }}</text>
              <text class="card-code" v-if="item.code">{{ item.code }}</text>
            </view>
            <view class="info-row">
              <text class="credit-limit">{{ item.creditLimit || 0 }}元</text>
              <text class="account-status" :class="getStatusClass(item.status, dictStr(item.status, statusList))">{{ dictStr(item.status, statusList) || '--' }}</text>
              <view class="balance-amount">
                <text class="balance-label">可用</text>
                <text class="balance-value">{{ item.availableLimit || 0 }}元</text>
              </view>
            </view>
          </view>
          
          <view class="card-body">
            <view class="info-row">
              <!-- <view class="info-item" v-if="item.creditLimit || true">
                <text class="info-label">信用额度</text>
                <text class="info-value primary">{{ item.creditLimit ? item.creditLimit + '元' : '--' }}</text>
              </view> -->
               <view class="info-item" v-if="item.balance || true">
                <text class="info-label">余额</text>
                <text class="info-value orange">{{ item.balance ? item.balance + '元' : '--' }}</text>
              </view>
              <!-- <view class="info-item" v-if="dictStr(item.status, statusList) || true">
                <text class="info-label">账户状态</text>
                <text class="info-value" :class="getStatusClass(item.status, dictStr(item.status, statusList))">{{ dictStr(item.status, statusList) || '--' }}</text>
              </view> -->
               <view class="info-item" v-if="item.bankName || true">
                <text class="info-label">银行</text>
                <text class="info-value">{{ item.bankName || '--' }}</text>
              </view>
              <view class="info-item" v-if="item.billDateName || true">
                <text class="info-label">账单日</text>
                <text class="info-value">{{ item.billDateName || '--' }}</text>
              </view>
              <view class="info-item" v-if="item.payDateName || true">
                <text class="info-label">还款日</text>
                <text class="info-value">{{ item.payDateName || '--' }}</text>
              </view>
              <view class="info-item" v-if="item.delayPeriod || true">
                <text class="info-label">延缓期限</text>
                <text class="info-value">{{ item.delayPeriod || '--' }}</text>
              </view>
              <view class="info-item" v-if="item.activationDate || true">
                <text class="info-label">开户日期</text>
                <text class="info-value">{{ item.activationDate || '--' }}</text>
              </view>
              <view class="info-item" v-if="item.effectiveDate || true">
                <text class="info-label">有效期</text>
                <text class="info-value">{{ item.effectiveDate || '--' }}</text>
              </view>
              <view class="info-item" v-if="dictStr(item.isNextBillDate, isNextBillDateList) || true">
                <text class="info-label">账单日消费</text>
                <text class="info-value">{{ dictStr(item.isNextBillDate, isNextBillDateList) || '--' }}</text>
              </view>
              <view class="info-item" v-if="dictStr(item.isZeroBill, isZeroBillList) || true">
                <text class="info-label">0账单操作</text>
                <text class="info-value">{{ dictStr(item.isZeroBill, isZeroBillList) || '--' }}</text>
              </view>
             
              <view class="info-item" v-if="dictStr(item.cardTier, cardTierList) ">
                <text class="info-label">卡片等级</text>
                <text class="info-value">{{ dictStr(item.cardTier, cardTierList) }}</text>
              </view>
              <view class="info-item" v-if="item.cardFace">
                <text class="info-label">卡面</text>
                <text class="info-value">{{ item.cardFace }}</text>
              </view>
              <view class="info-item info-item-full" v-if="item.remark">
                <text class="info-label">备注</text>
                <text class="info-value">{{ item.remark }}</text>
              </view>
            </view>
          </view>
          
          <view class="operate" @click.stop>
            <view class="btn-limit" @click="handleLimitHistory(item)">
              <uni-icons type="list" size="16" color="#fa8c16"></uni-icons>
              <text>调额记录</text>
            </view>
            <view class="btn-repay" @click="handleRepay(item)">
              <uni-icons type="redo" size="16" color="#52c41a"></uni-icons>
              <text>还款</text>
            </view>
            <view class="btn-deal" @click="handleAddDeal(item)">
              <uni-icons type="cart" size="16" color="#1890ff"></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>
  </view>
  <!-- 悬停按钮返回工作台-->
  <suspend></suspend>
  <refresh></refresh>
</template>

<script setup>
import { listBankcardLend,delBankcardLend} from '@/api/invest/bankcardlend'
import { getDicts } from '@/api/system/dict/data.js'
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 isNextBillDateList = ref([])
const isZeroBillList = ref([])
const statusList = ref([])
const cardTierList = ref([])
const settingPickShow = ref(false)
const settingColumns = ref([])
const flag = ref('list')
const data = reactive({
  filterPanel: false,
  queryParams: {
    name: null,
    type: '2'
   } 
})
const { filterPanel, queryParams} = toRefs(data)
const windowHeight = computed(() => {
			uni.getSystemInfoSync().windowHeight - 50
		})	
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'
      listBankcardLend({ 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() {
      // 类型
      getDicts('is_next_bill_date').then(res => {
        isNextBillDateList.value = res.data
      })
       // 类型
       getDicts('is_zero_bill').then(res => {
        isZeroBillList.value = res.data
      })
       // 账户状态
       getDicts('account_status').then(res => {
        statusList.value = res.data
      })
       // 卡片等级
       getDicts('card_tier').then(res => {
        cardTierList.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 formatCardCode(code) {
      if (!code) return ''
      // 去除所有空格和特殊字符
      const cleanCode = code.replace(/\s+/g, '')
      // 如果卡号长度小于等于4位，直接返回
      if (cleanCode.length <= 4) return code
      // 只显示后4位，前面用 XX 替代
      const suffix = cleanCode.substring(cleanCode.length - 4)
      return `${suffix}`
    }
    
    function getStatusClass(status, statusText) {
     // 根据状态值判断
  const statusStr = String(status)
  if (statusStr === '1') {
    return 'status-normal'
  }
  if (statusStr === '5') {
    return 'status-error'
  }
  
  return 'status-default'
    }
    function searchBlur() {
      pageNum.value = 1
      listData.value = []
      getList()
    }
    function resetQuery() {
        queryParams.value.name = '',
        queryParams.value.type = '2'
      isNextBillDateList.value.map(ele => {
        Reflect.set(ele, 'selected', false)
      })
    }
    function enterDetails(item) {
      uni.navigateTo({ url: `/pages/work/base/creditCard/details?id=${item.id}` })
    }
    function handleEdit(item) {
      uni.navigateTo({ url: `/pages/work/base/creditCard/addEdit?id=${item.id}` })
      isShow.value = true
    }
    function handleAdd() {
      uni.navigateTo({ url: `/pages/work/base/creditCard/addEdit` })
      isShow.value = true
    }
    function handleLimitHistory(item) {
      uni.navigateTo({ url: `/pages/work/base/creditCard/limitHistory?bankCardLendId=${item.id}&name=${item.name}` })
      isShow.value = true
    }
    function handleDelete(item) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条记录吗？',
        confirmText: '删除',
        cancelText: '取消',
        confirmColor: '#f5576c',
        cancelColor: '#909399',
        success: function (res) {
          if (res.confirm) {
            delBankcardLend(item.id).then(() => {
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
              pageNum.value = 1
              listData.value = []
              getList()
            })
          }
        }
      });
    }
    
    function handleAddDeal(item) {
      // 构建URL参数：账户ID（信用卡ID）、账户类型（信用卡type=2）
      let url = `/pages/work/accounts/accountDealRecord/addEdit?accountId=${item.id}&accountType=2`
      
      uni.navigateTo({ url })
      isShow.value = true
    }
    
    function handleRepay(item) {
      // 跳转到信用卡还款页面，传递信用卡ID
      uni.navigateTo({ 
        url: `/pages/work/accounts/creditTransferRecord/addEdit?creditCardId=${item.id}` 
      })
      isShow.value = true
    }
	
</script>

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

.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;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

  .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);
    height: 66rpx !important;
    display: flex;
    align-items: center;
  }
  
  .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-panel {
    width: 100%;
    position: absolute;
    left: 0;
    top: 96rpx;
    background-color: rgba(0, 0, 0, 0.5);

    .filter-panel-content {
      background-color: #ffff;
      padding: 0 30rpx 30rpx;

      .filter-title {
        color: #000000;
        font-size: 30rpx;
        font-weight: 500;
        padding: 30rpx 0;
      }

      .state-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;

        .state-item {
          width: 210rpx;
          height: 72rpx;
          border: 1rpx solid rgba(0, 0, 0, 0.25);
          border-radius: 72rpx;
          text-align: center;
          line-height: 72rpx;
          margin: 0 20rpx 20rpx 0;
          font-size: 28rpx;
          color: #000000;
        }

        .active {
          background-color: rgba(222, 241, 255, 1);
          border: 1rpx solid rgba(22, 119, 255, 1);
        }
      }
    }

    .btn-box {
      display: flex;
      padding: 24rpx 30rpx;
      background-color: #fff;
      box-shadow: 0rpx -10rpx 20rpx #EEEEEE;
    }
  }
}

.list-item {
  margin: 10rpx 24rpx;
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.99);
  }

  .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;
      background: rgba(255, 255, 255, 0.25);
      border-radius: 50%;
      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;
    }
    
    .card-code {
      font-size: 30rpx;
      color: rgba(255, 255, 255, 0.75);
      font-weight: 400;
      line-height: 1.3;
      letter-spacing: 0.5rpx;
      
      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);
    }
    
    .credit-limit {
      font-size: 24rpx;
      color: #667eea;
      font-weight: 600;
      line-height: 1.3;
      flex-shrink: 0;
      background: rgba(255, 255, 255, 0.9);
      padding: 4rpx 12rpx;
      border-radius: 8rpx;
    }
    
    .account-status {
      font-size: 24rpx;
      font-weight: 500;
      line-height: 1.3;
      flex: 1;
      text-align: center;
      
      &.status-normal {
        color: #52c41a;
      }
      
      &.status-error {
        color: #ff4d4f;
      }
      
      &.status-default {
        color: rgba(255, 255, 255, 0.7);
      }
    }
    
    .balance-amount {
      display: flex;
      align-items: baseline;
      gap: 6rpx;
      flex-shrink: 0;
    }

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

    .balance-value {
      font-size: 32rpx;
      font-weight: 700;
      color: #fa8c16;
      line-height: 1.2;
    }
  }
  
  .card-body {
    padding: 24rpx;
    background: #fafbfc;
    border: 2rpx solid #f0f2f5;
    margin: 15rpx 16rpx 2rpx;
    border-radius: 12rpx;
  }

  .info-row {
    display: flex;
    flex-wrap: wrap;
    gap: 24rpx;
    margin-bottom: 0;

    .info-item {
      flex: 0 0 calc(50% - 12rpx);
      display: flex;
      flex-direction: column;
      gap: 4rpx;
      min-width: 0;
      margin-bottom: -5rpx;
      
      &.info-item-full {
        flex: 0 0 100%;
      }

      .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;
        flex: 1;
        line-height: 1.5;
        word-break: break-all;
        
        &.primary {
          color: #667eea;
        }
        
        &.orange {
          color: #fa8c16;
          font-weight: 600;
        }
        
        &.status-normal {
          color: #52c41a;
        }
        
        &.status-error {
          color: #ff4d4f;
        }
        
        &.status-default {
          color: #666666;
        }
      }
      
      &:not(.info-item-full) .info-value {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

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

    .btn-deal,
    .btn-repay,
    .btn-limit,
    .btn-edit,
    .btn-delete {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4rpx;
      padding: 0 14rpx;
      height: 60rpx;
      border-radius: 10rpx;
      font-size: 24rpx;
      font-weight: 500;
      border: 1rpx solid;
      transition: all 0.3s ease;
      white-space: nowrap;
      flex-shrink: 0;
      
      &:active {
        transform: scale(0.95);
      }
    }
    
    .btn-deal {
      background: rgba(24, 144, 255, 0.1);
      color: #1890ff;
      border: 2rpx solid #1890ff;
      font-weight: 600;
    }
    
    .btn-repay {
      background: rgba(82, 196, 26, 0.1);
      color: #52c41a;
      border: 2rpx solid #52c41a;
      font-weight: 600;
    }
    
    .btn-limit {
      background: rgba(250, 140, 22, 0.1);
      color: #fa8c16;
      border-color: rgba(250, 140, 22, 0.3);
    }
    
    .btn-edit {
      background: rgba(102, 126, 234, 0.1);
      color: #667eea;
      border-color: rgba(102, 126, 234, 0.3);
    }
    
    .btn-delete {
      background: rgba(245, 87, 108, 0.1);
      color: #f5576c;
      border-color: rgba(245, 87, 108, 0.3);
    }
  }
}
</style>