<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="银行" required prop="bankName" @click="handleShowBank">
              <view class="input-with-arrow">
                <u--input v-model="form.bankName" readonly disabledColor="#ffffff" placeholder="请选择银行"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="信用卡名称" prop="name" required >
              <u--input v-model="form.name"  placeholder="请填写信用卡名称"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="信用卡卡号" prop="code" required >
              <u--input v-model="form.code"  placeholder="请填写信用卡卡号"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="信用卡额度" required prop="creditLimit" >
              <u--input v-model="form.creditLimit"  type="number" placeholder="请填写信用卡额度"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="账户状态" required prop="statusName"  @click="handleShowStatus">
              <view class="input-with-arrow">
                <u--input v-model="form.statusName" readonly disabledColor="#ffffff" placeholder="请选择账户状态"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="账单日" required prop="billDate" >
              <u--input v-model="form.billDate"  type="number" placeholder="请填写账单日"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="还款日" required prop="payDate" >
              <u--input v-model="form.payDate" type="number"  placeholder="请填写还款日"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="余额" required prop="balance" >
              <u--input v-model="form.balance" type="number"  placeholder="请填写余额"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="可用额度" required prop="availableLimit" >
              <u--input v-model="form.availableLimit"  type="number" placeholder="请填写可用额度"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="账单日消费" required prop="isNextBillDateName"  @click="handleShowIsNextBillDate">
              <view class="input-with-arrow">
                <u--input v-model="form.isNextBillDateName" readonly disabledColor="#ffffff" placeholder="请选择账单日消费"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="信用卡安全码" prop="cvv" >
              <u--input v-model="form.cvv"  placeholder="请填写信用卡安全码"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
     
            <u-form-item label="卡片等级" prop="cardTierName" @click="handleShowCardTier">
              <view class="input-with-arrow">
                <u--input v-model="form.cardTierName" readonly disabledColor="#ffffff" placeholder="请选择卡片等级"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="卡面" prop="cardFace">
              <u--input v-model="form.cardFace" placeholder="请填写卡面"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
          
            <u-form-item label="开户行" prop="openingBank" >
              <u--input v-model="form.openingBank"  placeholder="请填写开户行"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="开户日期" prop="activationDate"  @click="selectDate(1)">
              <view class="input-with-arrow">
                <u--input v-model="form.activationDate" readonly disabledColor="#ffffff" placeholder="请选择开户日期" inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="宽限期" prop="delayPeriod" >
              <u--input v-model="form.delayPeriod"  placeholder="请填写宽限期"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="有效期" prop="effectiveDate"  @click="selectDate(2)">
              <view class="input-with-arrow">
                <u--input v-model="form.effectiveDate" readonly disabledColor="#ffffff" placeholder="请选择有效期" inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
          
            <u-form-item label="账单日时间" prop="nextBillDateTime" >
              <u--input v-model="form.nextBillDateTime"  placeholder="请填写账单日时间"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="0账单操作" prop="isZeroBillName"  @click="handleShowIsZeroBill">
              <view class="input-with-arrow">
                <u--input v-model="form.isZeroBillName" readonly disabledColor="#ffffff" placeholder="请选择0账单操作"
                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" customStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; border-radius: 24rpx; font-size: 32rpx; font-weight: 600; box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4);"></u-button>
          </view>
        </view>
      </view>
      <u-toast ref="uToast"></u-toast>
      <u-picker itemHeight="88" :show="showIsNextBillDate" :columns="isNextBillDateList" keyName="dictLabel" @cancel="handleCancel"
        @confirm="handleConfirm"></u-picker>
        <u-picker itemHeight="88" :show="showIsZeroBill" :columns="isZeroBillList" keyName="dictLabel" @cancel="handleIsZeroBillCancel"
        @confirm="handleIsZeroBillConfirm"></u-picker>
        <u-picker itemHeight="88" :show="showStatus" :columns="statusList" keyName="dictLabel" @cancel="handleStatusCancel"
        @confirm="handleStatusConfirm"></u-picker>
        <u-picker itemHeight="88" :show="showBank" :columns="bankList" keyName="bankName" @cancel="handleBankCancel"
        @confirm="handleBankConfirm"></u-picker>
        <u-picker itemHeight="88" :show="showCardTier" :columns="cardTierList" keyName="dictLabel" @cancel="handleCardTierCancel"
        @confirm="handleCardTierConfirm"></u-picker>
        <u-datetime-picker
			:show="datePickShow"
			mode="date"
      :minDate="-2209017600000"
      ref="createTimeRef" 
			@cancel="datePickShow=false"
			@confirm="datePickConfirm"
			itemHeight="88"
		></u-datetime-picker>
    </view>
  </template>
  
  <script setup>
