<script setup lang="ts">
import type { Group } from '../types'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getNameByValue, updateStatusRuleList, dateUnitList, weekList, groupTypeList } from '@/utils/dictionary'
import {
  createStaticGroup,
  updateStaticGroup,
  createDynamicGroup,
  updateDynamicGroup,
  getGroupInfo,
  createRFMGroup,
  updateRFMGroup,
} from '../api'
import UserRule from '@/components/rule/UserRule.vue'
import EventRule from '@/components/rule/EventRule.vue'
import LabelRule from '@/components/rule/LabelRule.vue'
import UserActionRule from '@/components/rule/UserActionRule.vue'
import RFMRule from '@/components/rule/RFMRule.vue'
import { pick, merge } from 'lodash-es'
import { useQuestion } from '@/composables/useQuestion'

interface Props {
  data: Partial<Group>
}
const props = defineProps<Props>()

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

const isUpdate = computed(() => !!props.data?.id)
const title = computed(() => {
  const typeName = getNameByValue(props.data.type as string, groupTypeList)
  return isUpdate.value ? `修改${typeName}` : `新建${typeName}`
})

const formRef = ref<FormInstance>()
const form: any = reactive({
  id: '',
  name: '',
  type: '',
  status: '1',
  update_status: '2',
  update_rule: { type: 1, info: 1 },
  user_attr_rule: { current_logic_operate: 'and', items: [] },
  event_attr_rule: { current_logic_operate: 'and', items: [] },
  tag_rule: { current_logic_operate: 'and', items: [] },
  user_action_rule: { current_logic_operate: 'and', items: [] },
  rules: { R: {}, F: {}, M: {} },
  teacher_id: '',
})

function genRuleData(data: any) {
  if (Array.isArray(data)) data = data[0]
  return merge({ current_logic_operate: 'and', items: [] }, data)
}
function fetchInfo() {
  if (!props.data.id) return
  getGroupInfo({ id: props.data.id }).then((res) => {
    const { detail } = res.data
    const user_attr_rule = genRuleData(detail.user_attr_rule)
    const event_attr_rule = genRuleData(detail.event_attr_rule)
    const user_action_rule = genRuleData(detail.user_action_rule)
    const tag_rule = genRuleData(detail.tag_rule)

    const attrRuleItems = user_attr_rule.items.map((item: any) => {
      item.value = ['in', 'not in'].includes(item.operate) ? item.value.split(',') : item.value
      return item
    })
    const eventRuleItems = event_attr_rule.items.map((item: any) => {
      item.value = ['in', 'not in'].includes(item.operate) ? item.value.split(',') : item.value
      return item
    })

    const tagRuleItems = tag_rule.items.map((item: any, index: number) => {
      const rfm = tag_rule.rfm_tag_map?.[index] || {}
      return { tag_id: item.id, ...rfm }
    })

    Object.assign(form, detail, {
      user_attr_rule: { ...user_attr_rule, items: attrRuleItems },
      event_attr_rule: { ...event_attr_rule, items: eventRuleItems },
      user_action_rule,
      tag_rule: { ...tag_rule, items: tagRuleItems },
      update_rule: { type: 1, info: 1 },
    })
  })
}

watchEffect(() => fetchInfo())

const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入群组名称' }],
  teacher_id: [{ required: true, message: '请选择老师标签' }],
})

const questionType = props.data.type === '1' ? '301' : '302'

const { hasQuestion, teacherGroupList } = useQuestion(questionType, props.data.type)

