<script setup lang="ts">
import type { Trip } from '../types'
import { ElMessage } from 'element-plus'
import { bindTripConnections } from '../api'
import type { ConnectionType } from '@/composables/useAllData'
import { useConnection } from '@/composables/useAllData'
import ConnectionIcon from '@/components/ConnectionIcon.vue'

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

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

const { connectionList } = useConnection()

const multipleSelection = ref<string[]>([])

function toggleSelection(data: ConnectionType) {
  multipleSelection.value.includes(data.id)
    ? multipleSelection.value.filter(id => id !== data.id)
    : multipleSelection.value.push(data.id)
}

function isActive(data: ConnectionType) {
  return multipleSelection.value.includes(data.id)
}

// 保存
function handleSave() {
  bindTripConnections({ itinerary_id: props.data.id, connections_id: multipleSelection.value.join(',') }).then(() => {
    ElMessage({ message: '保存成功', type: 'success' })
    emit('update', multipleSelection.value)
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog title="配置连接" width="800px" append-to-body @closed="$emit('update:modelValue', false)">
    <div class="connection-list">
      <div
        class="connection-item"
        v-for="item in connectionList"
        :key="item.id"
        :class="{ 'is-active': isActive(item) }"
        @click="toggleSelection(item)">
        <el-checkbox @change="toggleSelection(item)" :model-value="isActive(item)" />
        <div class="connection-item__icon"><ConnectionIcon :name="item.type + ''" /></div>
        <p>{{ item.name }}</p>
      </div>
    </div>
    <template #footer>
      <el-row justify="center">
        <el-button plain auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
        <el-button type="primary" plain auto-insert-space @click="handleSave">保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.connection-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}
.connection-item {
  position: relative;
  height: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border: 1px dashed #bbb;
  cursor: pointer;
  &.is-active {
    background-color: rgb(204 247 131 / 38%);
  }
  .el-checkbox {
    position: absolute;
    left: 10px;
    top: 0;
  }
}
</style>
