<template>
  <view class="page-container" :style="containerStyle">
    <common-header title="新增返利" theme="rebate" @back="goBack" />
    
    <view class="add-content">
      <!-- 表单卡片 -->
      <view class="form-card">
        <uni-forms ref="form" :model="formData" :rules="rules" label-width="120">
          <!-- 基础信息区域 -->
          <view class="form-section">
            <view class="section-title">
              <uni-icons type="person" size="16" color="#4caf50" />
              <text>基础信息</text>
            </view>
            
            <uni-forms-item label="用户名称" name="userName" required>
              <uni-easyinput 
                v-model="formData.userName" 
                placeholder="请输入返利用户名称"
                maxlength="20"
                :clearable="true" 
                :focus="false" />
            </uni-forms-item>
            
            <uni-forms-item label="关联订单" name="orderNo">
              <uni-easyinput 
                v-model="formData.orderNo" 
                placeholder="请输入关联订单号（选填）"
                maxlength="32"
                :clearable="true" />
            </uni-forms-item>
          </view>
          
          <!-- 返利设置区域 -->
          <view class="form-section">
            <view class="section-title">
              <uni-icons type="wallet" size="16" color="#4caf50" />
              <text>返利设置</text>
            </view>
            
            <uni-forms-item label="返利金额" name="amount" required>
              <view class="amount-input-wrapper">
                <text class="currency-symbol">¥</text>
                <uni-easyinput 
                  v-model="formData.amount" 
                  placeholder="0.00"
                  type="digit"
                  :clearable="true" />
              </view>
            </uni-forms-item>
            
            <uni-forms-item label="返利类型" name="type">
              <uni-data-select 
                v-model="formData.type" 
                :localdata="typeOptions"
                placeholder="请选择返利类型" />
            </uni-forms-item>
            
            <uni-forms-item label="返利比例" name="percentage">
              <view class="percentage-input-wrapper">
                <uni-easyinput 
                  v-model="formData.percentage" 
                  placeholder="请输入返利比例"
                  type="digit"
                  :clearable="true" />
                <text class="percentage-symbol">%</text>
              </view>
            </uni-forms-item>
          </view>
          
          <!-- 详细信息区域 -->
          <view class="form-section">
            <view class="section-title">
              <uni-icons type="compose" size="16" color="#4caf50" />
              <text>详细信息</text>
            </view>
            
            <uni-forms-item label="返利描述" name="description">
              <uni-easyinput 
                v-model="formData.description" 
                type="textarea" 
                placeholder="请输入返利描述，如返利原因、计算方式等"
                maxlength="200"
                :auto-height="true" />
              <view class="char-count">{{ formData.description.length }}/200</view>
            </uni-forms-item>
            
            <uni-forms-item label="返利时间" name="rebateTime">
              <uni-datetime-picker 
                v-model="formData.rebateTime" 
                type="datetime"
                :clear-icon="true"
                placeholder="选择返利时间" />
            </uni-forms-item>
          </view>
        </uni-forms>
      </view>
      
      <!-- 操作按钮区域 -->
      <view class="action-section">
        <uni-button 
          class="action-btn cancel-btn" 
          @click="goBack">
          <uni-icons type="close" size="18" color="#666" />
          取消
        </uni-button>
        <uni-button 
          class="action-btn submit-btn" 
          type="primary" 
          @click="submitForm"
          :loading="submitting">
          <uni-icons type="checkmarkempty" size="18" color="#fff" />
          保存返利
        </uni-button>
      </view>
    </view>
  </view>
</template>

<script>
import CommonHeader from '@/components/common-header/common-header.vue'

