<template>
  <div class="vars-select">
    <el-popover
      placement="bottom"
      trigger="click"
      :width="400"
      :popper-style="{
        padding: 0
      }"
    >
      <template #reference>
        <div class="vars-display __hover">
          <varsValue :vars="state.vars"/>
        </div>
      </template>
      <div class="vars-select-block">
        <div class="filter">
          <el-input v-model="state.text" :prefix-icon="Search" placeholder="搜索变量" clearable/>
        </div>
        <div class="list">
          <template v-for="item in optionsCpt">
            <div class="list-group">
              <div class="px-2 text-sm mb-1 text-gray-400">{{item.label}}</div>
              <template v-for="son in item.options">
                <div class="__hover-bg px-2 py-1" @click="state.vars = son">
                  <varsItem :item="son"/>
                </div>
              </template>
            </div>
          </template>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import {computed, getCurrentInstance, reactive, ref, watch} from "vue";
import {useWorkflowStore} from "@/stores";
import { Search } from '@element-plus/icons-vue'
import varsItem from './vars-item.vue'
import varsValue from './vars-value.vue'

const WorkflowStore = useWorkflowStore()
const emits = defineEmits([])
const props = defineProps({
  node: {}
})
const {proxy}: any = getCurrentInstance()
const state: any = reactive({
  vars: null,
  options: [],
  text: ''
})
watch(() => props.node, (n) => {
  if (n) {
    state.options = WorkflowStore.getInVars(n)
  }
}, {immediate: true})
const optionsCpt = computed(() => {
  if (!state.text) {
    return state.options
  }
  return state.options.map(v => {
    const obj = {...v}
    obj.options = obj.options.filter(s => s.label.includes(state.text) || s.key.includes(state.text))
    return obj
  }).filter(v => v.options.length > 0)
})
</script>

<style lang="scss" scoped>
@import "@/views/workflow/instance/component/style";

.vars-display {
  border: $borderStyle;
  width: 100%;
  padding: 0 10px;
  border-radius: 4px;
  font-size: 12px;
  height: 32px;
  display: flex;
  align-items: center;
}
.vars-select-block {
  .filter {
    padding: 10px;
    border-bottom: $borderStyle;
  }
  .list {
    padding: 4px;
    display: flex;
    flex-direction: column;
    gap: 6px;
    .list-group {
      display: flex;
      flex-direction: column;
    }
  }
}
</style>