<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="onlineLendName" required @click="handleOnlineLend">
              <view class="input-with-arrow">
                <u--input v-model="form.onlineLendName" readonly disabledColor="#ffffff" placeholder="请选择信用卡"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="分期金额" prop="installmentAmount" required >
              <u--input v-model="form.installmentAmount"  type="number" placeholder="请填写分期金额"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="分期日期" prop="installmentDate" required @click="selectDate()">
              <view class="input-with-arrow">
                <u--input v-model="form.installmentDate" readonly disabledColor="#ffffff" placeholder="请选择分期日期" inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="分期期数" prop="period" required >
              <u--input v-model="form.period"  type="number" placeholder="请填写分期期数"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="余额" prop="balance" required >
              <u--input v-model="form.balance"  type="number" placeholder="请填写余额"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="结清状态" prop="settleStateName" required @click="handleShowTeam">
              <view class="input-with-arrow">
                <u--input v-model="form.settleStateName" readonly disabledColor="#ffffff" placeholder="请选择结清状态"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="总利息" prop="totalInterest" required >
              <u--input v-model="form.totalInterest"  type="number" placeholder="请填写总利息"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="已还期数" prop="repaidPeriod" required >
              <u--input v-model="form.repaidPeriod"  type="number" placeholder="请填写已还期数"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="利率" prop="interestRate"  >
              <u--input v-model="form.interestRate"  placeholder="请填写利率"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="关闭日期" prop="closeDate"  @click="selectCloseDate()">
              <view class="input-with-arrow">
                <u--input v-model="form.closeDate" 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" 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">
            <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="settleStateList" 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-datetime-picker
			:show="closeDatePickShow"
			mode="date"
      :minDate="-2209017600000"
      ref="closeTimeRef" 
			@cancel="closeDatePickShow=false"
			@confirm="closeDatePickConfirm"
			itemHeight="88"
		></u-datetime-picker>
    <u-picker itemHeight="88" :show="showOnlineLend" :columns="bankCardLendList" keyName="nameCode" @cancel="handleOnlineLendCancel"
        @confirm="handleOnlineLendConfirm"></u-picker>
    </view>
  </template>
  
  <script setup>
import {
  getInstallmentHistory,
  addInstallmentHistory,
  updateInstallmentHistory
} from '@/api/invest/installmentHistory'
  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 closeDatePickShow = ref(false)
const showTeam = ref(false)
const showOnlineLend = ref(false)
const title = ref("信用卡分期账单")
const bankCardLendList = ref([])
const settleStateList = ref([])
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}

const data = reactive({
  form: {
    id: null,
    name: null,
    type: '2',
    code: null,
    balance: null,
    bankCardLendId: null,
    installmentAmount: null,
    installmentDate: null,
    period: null,
    repaidPeriod: 0,
    totalInterest: 0,
    interestRate: null,
    dueDate: null,
    closeDate: null,
    state: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null
  },
  queryBankCardLendParams: {
    pageNum: 1,
    type: '2',
   status: '1', 
    pageSize: 1000
  },
  rules: {
           onlineLendName: [{ type: 'string', required: true, message: '信用卡不能为空', trigger: ['change', 'blur'] }],
          billDate: [{ type: 'string', required: true, message: '分期日期不能为空', trigger: ['change', 'blur'] }],
          settleStateName: [{ type: 'string', required: true, message: '结清状态不能为空', trigger: ['change', 'blur'] }],
          billAmount: [{ type: 'number', required: true, message: '分期金额不能为空', trigger: ['change', 'blur'] }],
          period: [{ type: 'number', required: true, message: '分期期数不能为空', trigger: ['change', 'blur'] }],
          totalInterest: [{ type: 'number', required: true, message: '总利息不能为空', trigger: ['change', 'blur'] }],
          repaidPeriod: [{ type: 'number', required: true, message: '已还期数不能为空', trigger: ['change', 'blur'] }],
          balance: [{ type: 'number', required: true, message: '余额不能为空', trigger: ['change', 'blur'] }],
  }
})
const { form, queryBankCardLendParams, rules} = toRefs(data)

onLoad((option) => {
       form.value.id = option.id
       if(form.value.id!=null){
        title.value="信用卡分期账单-修改"
       }else{
        title.value="信用卡分期账单-新增"
       }
      getDict()
  })
  onReady(() => {
    form.value.installmentDate = dayjs(new Date().getTime()).format("YYYY-MM-DD")
  })
  function  getDict() {
        // 账单状态
        getDicts('settle_state').then(res => {
        settleStateList.value =[res.data] 
      })
      listAccounts(queryBankCardLendParams.value).then((response) => {
        bankCardLendList.value = [response.rows] 
      })
      if(form.value.id!=null){
        getInstallmentHistory(form.value.id).then(res => {
          form.value = res.data
          form.value.onlineLendName = res.data.bankName
           // 类型
        getDicts('settle_state').then(result => {
          form.value.settleStateName=dictStr(form.value.state, result.data)
      })
          
        })
      }
  }
  function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
    }

  function handleShowTeam() {
        if (settleStateList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '结清状态为空  ', type: 'warning'
          })
        } else {
          showTeam.value = true
        }
      }
      function   handleConfirm(e) {
        form.value.settleStateName = e.value[0].dictLabel
        form.value.state = e.value[0].dictValue
        showTeam.value = false
      }
      function handleCancel() {
       showTeam.value = false
      }
      function handleOnlineLend() {
        if (bankCardLendList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '信用卡为空  ', type: 'warning'
          })
        } else {
          showOnlineLend.value = true
        }
     }
  function   handleOnlineLendConfirm(e) {
        form.value.onlineLendName = e.value[0].nameCode
        form.value.bankCardLendId= e.value[0].id
        showOnlineLend.value = false
  }
 function handleOnlineLendCancel() {
       showOnlineLend.value = false
  }

      function  selectDate() {
				datePickShow.value = true
        proxy.$refs['createTimeRef'].innerValue = new Date().getTime()
			}
			function datePickConfirm(e) {
				form.value.installmentDate = dayjs(e.value).format("YYYY-MM-DD")
				datePickShow.value = false
			}
      function  selectCloseDate() {
				closeDatePickShow.value = true
        proxy.$refs['closeTimeRef'].innerValue = new Date().getTime()
			}
			function closeDatePickConfirm(e) {
				form.value.closeDate = dayjs(e.value).format("YYYY-MM-DD")
				closeDatePickShow.value = false
			}

      function submit() {
        proxy.$refs['uForm'].validate().then(() => {
          if (form.value.id != null) {
            updateInstallmentHistory(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '修改成功', complete() {
                uni.navigateTo({ url: `/pages/work/bill/creditInstallmentHistory/list` })
              }
            })
          })
          }else {
            addInstallmentHistory(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '新增成功', complete() {
                uni.navigateTo({ url: `/pages/work/bill/creditInstallmentHistory/list` })
              }
            })
          })
          }
        })
      }
  </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>