export default {
  name: 'RebateAdd',
  components: {
    CommonHeader
  },
  
  data() {
    return {
      headerHeight: 120, // 默认头部高度
      formData: {
        userName: '',
        orderNo: '',
        amount: '',
        type: '',
        percentage: '',
        description: '',
        rebateTime: ''
      },
      rules: {
        userName: {
          rules: [
            { required: true, errorMessage: '请输入用户名称' },
            { minLength: 2, maxLength: 20, errorMessage: '用户名称长度在2-20字符之间' }
          ]
        },
        amount: {
          rules: [
            { required: true, errorMessage: '请输入返利金额' },
            { 
              validateFunction: (rule, value, data, callback) => {
                if (value && (isNaN(value) || parseFloat(value) <= 0)) {
                  callback('请输入有效的金额')
                  return
                }
                callback()
              }
            }
          ]
        },
        percentage: {
          rules: [
            { 
              validateFunction: (rule, value, data, callback) => {
                if (value && (isNaN(value) || parseFloat(value) < 0 || parseFloat(value) > 100)) {
                  callback('返利比例应在0-100之间')
                  return
                }
                callback()
              }
            }
          ]
        },
        description: {
          rules: [
            { maxLength: 200, errorMessage: '返利描述不能超过200字符' }
          ]
        }
      },
      typeOptions: [
        { value: 'order', text: '订单返利' },
        { value: 'referral', text: '推荐返利' },
        { value: 'loyalty', text: '忠诚返利' },
        { value: 'promotion', text: '促销返利' },
        { value: 'other', text: '其他返利' }
      ],
      submitting: false
    }
  },
  
  computed: {
    containerStyle() {
      return {
        paddingTop: (this.headerHeight + 10) + 'px'
      }
    }
  },
  
  onLoad() {
    this.listenHeaderHeight()
    this.calculateHeaderHeight()
  },
  
  onReady() {
    // 延迟计算头部高度，确保页面渲染完成
    setTimeout(() => {
      this.calculateHeaderHeight()
    }, 100)
  },
  
  onShow() {
    setTimeout(() => {
      this.calculateHeaderHeight()
    }, 50)
  },
  
  onUnload() {
    uni.$off('header-height-updated', this.onHeaderHeightUpdated)
  },
  
  methods: {
    // 头部高度管理
    listenHeaderHeight() {
      uni.$on('header-height-updated', this.onHeaderHeightUpdated)
    },
    
    onHeaderHeightUpdated(height) {
      this.headerHeight = height
      // 强制更新视图
      this.$forceUpdate()
    },
    
    calculateHeaderHeight() {
      // #ifdef MP-WEIXIN
      try {
        const systemInfo = uni.getSystemInfoSync()
        const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
        
        if (menuButtonInfo && systemInfo) {
          // 计算头部高度：状态栏高度 + 导航栏高度
          const statusBarHeight = systemInfo.statusBarHeight || 0
          const navBarHeight = menuButtonInfo.bottom + 8
          this.headerHeight = navBarHeight
          
          // 发送头部高度更新事件
          uni.$emit('header-height-updated', this.headerHeight)
                 } else {
           this.headerHeight = 120
         }
       } catch (error) {
         console.error('获取头部高度失败:', error)
         this.headerHeight = 120
       }
      // #endif
      
      // #ifdef APP-PLUS
      this.headerHeight = 100
      uni.$emit('header-height-updated', this.headerHeight)
      // #endif
      
      // #ifdef H5
      this.headerHeight = 80
      uni.$emit('header-height-updated', this.headerHeight)
      // #endif
    },
    
    async submitForm() {
      try {
        // 表单验证
        const valid = await this.$refs.form.validate()
        if (!valid) return
        
        // 验证金额格式
        if (this.formData.amount && !/^\d+(\.\d{1,2})?$/.test(this.formData.amount)) {
          this.$modal.showToast('请输入正确的金额格式')
          return
        }
        
        // 验证比例格式
        if (this.formData.percentage && !/^\d+(\.\d{1,2})?$/.test(this.formData.percentage)) {
          this.$modal.showToast('请输入正确的比例格式')
          return
        }
        
        this.submitting = true
        
        // 准备提交数据
        const submitData = {
          ...this.formData,
          amount: this.formData.amount ? parseFloat(this.formData.amount) : 0,
          percentage: this.formData.percentage ? parseFloat(this.formData.percentage) : 0,
          createTime: new Date().toISOString()
        }
        
        // TODO: Replace with actual API call
        const response = await this.$http.post('/brewery/rebate', submitData)
        
        this.$modal.showToast('保存成功')
        
        // 返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        console.error('保存失败:', error)
        this.$modal.showToast('保存失败')
      } finally {
        this.submitting = false
      }
    },
    
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.add-content {
  padding: 20rpx;
  padding-top: 30rpx;
  padding-bottom: 200rpx;
  padding-bottom: calc(200rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(200rpx + env(safe-area-inset-bottom));
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20rpx;
}

.form-section {
  padding: 30rpx;
  
  &:not(:last-child) {
    border-bottom: 1rpx solid #f0f0f0;
  }
  
  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    padding-bottom: 12rpx;
    border-bottom: 2rpx solid #e8f5e8;
    
    text {
      margin-left: 8rpx;
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
}

// 表单项样式
:deep(.uni-forms-item) {
  margin-bottom: 24rpx;
  
  .uni-forms-item__label {
    color: #333;
    font-weight: 500;
  }
  
  .uni-easyinput {
    .uni-easyinput__content {
      border-radius: 8rpx;
      border: 1rpx solid #e0e0e0;
      transition: all 0.3s ease;
      
      &:focus-within {
        border-color: #4caf50;
        box-shadow: 0 0 0 2rpx rgba(76, 175, 80, 0.1);
      }
    }
  }
  
  .uni-data-select {
    .uni-stat__select {
      border-radius: 8rpx;
      border: 1rpx solid #e0e0e0;
      transition: all 0.3s ease;
      
      &:focus-within {
        border-color: #4caf50;
        box-shadow: 0 0 0 2rpx rgba(76, 175, 80, 0.1);
      }
    }
  }
}

// 金额输入样式
.amount-input-wrapper {
  display: flex;
  align-items: center;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 0 16rpx;
  background: #fff;
  transition: all 0.3s ease;
  
  &:focus-within {
    border-color: #4caf50;
    box-shadow: 0 0 0 2rpx rgba(76, 175, 80, 0.1);
  }
  
  .currency-symbol {
    color: #4caf50;
    font-size: 32rpx;
    font-weight: 600;
    margin-right: 8rpx;
  }
  
  :deep(.uni-easyinput) {
    flex: 1;
    
    .uni-easyinput__content {
      border: none;
      background: transparent;
    }
  }
}

// 百分比输入样式
.percentage-input-wrapper {
  display: flex;
  align-items: center;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 0 16rpx;
  background: #fff;
  transition: all 0.3s ease;
  
  &:focus-within {
    border-color: #4caf50;
    box-shadow: 0 0 0 2rpx rgba(76, 175, 80, 0.1);
  }
  
  :deep(.uni-easyinput) {
    flex: 1;
    
    .uni-easyinput__content {
      border: none;
      background: transparent;
    }
  }
  
  .percentage-symbol {
    color: #4caf50;
    font-size: 32rpx;
    font-weight: 600;
    margin-left: 8rpx;
  }
}

// 字符计数
.char-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

// 操作按钮区域
.action-section {
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
  margin-top: 40rpx;
  background: #fff;
  border-radius: 16rpx 16rpx 0 0;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);
  padding-bottom: 40rpx;
  padding-bottom: calc(40rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
}

.action-btn {
  flex: 1;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 600;
  transition: all 0.3s ease;
  
  &.cancel-btn {
    background: #f5f5f5;
    border: 1rpx solid #e0e0e0;
    color: #666;
    
    &:hover {
      background: #e8e8e8;
    }
  }
  
  &.submit-btn {
    background: linear-gradient(135deg, #4caf50 0%, #45a049 100%);
    color: #fff;
    border: none;
    box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
    
    &:hover {
      transform: translateY(-2rpx);
      box-shadow: 0 6rpx 16rpx rgba(76, 175, 80, 0.4);
    }
    
    &:active {
      transform: translateY(0);
    }
  }
}

// 按钮内图标样式
.action-btn .uni-icons {
  margin-right: 8rpx;
}
</style> 