<!-- 固定旅程模板配置 -->
<script setup lang="ts">
import type { TripTemplate } from '../types'
import type { ConnectionType } from '@/composables/useAllData'
import { ElMessage } from 'element-plus'
import TripFlow from '@/components/flow/Index.vue'
import TripFlowSidebar from '@/components/flow/Sidebar.vue'
import { getTripTemplate, getTripConnections, getTripTemplateDemo, updateTripTemplateDemo, updateTriggerStatus } from '../api'
import { useMapStore } from '@/stores/map'
import { getNameByValue, tripTemplateTypeList } from '@/utils/dictionary'
const BindConnection = defineAsyncComponent(() => import('../components/BindConnection.vue'))

const props = defineProps<{ id: string }>()

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

const detail = ref<TripTemplate>()
const triggerStatus = ref<number>(0)
const score = computed(() => {
  return detail.value ? parseFloat(detail.value?.score) : 0
})
function fetchInfo() {
  getTripTemplate({ id: props.id }).then(res => {
    detail.value = res.data.detail
    triggerStatus.value = parseInt(res.data.detail.is_trigger)
  })
}

onMounted(() => fetchInfo())

const connections = ref<ConnectionType[]>([])
const connectionIds = computed(() => {
  return connections.value.map(item => item.id)
})
function fetchConnections() {
  getTripConnections({ itinerary_id: props.id }).then(res => {
    connections.value = res.data.items
  })
}
onMounted(() => fetchConnections())

const elements = ref([])
// 获取模板配置数据
function fetchDemo() {
  getTripTemplateDemo({ itinerary_id: props.id }).then(res => {
    try {
      elements.value = res.data.graph ? JSON.parse(res.data.graph) : []
    } catch (error) {
      console.log(error)
    }
  })
}
onMounted(() => fetchDemo())

// 保存
function handleSubmit() {
  const params = { itinerary_id: props.id, graph: JSON.stringify(elements.value) }
  updateTripTemplateDemo(params).then(() => {
    ElMessage.success('保存成功')
  })
}

// 配置
let configVisible = $ref(false)
function handleConfig() {
  configVisible = true
}

function handleChantTriggerStatus(status: 0 | 1) {
  updateTriggerStatus({ itinerary_id: props.id, trigger_status: status }).then(() => {
    triggerStatus.value = status
    ElMessage.success('修改成功')
  })
}
</script>
<template>
  <AppCard title="固定旅程模版配置" v-if="detail">
    <el-card shadow="never" style="margin-bottom: 20px">
      <el-form label-suffix="：" class="info">
        <el-row justify="space-between">
          <el-col :span="8">
            <el-form-item label="旅程模版名称">{{ detail.name }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模板类型">{{ getNameByValue(detail.type, tripTemplateTypeList) }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分值">{{ detail.score }}</el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between">
          <el-col :span="8">
            <el-form-item label="更新人">{{ detail.updated_operator.real_name }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="更新时间">{{ detail.updated_time }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <span :style="`color:${detail.status === '1' ? 'var(--main-success-color)' : 'var(--main-color)'}`">
                {{ getNameByValue(detail.status, statusList) }}
              </span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <TripFlow v-model="elements" :templateType="detail?.type" :score="score">
      <template #left-panel>
        <TripFlowSidebar :connectionIds="connectionIds" />
      </template>
      <template #header>
        <el-row align="middle">
          <el-button type="primary" size="large" @click="handleConfig" v-if="false">配置连接</el-button>
          <el-alert center style="flex: 1">
            <p style="text-align: center">
              用户旅程的基本组成：触发条件+营销动作+条件分支<br />
              您可以从左侧组件区域选择的对应的触发条件、营销动作和条件分支，拖拽到右侧的画布里面，进行编排组合个性化的用户旅程。
            </p>
          </el-alert>
        </el-row>
      </template>
      <template #footer>
        <el-row justify="center">
          <el-button plain auto-insert-space @click="$router.push('/trip/template')">取消</el-button>
          <el-button type="primary" auto-insert-space @click="handleSubmit">保存</el-button>
          <el-button type="primary" auto-insert-space :disabled="triggerStatus === 1" @click="handleChantTriggerStatus(1)">触发旅程</el-button>
          <el-button type="primary" auto-insert-space :disabled="triggerStatus === 0" @click="handleChantTriggerStatus(0)">关闭旅程</el-button>
        </el-row>
      </template>
    </TripFlow>
  </AppCard>

  <!-- 配置连接 -->
  <BindConnection v-model="configVisible" :data="detail" v-if="configVisible && detail" @update="fetchConnections"></BindConnection>
</template>
