<template>
    <view class="container" style="paddingBottom:1rpx;">
      <u-navbar
			leftIconSize="40rpx"
			leftIconColor="#ffffff"
			title="信用卡还款"
			:bgColor="'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'"
			titleStyle="color: #ffffff; font-weight: 600;"
		>
		</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="auto"
            :labelStyle="{ color: '#333333', fontSize: '30rpx' }">
            <u-form-item label="储蓄账户" prop="outAccountName" required @click="handleDebitCard">
              <u--input v-model="form.outAccountName" disabled disabledColor="#ffffff" placeholder="请选择储蓄账户"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item>
            <u-form-item label="信用卡" prop="inAccountName" required @click="handleCreditCard">
              <u--input v-model="form.inAccountName" disabled disabledColor="#ffffff" placeholder="请选择信用卡"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item>
            <u-form-item label="还款时间" prop="createTime" required @click="selectDate()">
              <u--input v-model="form.createTime" disabled disabledColor="#ffffff" placeholder="请选择还款时间" inputAlign="right" border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>
            <u-form-item label="还款金额" prop="amount" required >
              <u--input v-model="form.amount"  type="number" placeholder="请填写还款金额"
                inputAlign="right" border="none"></u--input>
            </u-form-item>
            <u-form-item label="还款方式" prop="dealTypeName" required @click="handleDealType">
              <u--input v-model="form.dealTypeName" disabled disabledColor="#ffffff" placeholder="请选择还款方式"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item> 
            <u-form-item label="备注" prop="remark"  labelPosition="top">
              <u--textarea v-model="form.remark" placeholder="请填写备注" border="none" autoHeight inputAlign="right" count
                maxlength="20000" style="padding:18rpx 0;"></u--textarea>
            </u-form-item>
          </u--form>
          <view class="form-btn">
            <u-button type="primary" text="提交" @click="submit" 
              customStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; border-radius: 12rpx; font-size: 32rpx; font-weight: 600; height: 92rpx; box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);"></u-button>
          </view>
        </view>
      </view>
      <u-toast ref="uToast"></u-toast>
      <u-picker 
        itemHeight="88" 
        :show="showDebitCard" 
        :columns="debitCardList" 
        keyName="nameCodeAvailableLimit" 
        @cancel="handleDebitCardCancel"
        @confirm="handleDebitCardConfirm"
        :closeOnClickOverlay="true"
        cancelColor="#666666"
        confirmColor="#667eea"
        title="选择储蓄账户"
      ></u-picker>
      <u-picker 
        itemHeight="88" 
        :show="showCreditCard" 
        :columns="bankCardLendList" 
        keyName="nameCodeAvailableLimit" 
        @cancel="handleCreditCardCancel"
        @confirm="handleCreditCardConfirm"
        :closeOnClickOverlay="true"
        cancelColor="#666666"
        confirmColor="#667eea"
        title="选择信用卡"
      ></u-picker>
      <u-picker 
        itemHeight="88" 
        :show="showDealType" 
        :columns="dealTypeList" 
        keyName="dictLabel" 
        @cancel="handleDealTypeCancel"
        @confirm="handleDealTypeConfirm"
        :closeOnClickOverlay="true"
        cancelColor="#666666"
        confirmColor="#667eea"
        title="选择还款方式"
      ></u-picker>
      <u-datetime-picker
			:show="datePickShow"
			mode="datetime"
      ref="createTimeRef" 
			@cancel="datePickShow=false"
			@confirm="datePickConfirm"
			itemHeight="88"
      confirmColor="#667eea"
      cancelColor="#666666"
		></u-datetime-picker>
    </view>
  </template>
  
  <script setup>
  import {getAccountsTransferRecord, addAccountsTransferRecord, updateAccountsTransferRecord } from '@/api/invest/accountsTransferRecord'
import { listAccounts } from '@/api/invest/accounts'
import { getDicts } from '@/api/system/dict/data.js'
  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 showDebitCard = ref(false)
