<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="inAccountName" required @click="handleFutruesStocks">
              <view class="input-with-arrow">
                <u--input v-model="form.inAccountName" readonly disabledColor="#ffffff" placeholder="请选择投资账户"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="交易类型" prop="dealTypeName" required @click="handleDealType">
              <view class="input-with-arrow">
                <u--input v-model="form.dealTypeName" readonly disabledColor="#ffffff" placeholder="请选择交易类型"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item> 
            <u-form-item label="转账时间" prop="createTime" required @click="selectDate()">
              <view class="input-with-arrow">
                <u--input v-model="form.createTime" readonly disabledColor="#ffffff" placeholder="请选择转账时间" inputAlign="left" :customStyle="inputBaseStyle"></u--input>
                <text class="arrow-icon">▼</text>
              </view>
            </u-form-item>
            <u-form-item label="转账金额" prop="amount" required >
              <u--input v-model="form.amount"  type="number" placeholder="请填写转账金额"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
            </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="showFutruesStocks" :columns="futruesStocksList" keyName="nameDebitNameCode" @cancel="handleFutruesStocksCancel"
        @confirm="handleFutruesStocksConfirm" :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"
      :closeOnClickOverlay="true"
      cancelColor="#666666"
      confirmColor="#667eea"
		></u-datetime-picker>
    </view>
  </template>
  
  <script setup>
  import {getAccountsTransferRecord, addAccountsTransferRecord, updateAccountsTransferRecord } from '@/api/invest/accountsTransferRecord'
  import { listFutureStocks } from '@/api/invest/futureStocks'
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 showFutruesStocks = ref(false)
const showDealType = ref(false)
const title = ref("投资账户记账")
const futruesStocksList = ref([])
const dealTypeList = ref([])
const flag = ref('add')
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: '3',
    outAccountId: null,
    inAccountId: null,
    posId: null,
    commission: null,
    amount: null,
    actualAmount: null,
    dealType: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null
  },
  queryFutruesStocksParams: {
    pageNum: 1,
    status: '1',
    pageSize: 1000
  },
  rules: {
    inAccountName: [{ 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, queryFutruesStocksParams, rules} = toRefs(data)


onLoad((option) => {
       form.value.id = option.id
     flag.value = option.flag
     
     // 接收从理财账户列表传递的参数
     if (option.investAccountId) {
       form.value.inAccountId = option.investAccountId
     }
     
     if(flag.value==null){
      if(form.value.id!=null){
      title.value="投资账户记账-修改"
     }else{
      title.value="投资账户记账-新增"
     }
     }else{
      title.value="投资账户记账-复制"
     }
      getData()
  })
  onReady(() => {
       form.value.createTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
  })
  function  getData() {
      listFutureStocks(queryFutruesStocksParams.value).then((response) => {
       futruesStocksList.value = [response.rows]
       
       // 如果有传递investAccountId参数，自动选中对应投资账户
       if (form.value.inAccountId && response.rows.length > 0) {
         const selectedAccount = response.rows.find(item => item.id === form.value.inAccountId)
         if (selectedAccount) {
           form.value.inAccountName = selectedAccount.nameDebitNameCode
         }
       } else if (!form.value.id && response.rows.length > 0) {
         // 新增时，默认选中第一条投资账户
         const firstAccount = response.rows[0]
         form.value.inAccountName = firstAccount.nameDebitNameCode
         form.value.inAccountId = firstAccount.id
       }
       })
           // 类型
           getDicts('in_out').then(res => {
        dealTypeList.value =[res.data] 
      })
      if(form.value.id!=null){
        getAccountsTransferRecord(form.value.id).then(res => {
          form.value = res.data   

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

  function handleFutruesStocks() {
        if (futruesStocksList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '投资账户为空  ', type: 'warning'
          })
        } else {
          showFutruesStocks.value = true
        }
     }
  function   handleFutruesStocksConfirm(e) {
       form.value.inAccountName = e.value[0].nameDebitNameCode
        form.value.inAccountId = e.value[0].id
        showFutruesStocks.value = false    
  }
 function handleFutruesStocksCancel() {
       showFutruesStocks.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) {
          if(flag.value==null){
            updateAccountsTransferRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '修改成功', complete() {
              uni.navigateBack()
            }
          })
        })
          }else {
            form.value.id == null
            addAccountsTransferRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateBack()
            }
          })
        })
          }
          }else {
            addAccountsTransferRecord(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '新增成功', complete() {
                uni.navigateBack()
              }
            })
          })
          }
        })
      }
  </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;
  
          .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>