<script setup lang="ts">
import type { DetailsProp, ScheduleMember, StudentFollow } from '../types'
import { Plus } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import ListItem from '../components/ListItem.vue'
import { getConnectionList, getConnectionDetails, getScheduleMember, getStudentFollow } from '../api'
import { useMapStore } from '@/stores/map'
import { useUserStore } from '@/stores/user'

const store = useMapStore()

const userStore = useUserStore()

const route = useRoute()

const FormDialog = defineAsyncComponent(() => import('../components/FormDialog.vue'))
const UserDataDialog = defineAsyncComponent(() => import('../components/UserDataDialog.vue'))
const EventDataDialog = defineAsyncComponent(() => import('../components/EventDataDialog.vue'))
const DataProgressDialog = defineAsyncComponent(() => import('../components/DataProgressDialog.vue'))
const StudentFollowDialog = defineAsyncComponent(() => import('../components/StudentFollowDialog.vue'))

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listOptions = computed(() => {
  return {
    remote: {
      httpRequest: getConnectionList,
      params: { created_operator: '', type: '' },
    },
    limit: 20,
    filters: [
      { type: 'input', prop: 'created_operator', placeholder: '请输入创建人姓名' },
      {
        type: 'select',
        prop: 'type',
        placeholder: '请选择类型',
        options: store.getMapValuesByKey('experiment_connection_type'),
      },
    ],
  }
})

// 刷新
function handleRefresh() {
  appList?.refetch()
}

// 新建链接
let formVisible = $ref(false)
const createConnect = function () {
  formData = undefined
  formVisible = true
}

// 编辑链接
let formData = $ref<DetailsProp | undefined>()
const editConnect = function (id: string) {
  getConnectionDetails({ id: id }).then((res) => {
    formData = res.data
    formVisible = true
  })
}

// 生成用户数据相关
let userDataVisible = $ref(false)
let userData = $ref<ScheduleMember>()

const handleGenerateUserData = function (experimentId: string, id: string, name: string) {
  getScheduleMember({ experiment_id: experimentId, connect_id: id }).then((res: { data: ScheduleMember }) => {
    userData = res.data
    if (res.data?.other_fields) {
      userData.other_fields = res.data.other_fields.map((item: any) => {
        if (item?.rule) {
          item.rule.type = parseInt(item.rule.type)
        }
        return item
      })
    }

    userData.type_name = name
    userData.experiment_id = experimentId
    userData.connect_id = id
  })
  userDataVisible = true
}

// 生成事件数据
let eventDataVisible = $ref(false)
let eventData = $ref<any>({})

const handleGenerateEventData = function (experimentId: string, id: string, events: any, last_event: string) {
  eventData = {
    experiment_id: experimentId,
    connect_id: id,
    events: events,
    last_event: last_event,
  }
  eventDataVisible = true
}

// 数据生成进度
let dataProgressVisible = $ref(false)
const viewDataProgress = function () {
  dataProgressVisible = true
}

// 用户触达
let studentFollowVisible = $ref(false)
let studentFollowData = $ref<StudentFollow>()
const handleStudentFollow = function (experimentId: string, id: string, type: string) {
  if (type === '15') {
    window.open(`https://mall-h5-web.ezijing.com?id=${id}&experiment_id=${route.query.experiment_id}`)
  } else {
    studentFollowVisible = true
    getStudentFollow({ experiment_id: experimentId, experiment_connection_id: id }).then((res: any) => {
      if (res.code === 0) {
        const data = res.data
        data.connect_id = id
        data.type = type
        studentFollowData = data
      }
    })
  }
}
</script>

<template>
  <AppCard>
    <AppList v-bind="listOptions" ref="appList">
      <template #body="{ data }">
        <div class="connect-list">
          <ListItem
            @edit="editConnect"
            :data="item"
            v-for="item in data"
            :key="item.id"
            @update="handleRefresh"
            @generateUserData="handleGenerateUserData"
            @generateEventData="handleGenerateEventData"
            @viewDataProgress="viewDataProgress"
            @handleStudentFollow="handleStudentFollow"></ListItem>
          <div class="connect-item" @click="createConnect" v-if="userStore.role?.id !== 1">
            <div class="connect-add-button">
              <el-icon><Plus /></el-icon>
              <span>新建连接</span>
            </div>
          </div>
        </div>
      </template>
    </AppList>
  </AppCard>
  <!-- 新建链接 -->
  <FormDialog :data="formData" v-model="formVisible" v-if="formVisible" @update="handleRefresh" />
  <!-- 生成用户数据 -->
  <UserDataDialog :data="userData" v-model="userDataVisible" v-if="userDataVisible"></UserDataDialog>
  <!-- 生成事件数据 -->
  <EventDataDialog :data="eventData" v-model="eventDataVisible" v-if="eventDataVisible"></EventDataDialog>
  <!-- 数据进度 -->
  <DataProgressDialog v-model="dataProgressVisible" v-if="dataProgressVisible"></DataProgressDialog>
  <!-- 用户触达 -->
  <StudentFollowDialog
    :data="studentFollowData"
    v-model="studentFollowVisible"
    v-if="studentFollowVisible"></StudentFollowDialog>
</template>

<style lang="scss">
.connect-list {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
  padding: 20px;
  // background-color: #efefef;
  border-radius: 5px;
}
.connect-add-button {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  .el-icon {
    font-size: 20px;
    margin-right: 10px;
  }
}
.connect-item {
  min-height: 166px;
}
</style>