const showDealType = ref(false)
const showCreditCard = ref(false)
const title = ref("信用卡还款")
const bankCardLendList = ref([])
const debitCardList = ref([])
const dealTypeList = ref([])
const data = reactive({
  form: {
    id: null,
    name: null,
    type: '2',
    outAccountId: null,
    inAccountId: null,
    posId: null,
    commission: null,
    amount: null,
    actualAmount: null,
    dealType: '6',
    dealTypeName: '信用卡还款',
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null
  },
  queryDebitCardParams: {
    pageNum: 1,
    type: '1',
   status: '1', 
    pageSize: 1000
  },
  queryBankCardLendParams: {
    pageNum: 1,
    type: '2',
   status: '1', 
    pageSize: 1000
  },
  rules: {
    inAccountName: [{ required: true, message: '信用卡不能为空', trigger:['change', 'blur'] }],
    outAccountName: [{ required: true, message: '储蓄账户不能为空', trigger: ['change', 'blur'] }],
    dealTypeName: [{ required: true, message: '还款方式不能为空', trigger: ['change', 'blur'] }],
    amount: [{ type: 'number',required: true, message: '还款金额不能为空', trigger: ['change', 'blur'] }],
    createTime: [{ required: true, message: '还款时间不能为空', trigger: ['change', 'blur'] }]
  }
})
const { form, queryDebitCardParams, queryBankCardLendParams, rules} = toRefs(data)


onLoad((option) => {
       form.value.id = option.id
       if(form.value.id!=null){
        title.value="信用卡还款-修改"
       }else{
        title.value="信用卡还款-新增"
       }
      getData()
  })
  onReady(() => {
       form.value.createTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
  })
  function  getData() {
      listAccounts(queryBankCardLendParams.value).then((response) => {
        bankCardLendList.value = [response.rows] 
      })
      listAccounts(queryDebitCardParams.value).then((response) => {
       debitCardList.value = [response.rows] 
       })
           // 类型
           getDicts('credit_repayment_type').then(res => {
        dealTypeList.value =[res.data] 
      })
      if(form.value.id!=null){
        getAccountsTransferRecord(form.value.id).then(res => {
          form.value = res.data   

           // 交易类型
             getDicts('credit_repayment_type').then(result => {
              form.value.amount = res.data.amount   
          form.value.dealTypeName=dictStr(form.value.dealType, result.data)
         })
        })
      }
  }

  function handleDebitCard() {
        if (debitCardList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '储蓄账户为空  ', type: 'warning'
          })
        } else {
          showDebitCard.value = true
        }
     }
  function   handleDebitCardConfirm(e) {
       form.value.outAccountName = e.value[0].nameCodeAvailableLimit
        form.value.outAccountId = e.value[0].id
        showDebitCard.value = false    
  }
 function handleDebitCardCancel() {
       showDebitCard.value = false
    }
function handleCreditCard() {
        if (bankCardLendList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '信用卡为空  ', type: 'warning'
          })
        } else {
          showCreditCard.value = true
        }
     }
  function   handleCreditCardConfirm(e) {
        form.value.inAccountName = e.value[0].nameCodeAvailableLimit
        form.value.inAccountId= e.value[0].id
        showCreditCard.value = false
  }
 function handleCreditCardCancel() {
       showCreditCard.value = false
  }
  function handleDealType() {
        if (dealTypeList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '交易类型为空  ', type: 'warning'
          })
        } else {
          showDealType.value = true
        }
     }
  function   handleDealTypeConfirm(e) {
        form.value.dealTypeName = e.value[0].dictLabel
        form.value.dealType = e.value[0].dictValue
        showDealType.value = false
  }
 function handleDealTypeCancel() {
       showDealType.value = false
      }
      function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
    }
  function  selectDate() {
				datePickShow.value = true
        proxy.$refs['createTimeRef'].innerValue = new Date().getTime()
		}
	function datePickConfirm(e) {
				form.value.createTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
				datePickShow.value = false
		}
  function submit() {
        proxy.$refs['uForm'].validate().then(() => {
          if (form.value.id != null) {
            updateAccountsTransferRecord(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '修改成功', complete() {
                uni.navigateTo({ url: `/pages/work/accounts/creditTransferRecord/list` })
              }
            })
          })
          }else {
            addAccountsTransferRecord(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '新增成功', complete() {
                uni.navigateTo({ url: `/pages/work/accounts/creditTransferRecord/list` })
              }
            })
          })
          }
        })
      }
  </script>
  
  <style lang="scss" scoped>
  .section {
    margin: 24rpx;
    padding: 0;
    background-color: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
    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;
  
      .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>