<template>

 <div class="p-2">
    <div class="filter-set-container">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="快递类型" prop="type">
                  <el-form-item label="订单类型" >
                  <el-select v-model="queryParams.orderType" placeholder="请选择订单类型" clearable width="300px">
                    <el-option label="普通订单" value="NORMAL_ORDDER_TPYE" />
                    <el-option label="团购订单" value="GROUP_ORDDER_TPYE" />
                    <el-option label="秒杀订单" value="SECKILL_ORDDER_TPYE" />
            </el-select>
            </el-form-item>
            </el-form-item>

     
            <el-form-item>
          <el-button type="primary" @click="loadData">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
     </div>


    <el-card shadow="never">
      <template #header >
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" >新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate(this)" >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete(this)" >删除</el-button>
          </el-col> -->

          <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>
      </template>
    <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="orderType" label="订单类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getOrderTypeTag(row.orderType)">
              {{ getOrderTypeText(row.orderType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="config" label="分润配置">
          <template #default="{ row }">
            <div v-for="(config, key) in row.config" :key="key" class="config-item">
              <span class="config-label">{{ getRoleLabel(key) }}:</span>
              <el-tag size="small">
                {{ config.type === 1 ? '百分比' : '固定金额' }}: {{ config.value }}{{ config.type === 1 ? '%' : '元' }}
              </el-tag>
            </div>
            <div v-if="row.config.upwardProfit" class="upward-info">
              <el-tag type="info" size="small">向上分润: {{ row.config.upwardProfit.enabled ? '开启' : '关闭' }}</el-tag>
              <el-tag v-if="row.config.upwardProfit.enabled" type="success" size="small">
                一级: {{ row.config.upwardProfit.floor1 ? '显示' : '隐藏' }}
              </el-tag>
              <el-tag v-if="row.config.upwardProfit.enabled && row.config.upwardProfit.floor1" type="warning" size="small">
                二级: {{ row.config.upwardProfit.floor2 ? '显示' : '隐藏' }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadData"
          @current-change="loadData"
        />
      </div>

   </el-card>
    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="700px"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="form.orderType" placeholder="请选择订单类型">
            <el-option label="普通订单" value="NORMAL_ORDDER_TPYE" />
            <el-option label="团购订单" value="GROUP_ORDDER_TPYE" />
            <el-option label="秒杀订单" value="SECKILL_ORDDER_TPYE" />
          </el-select>
        </el-form-item>

        <!-- 向上分润控制 -->
        <el-form-item label="代理分润控制">
          <div class="upward-control">
            <el-switch
              v-model="form.config.upwardProfit.enabled"
              active-text="启用代理分润"
              inactive-text="关闭代理分润"
              @change="handleUpwardProfitChange"
            />
            <div v-if="form.config.upwardProfit.enabled" class="upward-options">
              <el-checkbox 
                v-model="form.config.upwardProfit.floor1" 
                label="一级代理分润"
                @change="handleFloor1Change"
              />
              <!-- <el-checkbox 
                v-model="form.config.upwardProfit.floor2" 
                label="显示二级分润"
                :disabled="!form.config.upwardProfit.floor1"
              /> -->
            </div>
          </div>
        </el-form-item>

        <el-form-item label="分润配置" prop="config">
          <div class="config-form">
            <!-- 平台自身分润（始终显示） -->
            <div class="config-row">
              <span class="role-label">{{ roleOptions.self.label }}:</span>
              <el-radio-group v-model="form.config.self.type">
                <el-radio :label="1">百分比</el-radio>
                <el-radio :label="2">固定金额</el-radio>
              </el-radio-group>
              <el-input-number
                v-model="form.config.self.value"
                :min="0"
                :max="form.config.self.type === 1 ? 100 : 999999"
                :precision="2"
                controls-position="right"
              />
              <span class="unit">{{ form.config.self.type === 1 ? '%' : '元' }}</span>
            </div>

            <!-- 一级分润（根据控制显示） -->
            <div v-if="form.config.upwardProfit.enabled && form.config.upwardProfit.floor1" class="config-row">
              <span class="role-label">{{ roleOptions.floor1.label }}:</span>
              <el-radio-group v-model="form.config.floor1.type">
                <el-radio :label="1">百分比</el-radio>
                <el-radio :label="2">固定金额</el-radio>
              </el-radio-group>
              <el-input-number
                v-model="form.config.floor1.value"
                :min="0"
                :max="form.config.floor1.type === 1 ? 100 : 999999"
                :precision="2"
                controls-position="right"
              />
              <span class="unit">{{ form.config.floor1.type === 1 ? '%' : '元' }}</span>
            </div>

            <!-- 二级分润（根据控制显示） -->
            <!-- <div v-if="form.config.upwardProfit.enabled && form.config.upwardProfit.floor1 && form.config.upwardProfit.floor2" class="config-row">
              <span class="role-label">{{ roleOptions.floor2.label }}:</span>
              <el-radio-group v-model="form.config.floor2.type">
                <el-radio :label="1">百分比</el-radio>
                <el-radio :label="2">固定金额</el-radio>
              </el-radio-group>
              <el-input-number
                v-model="form.config.floor2.value"
                :min="0"
                :max="form.config.floor2.type === 1 ? 100 : 999999"
                :precision="2"
                controls-position="right"
              />
              <span class="unit">{{ form.config.floor2.type === 1 ? '%' : '元' }}</span>
            </div> -->

            <!-- 分润比例提示 -->
            <div v-if="showPercentWarning" class="percent-warning">
              <el-alert
                title="百分比总和超过100%，请调整分润比例"
                type="warning"
                :closable="false"
                show-icon
              />
            </div>
          </div>
        </el-form-item>


      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

 </div>

</template>

<script setup>
import { getCurrentInstance } from 'vue';
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { profitconfigApi } from '@/api/modules/profitconfig';



const { proxy } = getCurrentInstance();

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const formRef = ref()
const tableData = ref([])
const total = ref(0)
const isEdit = ref(false)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderType: ''
})

// 表单数据
const form = reactive({
  id: null,
  orderType: '',
  config: {
    self: { type: 1, value: 0 },
    floor1: { type: 1, value: 0 },
    floor2: { type: 1, value: 0 },
    upwardProfit: {
      enabled: false,
      floor1: false,
      floor2: false
    }
  },
  remark: ''
})

// 角色选项
const roleOptions = {
  self: { label: '用户分润' },
  floor1: { label: '一级代理分润' }
  // floor2: { label: '二级分润' }
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑分润配置' : '新增分润配置')

const showPercentWarning = computed(() => {
  let totalPercent = 0
  
  // 平台自身分润
  if (form.config.self.type === 1) {
    totalPercent += form.config.self.value
  }
  
  // 一级分润（如果启用且显示）
  if (form.config.upwardProfit.enabled && form.config.upwardProfit.floor1 && form.config.floor1.type === 1) {
    totalPercent += form.config.floor1.value
  }
  
//   // 二级分润（如果启用且显示）
//   if (form.config.upwardProfit.enabled && form.config.upwardProfit.floor1 && form.config.upwardProfit.floor2 && form.config.floor2.type === 1) {
//     totalPercent += form.config.floor2.value
//   }
  
  return totalPercent > 100
})

// 表单验证规则
const rules = {
  orderType: [{ required: true, message: '请选择订单类型', trigger: 'change' }],
  config: [
    {
      validator: (rule, value, callback) => {
        const errors = []
        
        // 检查百分比总和
        let totalPercent = 0
        let percentItems = []
        
        if (value.self.type === 1) {
          totalPercent += value.self.value
          percentItems.push(`用户分润: ${value.self.value}%`)
        }
        
        if (value.upwardProfit.enabled && value.upwardProfit.floor1 && value.floor1.type === 1) {
          totalPercent += value.floor1.value
          percentItems.push(`一级代理分润: ${value.floor1.value}%`)
        }
        

        
        if (totalPercent > 100) {
          errors.push(new Error(`百分比总和${totalPercent}%超过100%，请调整`))
        }
        
        // 检查一级分润显示时必须有值
        if (value.upwardProfit.enabled && value.upwardProfit.floor1) {
          if (value.floor1.value <= 0) {
            errors.push(new Error('一级分润必须设置大于0的值'))
          }
        }
        
        // 检查二级分润显示时必须有值
        if (value.upwardProfit.enabled && value.upwardProfit.floor1 && value.upwardProfit.floor2) {
          if (value.floor2.value <= 0) {
            errors.push(new Error('二级分润必须设置大于0的值'))
          }
        }
        
        if (errors.length > 0) {
          callback(errors)
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 监听向上分润配置变化
watch(() => form.config.upwardProfit, (newVal) => {
  // 如果关闭向上分润，隐藏所有上级分润
  if (!newVal.enabled) {
    form.config.upwardProfit.floor1 = false
    // form.config.upwardProfit.floor2 = false
  }
}, { deep: true })

// 方法
const getOrderTypeTag = (type) => {
  const map = { NORMAL_ORDDER_TPYE: '', GROUP_ORDDER_TPYE: 'success', SECKILL_ORDDER_TPYE: 'danger' }
  return map[type] || ''
}

const getOrderTypeText = (type) => {
  const map = { NORMAL_ORDDER_TPYE: '普通订单', GROUP_ORDDER_TPYE: '团购订单', SECKILL_ORDDER_TPYE: '秒杀订单' }
  return map[type] || type
}

const getRoleLabel = (key) => {
  return roleOptions[key]?.label || key
}

const handleUpwardProfitChange = (enabled) => {
  if (!enabled) {
    // 关闭向上分润时，重置一级二级分润的值
    form.config.floor1.value = 0
    // form.config.floor2.value = 0
  }
}

const handleFloor1Change = (showFloor1) => {
  if (!showFloor1) {
    // 隐藏一级分润时，同时隐藏二级分润并重置其值
    form.config.upwardProfit.floor2 = false
    // form.config.floor2.value = 0
  }
}

const loadData = async () => {
  loading.value = true
  try {
    // 调用API
    const response = await axios.get('/api/profit-sharing/config/list', { params: queryParams })
    tableData.value = response.data.rows
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    orderType: ''
  })
  loadData()
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  // 深拷贝数据，确保编辑不影响原数据
  const rowData = JSON.parse(JSON.stringify(row))
  
  // 确保upwardProfit结构完整
  if (!rowData.config.upwardProfit) {
    rowData.config.upwardProfit = {
      enabled: false,
      floor1: false
    //   floor2: false
    }
  }
  
  Object.assign(form, rowData)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定删除该分润配置吗？', '提示', { type: 'warning' })
    await axios.delete(`/api/profit-sharing/config/${row.id}`)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    orderType: '',
    config: {
      self: { type: 1, value: 0 },
      floor1: { type: 1, value: 0 },
      floor2: { type: 1, value: 0 },
      upwardProfit: {
        enabled: false,
        floor1: false,
        floor2: false
      }
    },
    remark: ''
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 准备提交的数据
    const submitData = JSON.parse(JSON.stringify(form))
    



    // 如果向上分润关闭，清理一级二级分润的值
    if (!submitData.config.upwardProfit.enabled) {
      submitData.config.floor1.value = 0

    }
    // // 如果一级分润隐藏，清理二级分润的值
    // else if (!submitData.config.upwardProfit.floor1) {
    //   submitData.config.floor2.value = 0
    // }

    // 添加必要的字段或转换格式
    if (!submitData.createTime) {
        submitData.createTime = Date.now();
    }
    if (!submitData.updateTime) {
        submitData.updateTime = Date.now();
    }

    // 确保 config 字段是字符串（如果 configObj 存在）
    if (submitData.configObj && !submitData.config) {
        submitData.config = JSON.stringify(submitData.configObj);
    }


    
    const api = isEdit.value 
      ? profitconfigApi.updateProfitconfig(submitData)
      : profitconfigApi.addProfitconfig(submitData)
    
    await api
    ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    if (error.errorFields) {
      ElMessage.error('表单验证失败，请检查输入')
    } else {
      ElMessage.error('操作失败')
    }
  }
}

// 生命周期
onMounted(() => {
  // loadData()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.config-item {
  margin-bottom: 4px;
}

.config-label {
  display: inline-block;
  width: 80px;
  font-weight: bold;
}

.upward-info {
  margin-top: 8px;
}

.upward-info .el-tag {
  margin-right: 5px;
}

.config-form {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
}

.config-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.role-label {
  width: 100px;
  font-weight: bold;
}

.unit {
  margin-left: 8px;
  width: 30px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.upward-control {
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.upward-options {
  margin-top: 12px;
}

.upward-options .el-checkbox {
  margin-right: 20px;
}

.percent-warning {
  margin-top: 10px;
}
</style>