<template>
  <view class="container">
    <u-navbar
      leftIconSize="40rpx"
      leftIconColor="#333333"
      title="还款明细"
    >
    </u-navbar>
    
    <u-sticky offsetTop="0rpx" customNavHeight="0rpx">

      <view class="search-view">
        <u-input v-model="queryParams.name" border="false" :disabled="true" type="select" v-show="true" class="search-input">
        </u-input>
          <view class="summary-btn" @click="handleUpdateInterest()">
            <uni-icons type="checkmarkempty" size="18" color="#667eea"></uni-icons>
            <text>总利息汇总</text>
          </view>
      </view>
    </u-sticky>
    <u-list @scrolltolower="loadmore" :spaceHeight="116" lowerThreshold="100" :scroll-into-view="scrollIntoView">
      <u-list-item v-for="(item, index) in listData" :key="index">
        <view class="list-item" :class="index === firstUnpaidIndex ? 'highlight-item' : ''" :id="'item-' + index">
          <view class="item-header">
            <view class="header-row">
              <view class="card-icon">
                <uni-icons type="calendar" size="20" color="#ffffff"></uni-icons>
              </view>
              <text class="account-name">{{ item.repaymentAccountName }}</text>
              <text class="status-badge" :class="item.postingState === '1' ? 'paid' : 'unpaid'">{{ dictStr(item.postingState, postingStateList) }}</text>
            </view>
            <view class="info-row">
              <text class="time-text">{{ item.repaymentDate }}</text>
              <text class="type-text">第{{ item.periods }}期</text>
              <text class="amount-value" :class="item.postingState === '1' ? 'paid' : 'unpaid'">{{ item.currentAmount }}元</text>
            </view>
          </view>
          
          <view class="card-body">
            <view class="info-item">
              <text class="info-label">应还本金</text>
              <text class="info-value orange">{{ item.principal }}元</text>
            </view>
            <view class="info-item">
              <text class="info-label">利息</text>
              <text class="info-value orange">{{ item.interest }}元</text>
            </view>
          </view>
          
          <view class="operate" @click.stop v-if="item.postingState !== '1'">
            <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 class="operate" @click.stop v-else>
            <view class="btn-view" @click="handleView(item)">
              <uni-icons type="eye" size="16" color="#52c41a"></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-toast ref="uToast"></u-toast>
    <u-picker itemHeight="88" :show="settingPickShow" :columns="settingColumns" keyName="settingName"
      @confirm="settingConfirm" @cancel="settingCancel"></u-picker>
  </view>
    <!-- 悬停按钮返回工作台-->
    <suspend></suspend>
</template>

<script setup>
import {
  listInstallmentDetail,
  delInstallmentDetail
} from '@/api/invest/installmentDetail'
import {
  getInstallmentHistory,
  updateInstallmentHistory
} from '@/api/invest/installmentHistory'
import { getDicts } from '@/api/system/dict/data.js'
import {onLoad,onShow} from "@dcloudio/uni-app";
    // 计算属性与监听属性是在vue中而非uniap中 需要注意！！！
import {reactive ,toRefs,ref }from "vue";
const pageNum = ref(1)
const listData = ref([])
const isShow = ref(false)
const status = ref('loadmore')
const postingStateList = ref([])
const settingPickShow = ref(false)
const settingColumns = ref([])
const scrollIntoView = ref('')
const firstUnpaidIndex = ref(-1)
const data = reactive({
  form: {},
  queryParams: {
    name: null,
    type: null,
    time: '',
    installmentHistoryId: null,
    dealType: null,
    dealCategory: null
   } 
})
const { queryParams,form} = toRefs(data)
onLoad((option) => {
  queryParams.value.installmentHistoryId = option.id
  queryParams.value.name = option.name
  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'
      listInstallmentDetail({ pageSize: 100, 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'
        }
        // 查找第一条未还款的数据
        scrollToFirstUnpaid()
      }).catch(() => {
        status.value = 'nomore'
      })
    }

