<script setup lang="ts">
import type { Trip } from '../types'
import TripFlow from '@/components/flow/Index.vue'
import TripFlowSidebar from '@/components/flow/Sidebar.vue'
import { ElMessage } from 'element-plus'
import { getStudentTrip, getTripTemplateDemo, updateTrip } from '../api'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

const BindConnection = defineAsyncComponent(() => import('../components/BindConnection.vue'))
const ViewGenerateEventData = defineAsyncComponent(() => import('@/components/ViewGenerateEventData.vue'))
const GenerateData = defineAsyncComponent(() => import('../components/GenerateData.vue'))

const detail = ref<Trip>()
const elements = ref([])
const connectionIds = computed(() => {
  return detail.value?.connect_ids || []
})
// 是否是自由旅程
const isFree = computed(() => {
  return detail.value?.experiment_itinerary_type === '1'
})
// 获取旅程信息
async function fetchInfo() {
  const res = await getStudentTrip()
  detail.value = res.data
  try {
    elements.value = res.data.graph ? JSON.parse(res.data.graph) : []
  } catch (error) {
    console.log(error)
  }
}
onMounted(async () => {
  await fetchInfo()
  fetchDemo()
})

// 获取模板配置数据
async function fetchDemo() {
  if (!detail.value) return
  if (isFree.value || detail.value.graph) return
  const res = await getTripTemplateDemo({ itinerary_id: detail.value.itinerary_id })
  try {
    elements.value = res.data.graph ? JSON.parse(res.data.graph) : []
  } catch (error) {
    console.log(error)
  }
}

// 保存 status:1缓存 2提交
function handleSubmit() {
  if (!detail.value) return
  const params = { itinerary_id: detail.value.itinerary_id, graph: JSON.stringify(elements.value), status: 2 }
  updateTrip(params).then(() => {
    ElMessage.success('保存成功')
  })
}

// 配置
let configVisible = $ref(false)
function handleConfig() {
  configVisible = true
}
function handleConnectionUpdate(value: string[]) {
  if (!detail.value) return
  detail.value.connect_ids = value
}

const generateEventVisible = ref(false)

const canGenerate = computed(() => {
  return !(userStore.status.status || userStore.status.group_status || userStore.status.material_status || userStore.status.tag_status)
})
</script>

<template>
  <AppCard :title="detail?.experiment_itinerary_type_name" v-if="detail">
    <el-card shadow="never" style="margin-bottom: 20px" v-if="detail">
      <div style="display: flex; align-items: center">
        <el-descriptions class="info" style="flex: 1">
          <el-descriptions-item label="课程名称:">{{ detail.course_name }}</el-descriptions-item>
          <el-descriptions-item label="实验名称:">{{ detail.experiment_name }}</el-descriptions-item>
          <el-descriptions-item label="旅程类型:">{{ detail.experiment_itinerary_type_name }}</el-descriptions-item>
        </el-descriptions>
        <el-space v-if="canGenerate">
          <GenerateData :data="detail" @update="fetchInfo"></GenerateData>
          <el-button type="primary" @click="generateEventVisible = true">查看用户旅程数据</el-button>
        </el-space>
      </div>
    </el-card>
    <TripFlow
      v-model="elements"
      action="edit"
      role="student"
      :templateType="detail?.experiment_itinerary_type"
      :nodes-draggable="isFree"
      :nodes-connectable="isFree">
      <template #left-panel v-if="isFree">
        <TripFlowSidebar :connectionIds="connectionIds" />
      </template>
      <template #header>
        <el-row align="middle">
          <el-button type="primary" size="large" @click="handleConfig" style="margin-right: 20px" v-if="false">配置连接</el-button>
          <el-alert center style="flex: 1">
            <p style="text-align: center">
              <template v-if="isFree">
                用户旅程的基本组成：触发条件+营销动作+条件分支<br />
                您可以从左侧组件区域选择的对应的触发条件、营销动作和条件分支，拖拽到右侧的画布里面，进行编排组合个性化的用户旅程。
              </template>
              <template v-else>请给本用户旅程的每一个节点进行详细配置，确保每一个节点能够顺利执行。</template>
            </p>
          </el-alert>
        </el-row>
      </template>
      <template #footer>
        <el-row justify="center">
          <el-button type="primary" auto-insert-space @click="handleSubmit">保存</el-button>
        </el-row>
      </template>
    </TripFlow>
  </AppCard>

  <!-- 配置连接 -->
  <BindConnection v-model="configVisible" :data="detail" @update="handleConnectionUpdate" v-if="configVisible && detail"></BindConnection>
  <!-- 用户事件数据 -->
  <ViewGenerateEventData v-model="generateEventVisible" v-if="generateEventVisible"></ViewGenerateEventData>
</template>
