<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', fontSize: '36rpx', fontWeight: '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="180rpx"
            :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
            <u-form-item label="信用卡" prop="creditCardName" required @click="handleCreditCard">
              <view class="input-with-arrow">
                <u--input v-model="form.creditCardName" readonly disabledColor="#ffffff" placeholder="请选择信用卡"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="账单日" prop="billDate" required @click="selectDate()">
              <view class="input-with-arrow">
                <u--input v-model="form.billDate" readonly disabledColor="#ffffff" placeholder="请选择账单日" inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="账单金额" prop="billAmount" required >
              <u--input v-model="form.billAmount"  type="number" placeholder="请填写账单金额"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </u-form-item>
            <u-form-item label="账单状态" prop="billStateName" required @click="handleShowTeam">
              <view class="input-with-arrow">
                <u--input v-model="form.billStateName" 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"
              customStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; border-radius: 16rpx; font-size: 32rpx; font-weight: 600; height: 96rpx; 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="showTeam" :columns="billStateList" keyName="dictLabel" @cancel="handleCancel"
        @confirm="handleConfirm" :closeOnClickOverlay="true" cancelColor="#666666" confirmColor="#667eea" title="选择账单状态"></u-picker>
        <u-datetime-picker
			:show="datePickShow"
			mode="date"
      :minDate="-2209017600000"
      ref="createTimeRef" 
			@cancel="datePickShow=false"
			@confirm="datePickConfirm"
			itemHeight="88"
      :closeOnClickOverlay="true"
      cancelColor="#666666"
      confirmColor="#667eea"
		></u-datetime-picker>
    <u-picker itemHeight="88" :show="showCreditCard" :columns="bankCardLendList" keyName="nameCodeAvailableLimit" @cancel="handleCreditCardCancel"
        @confirm="handleCreditCardConfirm" :closeOnClickOverlay="true" cancelColor="#666666" confirmColor="#667eea" title="选择信用卡"></u-picker>
    </view>
  </template>
  
  <script setup>
import {getCreditCardBill, addCreditCardBill, updateCreditCardBill } from '@/api/invest/creditCardBill'
  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 showCreditCard = ref(false)
const title = ref("信用卡账单")
const bankCardLendList = ref([])
const billStateList = 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,
    billDate: null,
    creditCardId: null,
    billDatePeriod: null,
    billAmount: 0,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    billState: null,
    remark: null,
    delFlag: null
  },
  queryBankCardLendParams: {
    pageNum: 1,
    type: '2',
    status: '1',
    pageSize: 1000
  },
  rules: {
           creditCardName: [{ type: 'string', required: true, message: '信用卡不能为空', trigger: ['change', 'blur'] }],
          billDate: [{ type: 'string', required: true, message: '账单日不能为空', trigger: ['change', 'blur'] }],
          billStateName: [{ type: 'string', required: true, message: '账单状态不能为空', trigger: ['change', 'blur'] }],
          billAmount: [{ 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.billDate = dayjs(new Date().getTime()).format("YYYY-MM-DD")
  })
  function  getDict() {
        // 账单状态
        getDicts('bill_state').then(res => {
        billStateList.value =[res.data] 
      })
      listAccounts(queryBankCardLendParams.value).then((response) => {
        bankCardLendList.value = [response.rows] 
      })
      if(form.value.id!=null){
        getCreditCardBill(form.value.id).then(res => {
          form.value = res.data
          form.value.creditCardName = res.data.bankNameCode
           // 类型
        getDicts('bill_state').then(result => {
          form.value.billStateName=dictStr(form.value.billState, result.data)
      })
          
        })
      }
  }
  function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
    }

  function handleShowTeam() {
        if (billStateList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '账单状态为空  ', type: 'warning'
          })
        } else {
          showTeam.value = true
        }
      }
      function   handleConfirm(e) {
        form.value.billStateName = e.value[0].dictLabel
        form.value.billState = e.value[0].dictValue
        showTeam.value = false
      }
      function handleCancel() {
       showTeam.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.creditCardName = e.value[0].nameCodeAvailableLimit
        form.value.creditCardId= e.value[0].id
        showCreditCard.value = false
  }
 function handleCreditCardCancel() {
       showCreditCard.value = false
  }

      function  selectDate() {
				datePickShow.value = true
        proxy.$refs['createTimeRef'].innerValue = new Date().getTime()
			}
			function datePickConfirm(e) {
				form.value.billDate = dayjs(e.value).format("YYYY-MM-DD")
				datePickShow.value = false
			}
      function submit() {
        proxy.$refs['uForm'].validate().then(() => {
          if (form.value.id != null) {
            updateCreditCardBill(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '修改成功', complete() {
                uni.navigateTo({ url: `/pages/work/bill/creditCardBill/list` })
              }
            })
          })
          }else {
            addCreditCardBill(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '新增成功', complete() {
                uni.navigateTo({ url: `/pages/work/bill/creditCardBill/list` })
              }
            })
          })
          }
        })
      }
  </script>
  
  <style lang="scss" scoped>
.section {
    margin: 24rpx;
    padding: 16rpx 24rpx;
    background-color: #fff;
    border-radius: 8rpx;

    .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;
      margin: -16rpx -24rpx 20rpx;

      &::before {
        content: '';
        width: 6rpx;
        height: 28rpx;
        background: #ffffff;
        border-radius: 3rpx;
        margin-right: 12rpx;
      }
    }
  
    .form-view {
      padding: 20rpx 0rpx 0 10rpx;
  
          .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;
        
        .u-button {
          border-radius: 24rpx;
          box-shadow: 0 6rpx 16rpx rgba(102, 126, 234, 0.25);
        }
      }
    }
  }
  </style>