<template>
    <view class="container" style="paddingBottom:1rpx;">
      <u-navbar
			leftIconSize="40rpx"
			leftIconColor="#333333"
			title="贷款账单还款明细"
		>
		</u-navbar>
      <view class="section">
        <view class="section-title">{{ title}}</view>
        <view class="form-view">
          <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" label-width="180rpx"
            :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
             <u-form-item label="还款账户" prop="debitCardName" required @click="!viewOnly && handleDebitCard()">
              <view class="input-with-arrow">
                <u--input v-model="form.debitCardName" readonly disabledColor="#ffffff" placeholder="请选择还款账户"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="还款日期" prop="repaymentDate" required @click="!viewOnly && selectDate()">
              <view class="input-with-arrow">
                <u--input v-model="form.repaymentDate" readonly disabledColor="#ffffff" placeholder="请选择还款日期" inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="还款期数" prop="periods" required >
              <u--input v-model="form.periods" :disabled="viewOnly" :disabledColor="viewOnly ? '#ffffff' : ''" placeholder="请填写还款期数"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="还款金额" prop="currentAmount"  >
              <u--input v-model="form.currentAmount" :disabled="viewOnly" :disabledColor="viewOnly ? '#ffffff' : ''" placeholder="请填写还款金额"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="应还本金" prop="principal" required >
              <u--input v-model="form.principal" :disabled="viewOnly" :disabledColor="viewOnly ? '#ffffff' : ''" placeholder="请填写应还本金"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="利息" prop="interest" required >
              <u--input v-model="form.interest" :disabled="viewOnly" :disabledColor="viewOnly ? '#ffffff' : ''" placeholder="请填写利息"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="还款状态" prop="postingStateName" required @click="!viewOnly && handleShowTeam()">
              <view class="input-with-arrow">
                <u--input v-model="form.postingStateName" readonly disabledColor="#ffffff" placeholder="请选择入账状态"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
           
            <u-form-item label="备注" prop="remark"  labelPosition="top">
              <u--textarea v-model="form.remark" :disabled="viewOnly" :disabledColor="viewOnly ? '#ffffff' : ''" placeholder="请填写备注" autoHeight inputAlign="left" count
                maxlength="20000" style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
            </u-form-item>
          </u--form>
          <view class="form-btn" v-if="!viewOnly">
            <u-button type="primary" text="提交" @click="submit"></u-button>
          </view>
        </view>
      </view>
      <u-toast ref="uToast"></u-toast>
      <u-picker itemHeight="88" :show="showTeam" :columns="postingStateList" keyName="dictLabel" @cancel="handleCancel"
        @confirm="handleConfirm"></u-picker>
        <u-datetime-picker
			:show="datePickShow"
			mode="date"
      :minDate="-2209017600000"
      ref="createTimeRef" 
			@cancel="datePickShow=false"
			@confirm="datePickConfirm"
			itemHeight="88"
		></u-datetime-picker>
      <u-picker itemHeight="88" :show="showDebitCard" :columns="debitCardList" keyName="nameCode" @cancel="handleDebitCardCancel"
        @confirm="handleDebitCardConfirm"></u-picker>
    </view>
  </template>
  
  <script setup>
import {
  getInstallmentDetail,
  addInstallmentDetail,
  updateInstallmentDetail
} from '@/api/invest/installmentDetail'
  import { getDicts } from '@/api/system/dict/data.js'
    import { listAccounts } from '@/api/invest/accounts'
  const { proxy } = getCurrentInstance()
  import dayjs from 'dayjs'
  import {onLoad,onReady} from "@dcloudio/uni-app";
    // 计算属性与监听属性是在vue中而非uniap中 需要注意！！！
import {reactive ,toRefs,ref,computed ,getCurrentInstance }from "vue";
const datePickShow = ref(false)
const showTeam = ref(false)
const title = ref("贷款账单还款明细")
const showDebitCard = ref(false)
const debitCardList = ref([])
const postingStateList = ref([])
const viewOnly = ref(false)
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}

const data = reactive({
  form: {},
   queryDebitCardParams: {
    pageNum: 1,
    type: '1',
    status: '1',
    // lendType: '1',
    pageSize: 1000
  },
  rules: {
           repaymentDate: [{ type: 'string', required: true, message: '还款日期不能为空', trigger: ['change', 'blur'] }],
           periods: [{ type: 'number', required: true, message: '还款期数不能为空', trigger: ['change', 'blur'] }],
           interest: [{ type: 'number', required: true, message: '利息不能为空', trigger: ['change', 'blur'] }],
           principal: [{ type: 'number', required: true, message: '应还本金不能为空', trigger: ['change', 'blur'] }],
          postingStateName: [{ type: 'string', required: true, message: '还款状态不能为空', trigger: ['change', 'blur'] }],
  }
})
const { form, rules, queryDebitCardParams} = toRefs(data)