// 提交
function handleSubmit() {
  formRef.value?.validate().then(() => (isUpdate.value ? handleUpdate() : handleCreate()))
}
// 新建
async function handleCreate() {
  if (props.data.type === '1') {
    // 静态群组
    const params = pick(form, ['name', 'status'])
    await createStaticGroup(params)
  } else if (props.data.type === '2') {
    const tagRule = form.tag_rule.items.reduce(
      (result: any, item: any, index: number) => {
        result.items.push(item.tag_id)
        if (item.rfm_key) {
          result.rfm_tag_map[index] = item
        }
        return result
      },
      { items: [], rfm_tag_map: {} }
    )
    // 动态群组
    const params = pick(
      {
        ...form,
        update_rule: JSON.stringify(form.update_rule),
        user_attr_rule: JSON.stringify([form.user_attr_rule]),
        event_attr_rule: JSON.stringify([form.event_attr_rule]),
        tag_rule: JSON.stringify([{ ...form.tag_rule, ...tagRule }]),
        user_action_rule: JSON.stringify(form.user_action_rule),
      },
      [
        'name',
        'status',
        'update_status',
        'update_rule',
        'user_attr_rule',
        'event_attr_rule',
        'tag_rule',
        'user_action_rule',
        'teacher_id',
      ]
    )
    await createDynamicGroup(params)
  } else {
    // RFM群组
    const params = pick(
      {
        ...form,
        update_rule: JSON.stringify(form.update_rule),
        rules: JSON.stringify(form.rules),
      },
      ['name', 'status', 'update_status', 'update_rule', 'rules', 'teacher_id']
    )
    await createRFMGroup(params)
  }
  ElMessage({ message: '创建成功', type: 'success' })
  emit('update')
  emit('update:modelValue', false)
}
// 修改
async function handleUpdate() {
  if (props.data.type === '1') {
    // 静态群组
    const params = pick(form, ['id', 'name', 'status', 'teacher_id'])
    await updateStaticGroup(params)
  } else if (props.data.type === '2') {
    // 动态群组
    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
    })
    const tagRule = form.tag_rule.items.reduce(
      (result: any, item: any, index: number) => {
        result.items.push(item.tag_id)
        if (item.rfm_key) {
          result.rfm_tag_map[index] = item
        }
        return result
      },
      { items: [], rfm_tag_map: {} }
    )
    // 动态群组
    const params = pick(
      {
        ...form,
        update_rule: JSON.stringify(form.update_rule),
        user_attr_rule: JSON.stringify([{ ...form.user_attr_rule, items: attrRuleItems }]),
        event_attr_rule: JSON.stringify([{ ...form.event_attr_rule, items: eventRuleItems }]),
        tag_rule: JSON.stringify([{ ...form.tag_rule, ...tagRule }]),
        user_action_rule: JSON.stringify(form.user_action_rule),
      },
      [
        'id',
        'name',
        'status',
        'update_status',
        'update_rule',
        'user_attr_rule',
        'event_attr_rule',
        'tag_rule',
        'user_action_rule',
        'teacher_id',
      ]
    )
    await updateDynamicGroup(params)
  } else {
    // RFM群组
    const params = pick({ ...form, update_rule: JSON.stringify(form.update_rule), rules: JSON.stringify(form.rules) }, [
      'id',
      'name',
      'status',
      'update_status',
      'update_rule',
      'rules',
      'teacher_id',
    ])
    await updateRFMGroup(params)
  }
  ElMessage({ message: '修改成功', type: 'success' })
  emit('update')
  emit('update:modelValue', false)
}
</script>

<template>
  <el-dialog :title="title" :close-on-click-modal="false" width="980px" @closed="$emit('update:modelValue', false)">
    <el-form ref="formRef" :model="form" :rules="rules" label-suffix="：" label-width="110px">
      <el-form-item label="群组名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入" />
      </el-form-item>
      <template v-if="data.type !== '1'">
        <el-form-item label="更新频率" prop="update_status">
          <el-radio-group v-model="form.update_status">
            <el-radio
              v-for="item in updateStatusRuleList"
              :key="item.value"
              :value="item.value"
              :disabled="item.value === '1'">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
          <div class="update-rule-wrap" v-if="form.update_status === '1'">
            <span>每</span>
            <el-select v-model="form.update_rule.type" placeholder=" " style="width: 60px">
              <el-option
                v-for="item in dateUnitList"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
            <template v-if="form.update_rule.type === 1">
              <span>的凌晨更新</span>
            </template>
            <template v-if="form.update_rule.type === 2">
              <span>的</span>
              <el-select v-model="form.update_rule.info" placeholder=" " style="width: 80px">
                <el-option
                  v-for="item in weekList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
              <span>的凌晨更新</span>
            </template>
            <template v-if="form.update_rule.type === 3">
              <span>第</span>
              <el-select v-model="form.update_rule.info" placeholder=" " style="width: 60px">
                <el-option v-for="item in 6" :key="item" :label="item" :value="item"></el-option>
              </el-select>
              <span>天的凌晨更新</span>
            </template>
          </div>
        </el-form-item>
      </template>
      <el-form-item label="匹配老师标签" prop="teacher_id" v-if="hasQuestion">
        <el-select v-model="form.teacher_id" style="width: 100%">
          <el-option v-for="item in teacherGroupList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" active-text="生效" active-value="1" inactive-text="失效" inactive-value="0" />
      </el-form-item>
      <template v-if="data.type === '2'">
        <!-- 用户属性规则 -->
        <UserRule v-model="form.user_attr_rule"></UserRule>
        <!-- 事件属性规则 -->
        <EventRule v-model="form.event_attr_rule" style="margin-top: 20px"></EventRule>
        <!-- 标签 -->
        <LabelRule v-model="form.tag_rule" style="margin-top: 20px"></LabelRule>
        <UserActionRule v-model="form.user_action_rule" style="margin-top: 20px"></UserActionRule>
      </template>
      <template v-if="data.type === '3'">
        <RFMRule v-model="form.rules"></RFMRule>
      </template>
    </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">保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.update-rule-wrap {
  width: 100%;
  .el-select {
    margin: 0 10px;
  }
}
</style>
