<template>
    <view class="container" style="paddingBottom:1rpx;">
      <u-navbar
			leftIconSize="40rpx"
			leftIconColor="#ffffff"
			title="POS机刷卡记账"
			: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="POS机" prop="posName" required @click="handlePosMachine">
              <u--input v-model="form.posName" disabled disabledColor="#ffffff" placeholder="请选择POS机"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item>
            <u-form-item label="刷卡费率" required prop="rate" >
              <u--input v-model="form.rate"  type="number" placeholder="请填写刷卡费率"
                inputAlign="right" border="none">
                <template #suffix>
					<up-text
						text="%"
					></up-text>
				</template>
              </u--input>
            </u-form-item>
            <u-form-item label="费率+" prop="ratePlus" >
              <u--input v-model="form.ratePlus" type="number"  placeholder="请填写费率+"
                inputAlign="right" border="none"></u--input>
            </u-form-item>
            <u-form-item label="信用卡" prop="outAccountName" required @click="handleCreditCard">
              <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="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="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="showPosMachine" 
        :columns="posMachineList" 
        keyName="nameMerchantName" 
        @cancel="handlePosMachineCancel"
        @confirm="handlePosMachineConfirm"
        :closeOnClickOverlay="true"
        cancelColor="#666666"
        confirmColor="#667eea"
        title="选择POS机"
      ></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-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 { listPosmachine, getPosmachine } from '@/api/invest/posmachine'
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 showPosMachine = ref(false)
const showCreditCard = ref(false)
const title = ref("POS机刷卡记账")
const bankCardLendList = ref([])
const posMachineList = ref([])
const data = reactive({
  form: {
    id: null,
    name: null,
    type: '1',
    outAccountId: null,
    inAccountId: null,
    posId: null,
    commission: null,
    amount: null,
    actualAmount: null,
    dealType: '3',
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    rate: null,
    ratePlus: 0,
    remark: null
  },
  queryPosMachineParams: {
    pageNum: 1,
    status: '1',
    pageSize: 1000
  },
  queryBankCardLendParams: {
    pageNum: 1,
    type: '2',
   status: '1', 
    pageSize: 1000
  },
  rules: {
    outAccountName: [{ required: true, message: '信用卡不能为空', trigger:['change', 'blur'] }],
    posName: [{ required: true, message: 'POS机不能为空', trigger: ['change', 'blur'] }],
    // rate: [{type: 'string', required: true, message: '刷卡费率不能为空', trigger: ['change', 'blur'] }],
    // ratePlus: [{ required: true, message: '费率+不能为空', trigger:['change', 'blur'] }],
    amount: [{ type: 'number',required: true, message: '刷卡金额不能为空', trigger: ['change', 'blur'] }],
    createTime: [{ required: true, message: '刷卡时间不能为空', trigger: ['change', 'blur'] }]
  }
})
const { form, queryPosMachineParams, queryBankCardLendParams, rules} = toRefs(data)


onLoad((option) => {
       form.value.id = option.id
       if(form.value.id!=null){
        title.value="POS机刷卡记账-修改"
       }else{
        title.value="POS机刷卡记账-新增"
       }
      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] 
      })
      listPosmachine(queryPosMachineParams.value).then((response) => {
       posMachineList.value = [response.rows] 
       })
    
      if(form.value.id!=null){
        getAccountsTransferRecord(form.value.id).then(res => {
          form.value = res.data   
        })
      }
  }

  function handlePosMachine() {
        if (posMachineList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: 'POS机为空  ', type: 'warning'
          })
        } else {
          showPosMachine.value = true
        }
     }
  function   handlePosMachineConfirm(e) {
       form.value.posName = e.value[0].nameMerchantName
        form.value.posId = e.value[0].id
        getPosmachine(e.value[0].id).then((response) => {  
    form.value.rate = response.data.rate
    form.value.ratePlus = response.data.ratePlus
    showPosMachine.value = false
  })
        
  }
 function handlePosMachineCancel() {
       showPosMachine.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.outAccountName = e.value[0].nameCodeAvailableLimit
        form.value.outAccountId = 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.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/posTransferRecord/list` })
              }
            })
          })
          }else {
            addAccountsTransferRecord(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '新增成功', complete() {
                uni.navigateTo({ url: `/pages/work/accounts/posTransferRecord/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>