<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" style="width: 1000px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="rules"
      class="mt-10px"
      label-width="80px"
      inline
    >
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="方案名称" prop="percentageName">
            <el-input v-model="formData.percentageName" placeholder="请输入方案名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="结算方式">
            <el-radio-group v-model="formData.percentageType">
              <el-radio :label="1">
                <Tooltip message="可配置多级，命中某档位后，按照档位分级结算" />阶梯结算
              </el-radio>
              <el-radio :label="2">
                <Tooltip message="可配置多级，命中某档位后所有金额全部按照该档位结算" />常规结算
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-card class="mb-18px" shadow="never" :body-style="{ padding: '10px' }">
        <div v-if="formData.percentageType == 1">
          <p class="text-red-500">阶梯结算说明：</p>
          <p>若设置 0档、1000档、2000档</p>
          <p>金额为1500，则未满1000的部分按照0档结算提成，1000-1500的部分按照1000档结算</p>
        </div>
        <div v-else-if="formData.percentageType == 2">
          <p class="text-red-500">阶梯结算说明：</p>
          <p>若设置 0档、1000档、2000档</p>
          <p>金额为1500，则全部按照1000档结算</p>
        </div>
      </el-card>

      <el-button type="primary" class="mb-10px" plain @click="handleAddRules">
        添加提成档位
      </el-button>
      <el-row :gutter="20" class="mb-10px">
        <el-col
          :span="24"
          :offset="0"
          class="flex"
          v-for="(item, index) in formData.rules"
          :key="index"
        >
          <el-select
            v-model="item.ruleParam1"
            style="width: 100px"
            :disabled="index > 0"
            @change="planChanged('ruleParam1', false)"
          >
            <el-option
              v-for="it in opts.percentage_param1"
              :key="it.value"
              :label="it.label"
              :value="it.value"
            />
          </el-select>
          <el-select
            class="ml-5px"
            v-model="item.ruleParam2"
            style="width: 100px"
            :disabled="index > 0"
            @change="planChanged('ruleParam2', false)"
          >
            <el-option
              v-for="it in opts.percentage_param2"
              :key="it.value"
              :label="it.label"
              :value="it.value"
            />
          </el-select>
          <span class="ml-5px">满</span>
          <el-input
            class="ml-5px"
            v-model="item.ruleParam3"
            placeholder="金额"
            type="number"
            :min="0"
            style="width: 100px"
          />
          <span class="ml-5px">元，</span>
          <el-select class="ml-5px" v-model="item.ruleParam4" style="width: 120px">
            <el-option
              v-for="it in opts.percentage_param4"
              :key="it.value"
              :label="it.label"
              :value="it.value"
            />
          </el-select>
          <div v-if="item.ruleParam4 == 2" class="inline-flex items-center">
            <el-input
              class="ml-5px"
              v-model="item.ruleParam7"
              placeholder="金额"
              type="number"
              :min="0"
              style="width: 100px"
            />
            <span class="ml-5px">元结算</span>
          </div>
          <div v-else class="inline-flex items-center">
            <span class="ml-5px">取</span>
            <el-select
              class="ml-5px"
              v-model="item.ruleParam5"
              style="width: 100px"
              :disabled="formData.percentageType == 1"
              @change="planChanged('ruleParam5')"
            >
              <el-option
                v-for="it in opts.percentage_param5"
                :key="it.value"
                :label="it.label"
                :value="it.value"
              />
            </el-select>
            <span class="ml-5px">结算</span>
            <el-input
              class="ml-5px"
              v-model="item.ruleParam6"
              placeholder="比例"
              type="number"
              :min="1"
              style="width: 100px"
            >
              <template #suffix> % </template>
            </el-input>
          </div>
          <Icon
            v-if="index > 0"
            icon="ep:remove-filled"
            class="text-red-500 ml-20px"
            @click="handleRemove(index)"
          />
        </el-col>
      </el-row>

      <el-divider direction="horizontal" />

      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="是否扣除其他支出" labelWidth="150px">
            <el-radio-group v-model="formData.isDeductExtraPay">
              <el-radio :label="true"> 是 </el-radio>
              <el-radio :label="false"> 否 </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="是否扣除售后" labelWidth="150px">
            <el-radio-group v-model="formData.isDeductAfterSale">
              <el-radio :label="true"> 是 </el-radio>
              <el-radio :label="false"> 否 </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="是否关联成交率" labelWidth="150px">
            <el-radio-group v-model="formData.isRelateSignRate">
              <el-radio :label="true"> 是 </el-radio>
              <el-radio :label="false"> 否 </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="提成计算时间" labelWidth="150px">
            <el-radio-group v-model="formData.calculateType">
              <el-radio :label="1">成交后</el-radio>
              <el-radio :label="2">回款后</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="关联规则" v-if="formData.isRelateSignRate">
            <div>
              <el-button @click="formData.rateRules.push({})"> 新增规则 </el-button>
              <div
                v-for="(item, index) in formData.rateRules"
                :key="index"
                class="mt-10px flex justify-center items-center"
              >
                <span>成交率达</span>
                <el-input
                  class="ml-10px"
                  v-model="item.signRate"
                  placeholder="成交率"
                  style="width: 100px"
                  type="number"
                  :min="0"
                >
                  <template #suffix>%</template>
                </el-input>
                <span>，可结算</span>
                <el-input
                  class="ml-10px"
                  v-model="item.percentageRate"
                  placeholder="提成率"
                  style="width: 100px"
                  type="number"
                  :min="0"
                >
                  <template #suffix>%</template>
                </el-input>
                <span>提成</span>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">保存</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script setup name="DialogCommissionPlan">