onLoad((option) => {
       form.value.id = option.id
       form.value.installmentHistoryId = option.installmentHistoryId
       form.value.name = option.name
       viewOnly.value = option.viewOnly === '1'
       if(form.value.id!=null){
        title.value = viewOnly.value ? "贷款账单还款明细-查看" : "贷款账单还款明细-修改"
       }else{
        title.value="贷款账单还款明细-新增"
       }
      getDict()
  })
  onReady(() => {
    form.value.createTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
  })
  function  getDict() {
        // 类型
        getDicts('repayment_state').then(res => {
        postingStateList.value =[res.data] 
      })
       listAccounts(queryDebitCardParams.value).then((response) => {
        debitCardList.value = [response.rows] 
      })
      if(form.value.id!=null){
        getInstallmentDetail(form.value.id).then(res => {
          form.value = res.data
             form.value.debitCardName = res.data.repaymentAccountName
           // 类型
        getDicts('repayment_state').then(result => {
          form.value.postingStateName=dictStr(form.value.postingState, result.data)
      })
          
        })
      }
  }
  function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
    }

  function handleShowTeam() {
        if (postingStateList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '入账状态为空  ', type: 'warning'
          })
        } else {
          showTeam.value = true
        }
      }
      function   handleConfirm(e) {
        form.value.postingStateName = e.value[0].dictLabel
        form.value.postingState = e.value[0].dictValue
        showTeam.value = false
      }
      function handleCancel() {
       showTeam.value = false
      }
       function handleDebitCard() {
        if (debitCardList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '收款账户为空  ', type: 'warning'
          })
        } else {
          showDebitCard.value = true
        }
     }
  function   handleDebitCardConfirm(e) {
        form.value.debitCardName = e.value[0].nameCode
        form.value.repaymentAccountId= e.value[0].id
        showDebitCard.value = false
  }
 function handleDebitCardCancel() {
       showDebitCard.value = false
  }

      function  selectDate() {
				datePickShow.value = true
        proxy.$refs['createTimeRef'].innerValue = form.value.repaymentDate ? new Date(form.value.repaymentDate).getTime() : new Date().getTime()
			}
			function datePickConfirm(e) {
				form.value.repaymentDate = dayjs(e.value).format("YYYY-MM-DD")
				datePickShow.value = false
			}
      function submit() {
        proxy.$refs['uForm'].validate().then(() => {
          if (form.value.id != null) {
           
            updateInstallmentDetail(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '修改成功', complete() {
                uni.navigateBack()
              }
            })
          })
          } else {
            addInstallmentDetail(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '新增成功', complete() {
                uni.navigateBack()
              }
            })
          })
          }
        })
      }
  </script>
  
  <style lang="scss" scoped>
  .section {
    margin: 24rpx;
    padding: 0;
    background-color: #fff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
    overflow: hidden;
  
    .section-title {
      padding: 16rpx 24rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #ffffff;
      line-height: 1.2;
      font-size: 28rpx;
      font-weight: 600;
      display: flex;
      align-items: center;
      
      &::before {
        content: '';
        width: 6rpx;
        height: 28rpx;
        background: #ffffff;
        border-radius: 3rpx;
        margin-right: 12rpx;
      }
    }
  
    .form-view {
      padding: 24rpx;
  
          .input-with-arrow {
      position: relative;
      width: 100%;

      .arrow-icon {
        position: absolute;
        right: 20rpx;
        top: 50%;
        transform: translateY(-50%);
        color: #c0c4cc;
        font-size: 20rpx;
        pointer-events: none;
        z-index: 10;
      }
    }

    .form-btn {
        padding-top: 16rpx;
      }
    }
  }
  </style>
  
  <style lang="scss">
  .form-btn .u-button {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
    border: none !important;
    border-radius: 24rpx !important;
    height: 80rpx !important;
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4) !important;
  }
  
  .form-btn .u-button__text {
    font-size: 30rpx !important;
    font-weight: 500 !important;
    letter-spacing: 2rpx !important;
  }
  </style>