<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-steps direction="vertical" :active="0" finish-status="success">
        <el-step title="基本信息">
          <template #description>
            <div class="desc-text">请填写基本信息</div>
            <el-form-item label="规则名称" prop="title">
              <el-input v-model="formData.title" clearable placeholder="请输入规则名称" style="width: 300px;"/>
            </el-form-item>
            <el-form-item label="选择事件地址" prop="url">
              <el-cascader 
                v-model="formData.url"
                placeholder="请输入要搜索的url地址"
                :options="eventUrlList"
                filterable
                clearable
                :props="{ label: 'operation', value: 'url' }"
              />
            </el-form-item>
            <el-form-item label="事件地址" prop="url">
              <el-input v-model="formData.url" clearable placeholder="请输入规则名称" style="width: 300px;"/>
            </el-form-item>
            <el-form-item label="触发类型" prop="triggerType">
              <el-radio-group v-model="formData.triggerType">
                <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_POINT_RULE_CONFIG_TRIGGER_TYPE)" :key="dict.value" :value="dict.value">
                  {{ dict.label }}
                  <Tooltip :message="dict.remark"/>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="事件类型" prop="type">
              <el-radio-group v-model="formData.type">
                <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_POINT_RULE_CONFIG_TYPE)" :key="dict.value" :value="dict.value">
                  {{ dict.label }}
                  <Tooltip :message="dict.remark" />
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="标记代码" prop="mark">
              <el-input v-model="formData.mark" clearable placeholder="请输入标记代码" style="width: 300px;"/>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="formData.sort" :min="0" :precision="0" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_POINT_RULE_CONFIG_STATUS)" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
        </el-step>
        <el-step title="触发条件">
          <template #description>
            <div class="desc-text">请设置触发条件</div>
            <ConditionPage ref="conditionRef" :itemData="formData.triggerRule" />
          </template>
        </el-step>
        <el-step title="积分设置">
          <template #description>
            <div class="desc-text">请填写积分设置</div>
            <el-form-item label="积分处理" prop="operation">
              <el-radio-group v-model="formData.operation">
                <el-radio :value="'+'">递增</el-radio>
                <el-radio :value="'-'">递减</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="积分数量" prop="point">
              <el-input-number v-model="formData.point" :min="1"/>
            </el-form-item>
          </template>
        </el-step>
      </el-steps>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup>
defineOptions({ name: 'SaveForm'})
import ConditionPage from './condition.vue'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { getEventTrackUrlList, savePointRuleConfig, getPointRuleConfigDetails, updatePointRuleConfig } from '@/api/menduner/system/integral'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false)
const formLoading = ref(false)
const dialogTitle = ref('')
const formType = ref('')
const formData = ref({
  title: '',
  url: '',
  mark: '',
  status: 0,
  triggerType: 0,
  type: 0,
  operation: '+',
  point: 10,
  sort: 0
})

const formRules = reactive({
  title: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
  // url: [{ required: true, message: '事件地址不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '事件状态不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '规则类型不能为空', trigger: 'blur' }],
  triggerType: [{ required: true, message: '触发类型不能为空', trigger: 'blur' }],
  operation: [{ required: true, message: '积分处理不能为空', trigger: 'blur' }],
  point: [{ required: true, message: '积分数量不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})
const eventUrlList = ref([])
const formRef = ref() // 表单 Ref
const conditionRef = ref()

// 获取事件地址列表
const getEventUrlList = async () => {
  const data = await getEventTrackUrlList()
  eventUrlList.value = data.map(e => {
    const children = e.children.map(k => {
      return { operation: k.name, url: k.name, children: k.children }
    })
    return { operation: e.name, url: e.name, children }
  })
}

/** 打开弹窗 */
const open = async (type, id) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获取事件地址列表
  getEventUrlList()

  if (id) {
    formLoading.value = true
    try {
      formData.value = await getPointRuleConfigDetails(id)
      formData.value.status = Number(formData.value.status)
      formData.value.triggerType = Number(formData.value.triggerType)
      formData.value.type = Number(formData.value.type)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success'])

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    title: '',
    url: '',
    mark: '',
    status: 0,
    triggerType: 0,
    type: 0,
    operation: '+',
    point: 10,
    sort: 0
  }
  formRef.value?.resetFields()
}

// 提交
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  const query = {
    constraintRule: null
  }
  for (let i in formData.value) {
    if (i === 'url') query[i] = Array.isArray(formData.value[i]) ? formData.value[i][formData.value[i].length - 1] : formData.value[i]
    else query[i] = formData.value[i]
  }
  const data = conditionRef.value.getQuery()
  if (!data) return
  if (Object.keys(data).length) query.triggerRule = data

  try {
    if (formType.value === 'create') {
      await savePointRuleConfig(query)
      message.success(t('common.createSuccess'))
    } else {
      await updatePointRuleConfig(query)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.desc-text {
  margin-bottom: 20px;
  color: #a8abb2;
}
</style>