import * as PlanApi from '@/api/finance/plan'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('提成方案')
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const formData = ref({})
const rules = {
  percentageName: { required: true, message: '方案名称不可为空', trigger: 'blur' }
}
const opts = ref({
  percentage_param1: [],
  percentage_param2: [],
  percentage_param4: [],
  percentage_param5: []
})

const formType = ref('create')
/** 打开弹窗 */
const open = async (type, row) => {
  dialogVisible.value = true
  dialogTitle.value = type == 'create' ? `新增方案` : '修改方案'
  formType.value = type
  resetForm()

  if (!opts.value.length) {
    const arr = await PlanApi.getCommissionParams()
    arr.map((item) => {
      opts.value[item.dictType].push(item)
    })
  }

  if (row?.percentageId) {
    formLoading.value = true
    try {
      formData.value = await PlanApi.getPlanDetail(row.percentageId)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  opts.value = {
    percentage_param1: [],
    percentage_param2: [],
    percentage_param4: [],
    percentage_param5: []
  }
  formData.value = {
    percentageName: undefined,
    percentageType: 2,
    rules: [
      {
        ruleParam1: '2',
        ruleParam2: '1',
        ruleParam3: 0,
        ruleParam4: '1',
        ruleParam5: '1',
        ruleParam6: 10
      }
    ],
    isRelateSignRate: false,
    rateRules: [],
    isDeductExtraPay: true,
    isDeductAfterSale: true,
    calculateType: 1
  }
  formRef.value?.resetFields()
}

function handleAddRules() {
  formData.value.rules.push(formData.value.rules[0])
}

const emit = defineEmits(['success'])
const formRef = ref()
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value }
    if (formType.value === 'create') {
      await PlanApi.createPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlanApi.updatePlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

function handleRemove(index) {
  formData.value.rules.splice(index, 1)
}

function planChanged(paramName, editble = true) {
  const defaultRule = formData.value.rules[0]
  formData.value.rules.forEach((it, index) => {
    if (formData.value.percentageType == 2) {
      if (!editble) {
        it[paramName] = defaultRule[paramName]
      }
    } else {
      if (index > 0) {
        it[paramName] = defaultRule[paramName]
      }
      if (paramName == 'ruleParam2') {
        it['ruleParam5'] = defaultRule[paramName]
      }
    }
  })
}
</script>

<style lang="scss" scoped></style>