import { getBankcardLend, addBankcardLend, updateBankcardLend } from '@/api/invest/bankcardlend'
  import { getDicts } from '@/api/system/dict/data.js'
  import { listBankBaseInfo } from '@/api/invest/bankBaseInfo'
  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 showIsNextBillDate = ref(false)
const showIsZeroBill = ref(false)
const title = ref("信用卡管理")
const isNextBillDateList = ref([])
const isZeroBillList = ref([])
const showStatus = ref(false)
const statusList = ref([])
const dateType = ref(1)
const showBank = ref(false)
const bankList = ref([])
const showCardTier = ref(false)
const cardTierList = 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,
    openingBank: null,
    activationDate: null,
    billDate: null,
    payDate: null,
    delayPeriod: null,
    balance: null,
    creditLimit: null,
    availableLimit: null,
    effectiveDate: null,
    cvv: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    debitType: null,
    isNextBillDate: null,
    nextBillDateTime: null,
    isZeroBill: null,
    status: '1',
    statusName: '正常使用',
    bankId: null,
    bankName: null,
    cardTier: null,
    cardTierName: null,
    cardFace: null
  },
  // dateType:'1',
  rules: {
      bankName: [{ type: 'string', required: true, message: '银行不能为空', trigger: ['change', 'blur'] }],
          name: [{ type: 'string', required: true, message: '信用卡名称不能为空', trigger: ['change', 'blur'] }],
          code: [{ type: 'string', required: true, message: '信用卡卡号不能为空', trigger: ['change', 'blur'] }],
          billDate: [{ type: 'number', required: true, message: '账单日不能为空', trigger: ['change', 'blur'] }],
          payDate: [{ type: 'number', required: true, message: '还款日不能为空', trigger: ['change', 'blur'] }],  
          statusName: [{ type: 'string', required: true, message: '账户状态不能为空', trigger: ['change', 'blur'] }],  
          creditLimit: [{ type: 'number', required: true, message: '信用卡额度不能为空', trigger: ['change', 'blur'] }],  
          balance: [{ type: 'number', required: true, message: '余额不能为空', trigger: ['change', 'blur'] }],  
          isNextBillDateName: [{ type: 'string', required: true, message: '账单日消费不能为空', trigger: ['change', 'blur'] }],  
          availableLimit: [{ type: 'number', required: true, message: '可用额度不能为空', trigger: ['change', 'blur'] }],  
  }
})
const { form, rules} = toRefs(data)

