<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="auto"
            :labelStyle="{ color: '#333333', fontSize: '30rpx' }">
            <u-form-item label="投资账户" prop="accountName" required @click="handleAccountName">
              <u--input v-model="form.accountName" 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="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="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" v-show="!futuresShow"  required >
              <u--input v-model="form.amount"  type="number" placeholder="请填写交易金额"
                inputAlign="right" border="none"></u--input>
            </u-form-item>
            <u-form-item label="平仓盈亏" prop="closedPosition" v-show="futuresShow"  required >
              <u--input v-model="form.closedPosition"  type="number" placeholder="请填写平仓盈亏"
                inputAlign="right" border="none"></u--input>
            </u-form-item>
            <u-form-item label="手续费" prop="commission" v-show="futuresShow"  required >
              <u--input v-model="form.commission"  type="number" placeholder="请填写手续费"
                inputAlign="right" border="none"></u--input>
            </u-form-item>
            <u-form-item label="备注" v-show="!futuresShow" 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: 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="showAccountName" :columns="accountNameList" keyName="nameCodeAvailableLimit" @cancel="handleAccountNameCancel"
        @confirm="handleAccountNameConfirm" :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 {getAccountDealRecord, addAccountDealRecord, updateAccountDealRecord } from '@/api/invest/accountDealRecord'
  import { getDicts } from '@/api/system/dict/data.js'
  import { listAccounts } from '@/api/invest/accounts'
  import { getFutureStocks } from '@/api/invest/futureStocks'
  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 showAccountType = ref(false)
const showAccountName = ref(false)
const showDealCategory = ref(false)
const showDealType = ref(false)
const title = ref("投资交易记录")
const accountTypeList = ref([])
const accountNameList = ref([])
const dealTypeList = ref([])
const futuresShow = ref(false)
//账户类型
const accountType = ref(0)
const data = reactive({
  form: {
    id: null,
    name: null,
    type: '5',
    accountId: null,
    amount: null,
    dealType: "1",
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    dealCategory: '2',
    childCategory: '2'
  },
  queryAccountParams: {
    pageNum: 1,
    type: '5',
   status: '1', 
    pageSize: 1000
  },
  rules: {
    accountName: [{ required: true, message: '投资账户不能为空', trigger: ['change', 'blur'] }],
    amount: [{type: 'number', required: true, message: '交易金额不能为空', trigger: ['blur'] }],
    dealTypeName: [{ required: true, message: '交易类型不能为空', trigger:['change', 'blur'] }],
    closedPosition: [{type: 'number',  required: true, message: '平仓盈亏不能为空', trigger: 'blur' }],
    commission: [{ type: 'number', required: true, message: '手续费不能为空', trigger: 'blur' }],
    createTime: [{ required: true, message: '交易时间不能为空', trigger: ['change', 'blur'] }]
  }
})
const { form, queryAccountParams, rules} = toRefs(data)


onLoad((option) => {
       form.value.id = option.id
       if(form.value.id!=null){
        title.value="投资交易记录-修改"
       }else{
        title.value="投资交易记录-新增"
       }
     
  })
  onReady(() => {
    form.value.createTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
    getData()
  })
  function  getData() {
       // 类型
       getDicts('profit_loss').then(res => {
        dealTypeList.value =[res.data] 
      })
      listAccounts(queryAccountParams.value).then((response) => {
    accountNameList.value = [response.rows] 
  })
      if(form.value.id!=null){
        getAccountDealRecord(form.value.id).then(res => {
          form.value = res.data
          // 交易类型
          getDicts('profit_loss').then(result => {
          form.value.dealTypeName=dictStr(form.value.dealType, result.data)
         })
         queryAccountParams.value.type = ""
        listAccounts(queryAccountParams.value).then((response) => {
          accountNameList.value = [response.rows] 
         })    
        })
      }
  }
  function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
    }
      function handleAccountName() {
        if (accountNameList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '投资账户为空  ', type: 'warning'
          })
        } else {
          showAccountName.value = true
        }
     }
  function   handleAccountNameConfirm(e) {
        form.value.accountName = e.value[0].nameCodeAvailableLimit
        form.value.accountId = e.value[0].id
       let accountId=e.value[0].id
        if (accountId != null && accountId != '') {
    getFutureStocks(accountId).then((response) => {
      const account = response.data
      accountType.value = account.type
      if (account.type == '1') {
        futuresShow.value = true
        form.value.amount = 0
        form.value.closedPosition = null
        form.value.commission = null
      } else {
        futuresShow.value = false
        form.value.amount = null
        form.value.closedPosition = 0
        form.value.commission = 0
      }
    })
  }

        showAccountName.value = false
  }
 function handleAccountNameCancel() {
       showAccountName.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  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 (accountType.value == '1') {
        form.value.remark = '平仓盈亏' + form.value.closedPosition + '，手续费' + form.value.commission
        form.value.amount = form.value.closedPosition - form.value.commission
      }
      //如果是亏损，金额乘以-1
      if (form.value.amount >= 0) {
        form.value.dealType = '1'
      } else {
        form.value.dealType = '2'
        form.value.amount = form.value.amount * -1
      }
          if (form.value.id != null) {
            updateAccountDealRecord(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '修改成功', complete() {
                uni.navigateTo({ url: `/pages/work/accounts/investAccountDeal/list` })
              }
            })
          })
          }else {
            addAccountDealRecord(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '新增成功', complete() {
                uni.navigateTo({ url: `/pages/work/accounts/investAccountDeal/list` })
              }
            })
          })
          }
        })
      }
  </script>
  
  <style lang="scss" scoped>
  .section {
    margin: 24rpx;
    padding: 16rpx 24rpx;
    background-color: #fff;
    border-radius: 8rpx;
  
    .section-title {
      width: 360rpx;
      color: #333333;
      line-height: 44rpx;
      font-size: 30rpx;
      border-left: 6rpx solid #2681FF;
      padding-left: 26rpx;
    }
  
    .form-view {
      padding: 20rpx 0rpx 0 10rpx;
  
      .form-btn {
        padding-top: 20rpx;
      }
    }
  }
  </style>