<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import type { ExperimentItem } from '../types'
import { ElMessage } from 'element-plus'
import { getTripConfig, updateTripConfig } from '../api'
import { useConnection, useUserAttr, useMetaEvent, useTag, useGroup, useMaterial } from '../composables/useAllData'
import { useDocumentVisibility } from '@vueuse/core'

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

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

const { connectionList } = useConnection(props.data.id)
const { userAttrList } = useUserAttr(props.data.id)
const { metaEventList } = useMetaEvent(props.data.id)
const { tagList } = useTag(props.data.id)
const { groupList } = useGroup(props.data.id)
const { materialList } = useMaterial(props.data.id)

const dmlURL = computed(() => {
  return `${import.meta.env.VITE_DML_URL}/trip/template?experiment_id=${props.data.id}`
})

const formRef = $ref<FormInstance>()
const form = reactive({
  experiment_id: props.data.id,
  itinerary_id: '',
  connect_ids: [],
  user_attr_config: { is_all: true, items: [] },
  event_config: { is_all: true, items: [] },
  is_use_common: 0,
  ids: [],
  tag_ids: [],
  group_ids: [],
  material_ids: []
})

// 模板列表
let templateList = $ref<{ id: string; name: string }[]>([])

function fetchInfo() {
  getTripConfig({ experiment_id: props.data.id }).then(res => {
    const data = res.data
    if (!data.itinerary?.id) return
    templateList = [data.itinerary]
    const connect_ids = data.connections.map((item: any) => item.id)
    if (!data.is_config_created) {
      Object.assign(form, { itinerary_id: data.itinerary.id, connect_ids })
      return
    }
    const user_attr_config = {
      is_all: data.user_attr_config.is_all,
      items: data.user_attr_config.items.map((item: any) => item.id)
    }
    const event_config = {
      is_all: data.event_config.is_all,
      items: data.event_config.items.map((item: any) => item.id)
    }
    const tag_ids = data.tags.map((item: any) => item.id)
    const group_ids = data.groups.map((item: any) => item.id)
    const material_ids = data.marketing_materials.map((item: any) => item.id)
    Object.assign(form, {
      itinerary_id: data.itinerary.id,
      connect_ids,
      user_attr_config,
      event_config,
      is_use_common: data.is_use_common,
      tag_ids,
      group_ids,
      material_ids
    })
  })
}
watchEffect(() => fetchInfo())

const visibility = useDocumentVisibility()
watch(visibility, (current, previous) => {
  if (current === 'visible' && previous === 'hidden') fetchInfo()
})

const step = ref(0)
// 上一步
function handlePrev() {
  step.value--
}
// 下一步
function handleNext() {
  step.value++
}

// 提交
function handleSubmit() {
  formRef?.validate().then(() => {
    const params = {
      ...form,
      connect_ids: JSON.stringify(form.connect_ids),
      user_attr_config: JSON.stringify(form.user_attr_config),
      event_config: JSON.stringify(form.event_config),
      tag_ids: JSON.stringify(form.tag_ids),
      group_ids: JSON.stringify(form.group_ids),
      material_ids: JSON.stringify(form.material_ids)
    }
    updateTripConfig(params).then(() => {
      ElMessage({ message: '保存成功', type: 'success' })
      emit('update')
      emit('update:modelValue', false)
    })
  })
}
</script>

<template>
  <el-dialog
    title="配置数字营销实验"
    :close-on-click-modal="false"
    width="600px"
    @update:modelValue="$emit('update:modelValue')">
    <el-form ref="formRef" :model="form" label-suffix="：">
      <el-row justify="space-between">
        <el-form-item label="实验名称">{{ data.name }}</el-form-item>
        <el-form-item label="实验类型">{{ data.type_name }} </el-form-item>
        <el-form-item label="实验总成绩">{{ data.score }}</el-form-item>
      </el-row>
      <el-tabs v-model="step">
        <el-tab-pane label="模板与连接" :name="0">
          <el-form-item label="旅程模板" label-width="82" prop="itinerary_id">
            <template v-if="templateList.length">
              <el-select v-model="form.itinerary_id" style="width: 100%">
                <el-option v-for="item in templateList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </template>
            <template v-else>
              <a :href="dmlURL" target="_blank">
                <el-button type="primary">新建旅程模板</el-button>
              </a>
            </template>
          </el-form-item>
          <el-form-item label="连接" label-width="82" prop="connect_ids">
            <el-select v-model="form.connect_ids" multiple style="width: 100%">
              <el-option
                v-for="item in connectionList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
                disabled></el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="元数据" :name="1">
          <el-form-item label="用户属性" label-width="82">
            <el-radio-group v-model="form.user_attr_config.is_all">
              <el-radio :label="true">全部</el-radio>
              <el-radio :label="false">部分</el-radio>
            </el-radio-group>
            <el-select
              v-model="form.user_attr_config.items"
              multiple
              style="margin-left: 40px"
              v-if="!form.user_attr_config.is_all">
              <el-option v-for="item in userAttrList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="事件" label-width="82">
            <el-radio-group v-model="form.event_config.is_all">
              <el-radio :label="true">全部</el-radio>
              <el-radio :label="false">部分</el-radio>
            </el-radio-group>
            <el-select
              v-model="form.event_config.items"
              multiple
              style="margin-left: 40px"
              v-if="!form.event_config.is_all">
              <el-option v-for="item in metaEventList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="旅程资源" :name="2">
          <el-form-item label="是否允许学生新建如下资源">
            <el-radio-group v-model="form.is_use_common">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="form.is_use_common === 0">
            <el-divider />
            <el-form-item label="用户/事件数据" label-width="118">
              <el-select v-model="form.ids" multiple style="width: 100%">
                <el-option value="教师维护的用户和事件数据"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签数据" label-width="118" prop="tag_ids">
              <el-select v-model="form.tag_ids" multiple style="width: 100%">
                <el-option v-for="item in tagList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户群组" label-width="118" prop="group_ids">
              <el-select v-model="form.group_ids" multiple style="width: 100%">
                <el-option v-for="item in groupList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="营销资料" label-width="118" prop="material_ids">
              <el-select v-model="form.material_ids" multiple style="width: 100%">
                <el-option v-for="item in materialList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-row justify="center">
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)" v-if="step === 0">关闭</el-button>
        <el-button round auto-insert-space @click="handlePrev" v-else>上一步</el-button>
        <el-button type="primary" round auto-insert-space @click="handleNext" v-if="step < 2">下一步</el-button>
        <el-button type="primary" round auto-insert-space @click="handleSubmit" v-else>保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>
