<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="200px" v-loading="formLoading">
      <template v-if="formType == 'update1'">
        <el-form-item label="毛利百分比" prop="grossProfitPerc">
          <template #label>
            <Tooltip message="例(0.3888)" title="毛利" />
          </template>
          <el-input v-model="formData.grossProfitPerc" placeholder="请输入毛利百分比">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="用户自得" prop="grossProfitUserQuotaPerc">
          <template #label>
            <Tooltip message="例(35),用户自得+直推奖+合赢奖+平台服务费,总和不能超过100" title="用户自得" />
          </template>
          <el-input v-model="formData.grossProfitUserQuotaPerc" placeholder="请输入用户自得">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="直推奖" prop="grossProfitAncestorQuotaPerc">
          <template #label>
            <Tooltip message="例(35),用户自得+直推奖+合赢奖+平台服务费,总和不能超过100" title="直推奖" />
          </template>
          <el-input v-model="formData.grossProfitAncestorQuotaPerc" placeholder="请输入直推奖">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="合赢奖" prop="grossProfitBonusQuotaPerc">
          <template #label>
            <Tooltip message="例(22),用户自得+直推奖+合赢奖+平台服务费,总和不能超过100" title="合赢奖" />
          </template>
          <el-input v-model="formData.grossProfitBonusQuotaPerc" placeholder="请输入合赢奖">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="平台服务费" prop="grossProfitPlatformQuotaPerc">
          <template #label>
            <Tooltip message="例(35),用户自得+直推奖+合赢奖+平台服务费,总和不能超过100" title="平台服务费" />
          </template>
          <el-input v-model="formData.grossProfitPlatformQuotaPerc" placeholder="请输入平台服务费">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="分成" prop="divideIntoPerc">
          <el-input v-model="formData.divideIntoPerc" placeholder="请输入分成">
            <template #append>%</template>
          </el-input>
        </el-form-item>
      </template>
      <template v-else-if="formType == 'withdraw'">
        <el-form-item label="提现比例" prop="withdrawCommission">
          <template #label>
            <Tooltip message="例80%,提现比例+消费分比例必须等于100%" title="提现比例" />
          </template>
          <el-input v-model="formData.withdrawCommission" placeholder="请输入提现比例">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="消费分比例" prop="withdrawConsumption">
          <template #label>
            <Tooltip message="例20%,提现比例+消费分比例必须等于100%" title="消费分比例" />
          </template>
          <el-input v-model="formData.withdrawConsumption" placeholder="请输入消费分比例">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        
      </template>
      <template v-else-if="formType == 'update2'">
        <el-form-item label="购物自得" prop="orderUserSocialStatus">
          <el-input v-model="formData.orderUserSocialStatus" placeholder="请输入购物自得" />
        </el-form-item>
        <el-form-item label="购物推荐人获得" prop="orderAncestorSocialStatus">
          <el-input v-model="formData.orderAncestorSocialStatus" placeholder="请输入购物推荐人获得" />
        </el-form-item>
        <el-form-item label="注册默认身价" prop="registerSocialStatus">
          <el-input v-model="formData.registerSocialStatus" placeholder="请输入注册默认身价" />
        </el-form-item>
        <el-form-item label="推荐注册身价" prop="registerAncestorSocialStatus">
          <el-input v-model="formData.registerAncestorSocialStatus" placeholder="请输入推荐注册身价" />
        </el-form-item>
        <el-form-item label="收藏获得" prop="collectSocialStatus">
          <el-input v-model="formData.collectSocialStatus" placeholder="请输入收藏获得" />
        </el-form-item>
        <el-form-item label="签到获得" prop="signInsocialstatus">
          <el-input v-model="formData.signInSocialStatus" placeholder="请输入签到获得" />
        </el-form-item>
        <el-form-item label="签到可获得最大身价值" prop="signInsocialstatusMax">
          <el-input v-model="formData.signInSocialStatusMax" placeholder="请输入签到获得" />
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="充值倍率" prop="consumptionMagnification">
          <el-input v-model="formData.consumptionMagnification" placeholder="请输入充值倍率" >
            <template #append>%</template>
          </el-input> 
        </el-form-item>
        <el-form-item label="触发倍率的最低金额" prop="triggerMagnificationPoints">
          <el-input v-model="formData.triggerMagnificationPoints" placeholder="请输入触发倍率的最低金额" />
        </el-form-item>
        <!-- <el-form-item label="首次最低充值金额" prop="firstTopUpConsumption">
          <el-input v-model="formData.firstTopUpConsumption" placeholder="请输入首次最低充值金额" />
        </el-form-item> -->
        <!-- <el-form-item label="后续单次最低充值金额" prop="followUpConsumption">
          <el-input v-model="formData.followUpConsumption" placeholder="请输入后续单次最低充值金额" />
        </el-form-item>-->
        <el-form-item label="用户单次最低充值金额" prop="userTopUpConsumptionPoints">
          <el-input v-model="formData.userTopUpConsumptionPoints" placeholder="用户单次最低充值金额" />
        </el-form-item> 
      </template>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>

    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { OrderPercentageApi, OrderPercentageVO } from '@/api/system/distri/orderpercentage'