// 滚动到最近一条未还款的数据
function scrollToFirstUnpaid() {
  // 查找所有未还款的记录
  const unpaidRecords = listData.value
    .map((item, index) => ({ ...item, originalIndex: index }))
    .filter(item => item.postingState !== '1')
  
  if (unpaidRecords.length === 0) return
  
  // 获取当前日期
  const now = new Date()
  
  // 找到距离当前日期最近的未还款记录
  let closestRecord = unpaidRecords[0]
  let minDiff = Math.abs(new Date(unpaidRecords[0].repaymentDate) - now)
  
  unpaidRecords.forEach(record => {
    const recordDate = new Date(record.repaymentDate)
    const diff = Math.abs(recordDate - now)
    if (diff < minDiff) {
      minDiff = diff
      closestRecord = record
    }
  })
  
  const index = closestRecord.originalIndex
  firstUnpaidIndex.value = index
  
  // 延迟执行，确保 DOM 渲染完成
  setTimeout(() => {
    scrollIntoView.value = 'item-' + index
    
    // 3秒后移除高亮效果
    setTimeout(() => {
      firstUnpaidIndex.value = -1
      scrollIntoView.value = ''
    }, 3000)
  }, 800)
}
function   getDict() {
       // 交易类型
       getDicts('repayment_state').then(res => {
        postingStateList.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 handleUpdateInterest() {
  let totalInterest = 0
  for (let i = 0; i < listData.value.length; i++) {
    if (listData.value[i].interest) {
      totalInterest = totalInterest + listData.value[i].interest
    }
  }
  getInstallmentHistory(queryParams.value.installmentHistoryId).then((response) => {
    form.value = response.data
    form.value.totalInterest = totalInterest
    if (form.value.id != null) {
      updateInstallmentHistory(form.value).then((response) => {
        uni.showToast({
	title: '总利息汇总成功！',
	duration: 2000
});
      })
    }
  })
}
    function handleEdit(item) {
      uni.navigateTo({ url: `/pages/work/bill/onlineLendHistory/detailsAddEdit?id=${item.id}&installmentHistoryId=${queryParams.value.installmentHistoryId}&name=${queryParams.value.name}` })
      isShow.value = true
    }
    function handleView(item) {
      uni.navigateTo({ url: `/pages/work/bill/onlineLendHistory/detailsAddEdit?id=${item.id}&installmentHistoryId=${queryParams.value.installmentHistoryId}&name=${queryParams.value.name}&viewOnly=1` })
      isShow.value = true
    }
    // function handleAdd() {
    //   uni.navigateTo({ url: `/pages/work/bill/onlineLendHistory/addEdit` })
    //   isShow.value = true
    // }
    function handleDelete(item) {
      uni.showModal({
        	title: '提示',
        	content: '你确定要删除吗',
        	success: function (res) {
        		if (res.confirm) {
        		  delInstallmentDetail(item.id)
              uni.navigateTo({ url: `/pages/work/bill/onlineLendHistory/details?id=${queryParams.value.installmentHistoryId}&name=${queryParams.value.name}` })
        		} else if (res.cancel) {
        			console.log('取消');
        		}
        	}
        });
    }
	
</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;
  }
  
  .summary-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;
    }
  }
}

.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);
  transition: all 0.3s ease;
  
  &.highlight-item {
    animation: highlight 2s ease-in-out;
    box-shadow: 0 0 20rpx rgba(102, 126, 234, 0.6);
  }

  .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;
    }

    .account-name {
      font-size: 24rpx;
      font-weight: 500;
      color: #ffffff;
      line-height: 1.3;
      flex: 1;
      min-width: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .status-badge {
      font-size: 22rpx;
      font-weight: 600;
      padding: 4rpx 12rpx;
      border-radius: 12rpx;
      line-height: 1.2;
      flex-shrink: 0;
      
      &.paid {
        background: rgba(82, 196, 26, 0.2);
        color: #52c41a;
      }
      
      &.unpaid {
        background: rgba(255, 140, 0, 0.2);
        color: #ff8c00;
      }
    }

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

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

    .type-text {
      font-size: 24rpx;
      font-weight: 600;
      color: #ffffff;
      line-height: 1.3;
      flex: 1;
      min-width: 0;
      text-align: center;
    }

    .amount-value {
      font-size: 32rpx;
      font-weight: 700;
      line-height: 1.2;
      flex-shrink: 0;
      
      &.paid {
        color: #52c41a;
      }
      
      &.unpaid {
        color: #f5576c;
      }
    }
  }

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

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

    .info-label {
      font-size: 22rpx;
        color: #667eea;
        font-weight: 500;
        background: rgba(102, 126, 234, 0.08);
         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;
      
      &.orange {
        color: #fa8c16;
        font-weight: 600;
      }
    }
  }

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

    .btn-edit,
    .btn-delete,
    .btn-view {
      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-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);
    }
    
    .btn-view {
      background: rgba(82, 196, 26, 0.1);
      color: #52c41a;
      border: 1rpx solid rgba(82, 196, 26, 0.3);
    }
  }
}

@keyframes highlight {
  0%, 100% {
    background-color: #fff;
  }
  50% {
    background-color: rgba(102, 126, 234, 0.1);
  }
}
</style>