onLoad((option) => {
       form.value.id = option.id
       if(form.value.id!=null){
        title.value="信用卡管理-修改"
       }else{
        title.value="信用卡管理-新增"
       }
      getDict()
  })
  onReady(() => {
    form.value.activationDate = dayjs(new Date().getTime()).format("YYYY-MM-DD")
    form.value.effectiveDate = dayjs(new Date().getTime()).format("YYYY-MM-DD")
  })
  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] 
      })
      // 获取银行列表
      listBankBaseInfo({ pageSize: 1000, pageNum: 1 }).then(res => {
        bankList.value = [res.rows]
      })
      if(form.value.id!=null){
        getBankcardLend(form.value.id).then(res => {
          form.value = res.data
           // 类型
        getDicts('is_next_bill_date').then(result => {
          form.value.isNextBillDateName=dictStr(form.value.isNextBillDate, result.data)
      })
          // 类型
          getDicts('is_zero_bill').then(result => {
          form.value.isZeroBillName=dictStr(form.value.isZeroBill, result.data)
      })

       // 类型
       getDicts('account_status').then(result => {
          form.value.statusName=dictStr(form.value.status, result.data)
      })
          // 卡片等级
       getDicts('card_tier').then(result => {
          form.value.cardTierName=dictStr(form.value.cardTier, result.data)
      })
          // 银行名称
       listBankBaseInfo({ pageSize: 1000, pageNum: 1 }).then(res => {
          const bank = res.rows.find(item => item.id === form.value.bankId)
          if (bank) {
            form.value.bankName = bank.bankName
          }
      })
          
        })
      }
  }
  function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
    }

  function handleShowIsNextBillDate() {
        if (isNextBillDateList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '账单日消费为空  ', type: 'warning'
          })
        } else {
          showIsNextBillDate.value = true
        }
      }
      function   handleConfirm(e) {
        form.value.isNextBillDateName = e.value[0].dictLabel
        form.value.isNextBillDate = e.value[0].dictValue
        showIsNextBillDate.value = false
      }
      function handleCancel() {
       showIsNextBillDate.value = false
      }
      function handleShowIsZeroBill() {
        if (isZeroBillList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '0账单操作为空  ', type: 'warning'
          })
        } else {
          showIsZeroBill.value = true
        }
      }
      function   handleIsZeroBillConfirm(e) {
        form.value.isZeroBillName = e.value[0].dictLabel
        form.value.isZeroBill = e.value[0].dictValue
        showIsZeroBill.value = false
      }
      function handleIsZeroBillCancel() {
       showIsZeroBill.value = false
      }

      function handleShowStatus() {
        if (statusList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '账户状态操作为空  ', type: 'warning'
          })
        } else {
          showStatus.value = true
        }
      }
      function   handleStatusConfirm(e) {
        form.value.statusName = e.value[0].dictLabel
        form.value.status = e.value[0].dictValue
        showStatus.value = false
      }
      function handleStatusCancel() {
       showStatus.value = false
      }
      
      function handleShowBank() {
        if (bankList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '银行列表为空  ', type: 'warning'
          })
        } else {
          showBank.value = true
        }
      }
      function handleBankConfirm(e) {
        form.value.bankName = e.value[0].bankName
        form.value.bankId = e.value[0].id
        showBank.value = false
      }
      function handleBankCancel() {
        showBank.value = false
      }
      
      function handleShowCardTier() {
        if (cardTierList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '卡片等级为空  ', type: 'warning'
          })
        } else {
          showCardTier.value = true
        }
      }
      function handleCardTierConfirm(e) {
        form.value.cardTierName = e.value[0].dictLabel
        form.value.cardTier = e.value[0].dictValue
        showCardTier.value = false
      }
      function handleCardTierCancel() {
        showCardTier.value = false
      }

      function  selectDate(type) {
        dateType.value=type
				datePickShow.value = true
        proxy.$refs['createTimeRef'].innerValue = new Date().getTime()
			}
			function datePickConfirm(e) {
         if(dateType.value===1){
          form.value.activationDate = dayjs(e.value).format("YYYY-MM-DD")
          }
          if(dateType.value===2){
          form.value.effectiveDate = dayjs(e.value).format("YYYY-MM-DD")
          }
				datePickShow.value = false
			}
      function submit() {
        proxy.$refs['uForm'].validate().then(() => {
          if (form.value.id != null) {
            updateBankcardLend(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '修改成功', complete() {
                uni.navigateTo({ url: `/pages/work/base/creditCard/list?flag='addEdit'` })
              }
            })
          })
          }else {
            addBankcardLend(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '新增成功', complete() {
                uni.navigateTo({ url: `/pages/work/base/creditCard/list?flag='addEdit'` })
              }
            })
          })
          }
        })
      }
  </script>
  
  <style lang="scss" scoped>
  .container {
    background: #f5f7fa;
  }
  
  .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: 32rpx;
      }
    }
  }
  </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>