/** 佣金相关计算浮动设置 表单 */
defineOptions({ name: 'OrderPercentageForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('编辑') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  grossProfitPerc: undefined,
  grossProfitUserQuotaPerc: undefined,
  grossProfitAncestorQuotaPerc: undefined,
  grossProfitBonusQuotaPerc: undefined,
  grossProfitPlatformQuotaPerc: undefined,
  divideIntoPerc: undefined,
  orderUserSocialStatus: undefined,
  orderAncestorSocialStatus: undefined,
  registerSocialStatus: undefined,
  registerAncestorSocialStatus: undefined,
  collectSocialStatus: undefined,
  signInSocialStatus:undefined,
  signInSocialStatusMax:undefined,
  consumptionMagnification: undefined,
  firstTopUpConsumption: undefined,
  followUpConsumption: undefined,
  withdrawCommission: undefined,
  withdrawConsumption:undefined,
  userTopUpConsumptionPoints:undefined,
  triggerMagnificationPoints:undefined
}) // 表单数据

const totalPercentage = computed(() => {
  return Number(formData.value.grossProfitUserQuotaPerc) +
    Number(formData.value.grossProfitAncestorQuotaPerc) +
    Number(formData.value.grossProfitBonusQuotaPerc) +
    Number(formData.value.grossProfitPlatformQuotaPerc);
});
const isSubmitDisabled = computed(() => {
  return totalPercentage.value > 100;
});

const withdrawPercentage = computed(() => {
  return Number(formData.value.withdrawCommission) +
    Number(formData.value.withdrawConsumption) 
});
const withdrawIsSubmitDisabled = computed(() => {
  return withdrawPercentage.value !== 100;
});
const formRules = reactive({
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true

  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderPercentageApi.getOrderPercentage(id)
    } finally {
      formLoading.value = false
    }
    percKeys.forEach(key => {
      if (formData.value.hasOwnProperty(key)) {
        formData.value[key] = (formData.value[key] * 100);
      }
    });
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const percKeys = [
  "grossProfitPerc",
  "grossProfitUserQuotaPerc",
  "grossProfitAncestorQuotaPerc",
  "grossProfitBonusQuotaPerc",
  "grossProfitPlatformQuotaPerc",
  "divideIntoPerc",
  "consumptionMagnification",
  "withdrawCommission",
  "withdrawConsumption",
];
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {

 
  // 如果用户自得+直推奖+合赢奖+平台服务费> 100那就不给保存
  if (isSubmitDisabled.value) {
    message.error('用户自得+直推奖+合赢奖+平台服务费,总和不能超过100%');
    return;
  }
  // 如果提现佣金+提现消费金额 != 100那就不给保存
  if (withdrawIsSubmitDisabled.value) {
    message.error('提现佣金+提现消费金额,总和必须为100%');
    return;
  }
  
   // 转换百分比为小数并转为字符串
   percKeys.forEach(key => {
    if (formData.value.hasOwnProperty(key)) {
      formData.value[key] = (formData.value[key] / 100).toFixed(4);  // 转为小数并保留四位小数
    }
  });
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true

  try {
    const data = formData.value
    if (formType.value === 'create') {
      await OrderPercentageApi.createOrderPercentage(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderPercentageApi.updateOrderPercentage(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    grossProfitPerc: undefined,
    grossProfitUserQuotaPerc: undefined,
    grossProfitAncestorQuotaPerc: undefined,
    grossProfitBonusQuotaPerc: undefined,
    grossProfitPlatformQuotaPerc: undefined,
    divideIntoPerc: undefined
  }
  formRef.value?.resetFields()
}
</script>