<script setup lang="ts">
import type { Label } from '../types'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useMapStore } from '@/stores/map'
import { getNameByValue, updateStatusRuleList, labelList } from '@/utils/dictionary'
import { getLabelRule, updateLabelRule } from '../api'
import LevelRule from '@/components/rule/LevelRule.vue'
import EventPreferenceRule from '@/components/rule/EventPreferenceRule.vue'
import EventTargetRule from '@/components/rule/EventTargetRule.vue'
import RFMRule from '@/components/rule/RFMRule.vue'
import CustomRule from '@/components/rule/CustomRule.vue'
import SingleUserRule from '@/components/rule/SingleUserRule.vue'
import UserRule from '@/components/rule/UserRule.vue'

const props = defineProps<{
  data: Label
}>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const userStore = useUserStore()

const disabled = computed(() => userStore.status.tag_status)

const statusList = useMapStore().getMapValuesByKey('system_status')

const formRef = $ref<FormInstance>()

const form: any = reactive({
  id: '',
  rules: undefined,
})

function fetchInfo() {
  getLabelRule({ id: props.data.id }).then((res) => {
    const { detail } = res.data

    let rules = detail.rules
    if (detail.rules.length === 0) {
      if (detail.label == '2') {
        rules = {
          event_attr_rule: {
            current_logic_operate: 'and',
            happen_info: { is_happened: true, event_id: '-1', event_name: '所有事件', attr_list: [] },
            trigger_info: { operate: '', operate_name: '', value: '' },
          },
          tag_rule: { event_id: '', event_name: '', attr_id: '', attr_name: '', type: 1, value: undefined },
        }
      }
      if (detail.label == '3') {
        rules = {
          event_attr_rule: {
            current_logic_operate: 'and',
            happen_info: { is_happened: true, event_id: '-1', event_name: '所有事件', attr_list: [] },
            trigger_info: { operate: '', operate_name: '', value: '' },
          },
          tag_rule: { way: '' },
        }
      }
      if (detail.label === '4') {
        rules = { R: {}, F: {}, M: {} }
      }
      if (detail.label === '5') {
        rules = { attr_id: '', attr: '', attr_name: '', attr_type: '', operate: '', operate_name: '', value: '' }
      }
      if (detail.label === '6') {
        rules = { current_logic_operate: 'and', items: [] }
      }
      if (detail.label === '7') {
        rules = {
          user_attr_rule: { current_logic_operate: 'and', items: [] },
          event_attr_rule: { current_logic_operate: 'and', items: [] },
          user_action_rule: { current_logic_operate: 'and', items: [] },
        }
      }
    }
    Object.assign(form, { id: props.data.id, rules })
  })
}

watchEffect(() => fetchInfo())

// 提交
function handleSubmit() {
  formRef?.validate().then(handleUpdate)
}

// 保存
function handleUpdate() {
  // const attrRuleItems = form.user_attr_rule.items.map((item: any) => {
  //   item.value = Array.isArray(item.value) ? item.value.join(',') : item.value
  //   return item
  // })
  // const eventRuleItems = form.event_attr_rule.items.map((item: any) => {
  //   item.value = Array.isArray(item.value) ? item.value.join(',') : item.value
  //   return item
  // })
  let rules = form.rules
  if (props.data.label == '1' && rules?.length > 0) {
    rules = rules.map((item: any, index: number) => {
      return { ...item, level: index }
    })
  }
  const params = {
    id: form.id,
    rules: JSON.stringify(rules),
    // user_attr_rule: JSON.stringify([{ ...form.user_attr_rule, items: attrRuleItems }]),
    // event_attr_rule: JSON.stringify([{ ...form.event_attr_rule, items: eventRuleItems }])
  }
  updateLabelRule(params).then(() => {
    ElMessage({ message: '保存成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog
    title="标签规则管理"
    :close-on-click-modal="false"
    width="1100px"
    @closed="$emit('update:modelValue', false)">
    <el-form label-suffix="：" label-width="82px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="标签名称">{{ data.name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签类型">{{ getNameByValue(data.label, labelList) }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="更新频率">{{ getNameByValue(data.update_status, updateStatusRuleList) }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-tag :type="data.status === '1' ? 'success' : 'danger'">
              {{ getNameByValue(data.status, statusList) }}
            </el-tag>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form :model="form" inline ref="formRef" :disabled="disabled" @submit.prevent v-if="form.id">
      <!-- 分层 -->
      <LevelRule v-model="form.rules" v-if="data.label == '1'"></LevelRule>
      <!-- 事件偏好 -->
      <EventPreferenceRule v-model="form.rules" v-if="data.label == '2'"></EventPreferenceRule>
      <!-- 事件指标 -->
      <EventTargetRule v-model="form.rules" v-if="data.label == '3'"></EventTargetRule>
      <!-- RFM模型 -->
      <RFMRule v-model="form.rules" :tagId="form.id" v-if="data.label == '4'"></RFMRule>
      <!-- 自定义 -->
      <CustomRule v-model="form.rules" v-if="data.label == '7'"></CustomRule>
      <!-- 单属性 -->
      <SingleUserRule v-model="form.rules" v-if="data.label == '5'"></SingleUserRule>
      <!-- 多属性规则 -->
      <UserRule v-model="form.rules" v-if="data.label == '6'"></UserRule>
      <!-- 事件属性规则 -->
      <!-- <EventRule style="margin-top: 20px"></EventRule> -->
    </el-form>
    <template #footer>
      <el-row justify="center">
        <el-button plain auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
        <el-button type="primary" auto-insert-space @click="handleSubmit" :disabled="disabled">保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>
