<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="160rpx"
            :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
            <u-form-item label="股票账户" prop="futureStocksName" required @click="handleFutureStocks">
              <view class="input-with-arrow">
                <u--input v-model="form.futureStocksName" readonly placeholder="请选择股票账户" :customStyle="getInputStyle('futureStocksName')" disabledColor="#ffffff" inputAlign="left"></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 placeholder="请选择账单日" :customStyle="getInputStyle('billDate')" disabledColor="#ffffff" inputAlign="left"></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="getInputStyle('billAmount')"></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"></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"></u-picker>
        <u-datetime-picker
			:show="datePickShow"
			mode="date"
      :minDate="-2209017600000"
      ref="createTimeRef" 
			@cancel="datePickShow=false"
			@confirm="datePickConfirm"
			itemHeight="88"
		></u-datetime-picker>
    <u-picker 
      itemHeight="88" 
      :show="showFutureStocks" 
      :columns="futureStocksBillList" 
      keyName="nameCode" 
      @cancel="handleFutureStocksCancel"
      @confirm="handleFutureStocksConfirm"
      ></u-picker>
    </view>
  </template>
  
  <script setup>
import {getFutureStocksBill, addFutureStocksBill, updateFutureStocksBill } from '@/api/invest/futureStocksBill'
  import { listFutureStocks } 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 showTeam = ref(false)
const showFutureStocks = ref(false)
const title = ref("股票账单")
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}
const errorFields = ref([])
const inputErrorStyle = {
  background: '#fef0f0',
  border: '2rpx solid #f56c6c',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}
const getInputStyle = (field) => {
  return errorFields.value.includes(field) ? inputErrorStyle : inputBaseStyle
}
const futureStocksBillList = ref([])
const billStateList = ref([])
const data = reactive({
  form: {
    id: null,
    name: null,
    billDate: null,
    futureStocksId: null,
    billDatePeriod: null,
    billAmount: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    type: '2',
    remark: null,
    billYear: null,
    billMonth: null
  },
  queryFutureStocksListParams: {
    pageNum: 1,
    type: '2',
    status: '1',
    pageSize: 1000
  },
  rules: {
           futureStocksName: [{ type: 'string', required: true, message: '股票账户不能为空', trigger: ['change', 'blur'] }],
          billDate: [{ type: 'string', required: true, message: '账单日不能为空', trigger: ['change', 'blur'] }],
          billAmount: [{ type: 'number', required: true, message: '股票收益不能为空', trigger: ['change', 'blur'] }],
  }
})
const { form, queryFutureStocksListParams, 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() {
    listFutureStocks(queryFutureStocksListParams.value).then((response) => {
        futureStocksBillList.value = [response.rows] 
      })
      if(form.value.id!=null){
        getFutureStocksBill(form.value.id).then(res => {
          form.value = res.data
          form.value.futureStocksName = res.data.futureStocksNameCode 
        })
      }
  }
  function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
    }

      function handleFutureStocks() {
        if (futureStocksBillList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '股票账户为空  ', type: 'warning'
          })
        } else {
          showFutureStocks.value = true
        }
     }
  function   handleFutureStocksConfirm(e) {
        form.value.futureStocksName = e.value[0].nameCode
        form.value.futureStocksId= e.value[0].id
        showFutureStocks.value = false
  }
 function handleFutureStocksCancel() {
       showFutureStocks.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() {
        errorFields.value = []
  proxy.$refs['uForm'].validate().then(() => {
          if (form.value.id != null) {
            updateFutureStocksBill(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '修改成功', complete() {
                uni.navigateTo({ url: `/pages/work/bill/stocksBill/list` })
              }
            })
          })
          }else {
            addFutureStocksBill(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '新增成功', complete() {
                uni.navigateTo({ url: `/pages/work/bill/stocksBill/list` })
              }
            })
          })
          }
        }).catch(errors => {
          if (errors && errors.length > 0) {
            errorFields.value = errors.map(err => err.field)
          }
          proxy.$modal.msgError('请填写完整信息')
        })
      }
  </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;



    .form-btn {
      padding-top: 20rpx;
    }
  }
}
  </style>
  
  