<script lang="ts" setup>
import api from '@/servers/finyx/api'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { cloneDeep, debounce, forEach, isEmpty, map, remove } from 'lodash-es'
import { computed, ref } from 'vue'
import DialogBox from '@/components/dialog-box/index.vue'

const props = withDefaults(defineProps<{}>(), {})

// 定义组件事件，允许触发 submitHandle 事件
const emit = defineEmits(['submitHandle'])

// 定义一个响应式变量 dialogVisible，用于控制对话框的显示和隐藏
const dialogVisible = ref<boolean>(false)

const loading = ref<boolean>(false)

const allData = ref<any>([])
const tagData = ref<any>([])
const selectTagIndex = ref<number>(0)
const labelData = ref<any>([])
const selectLabels = ref<any>([])


const selectIds = computed(() => {
  return selectLabels.value.map((v: any) => v.id)
})

const handleChangeWeidu = (i: number) => {
  selectTagIndex.value = i
  labelData.value = tagData.value[i].flabelList
}
const handleChangeLabel = (item: any) => {
  // 如果已存在则删除
  if (selectIds.value.includes(item.id)) {
    remove(selectLabels.value, (v: any) => v.id === item.id)
    return false
  }
  selectLabels.value.push(item)
}

const getAllTagData = async () => {
  try {
    loading.value = true
    const data = await api.weidu.query10({})
    tagData.value = map(data || [], (v: any) => {
      return {
        ...v,
        flabelList: map(v.flabelList || [], (j) => {
          return {
            ...j,
            // 把维度信息塞入到标签里面。为了后续选择标签时知道是哪个维度的标签
            wId: v.id,
            wName: v.name
          }
        })
      }
    })
    allData.value = cloneDeep(tagData.value)
    if (!isEmpty(data)) {
      handleChangeWeidu(0)
    }
  } catch (e) {
    ElMessage.error('获取数据失败！')
  } finally {
    loading.value = false
  }
}

// 关闭对话框的方法
const close = () => {
  dialogVisible.value = false
  selectLabels.value = []
}
// 关闭对话框的方法
const open = (query?: any) => {
  getAllTagData()
  dialogVisible.value = true
  if (!isEmpty(query)) {
    selectLabels.value = cloneDeep(query)
  }
}

// 提交表单的方法
const submitHandle = async () => {
  try {
    emit('submitHandle', selectIds.value, selectLabels.value)
    close()
  } catch (e) {
    console.log(e)
  }
}

const keyword = ref<string>('')
const searchData = debounce((val: string) => {
  // 根据keyword 匹配 allData 树级结构，如果数组对象里面的name包含了 keyword 则显示
  if (!keyword.value) {
    tagData.value = cloneDeep(allData.value)
  } else {
    tagData.value = [];
    labelData.value = [];
    forEach(allData.value, (v: any, i: number) => {
      const flabelList = []
      forEach(v.flabelList, (j: any, c: number) => {
        if (j.name.indexOf(keyword.value) > -1) {
          flabelList.push(j)
        }
      })
      if (!isEmpty(flabelList)) {
        tagData.value.push(v)
        labelData.value = cloneDeep(flabelList);
      }
    })
    if (!isEmpty(tagData.value)) {
      selectTagIndex.value = 0;
    }

  }
}, 400)

const handleDelete = (i: number) => {
  selectLabels.value.splice(i, 1)
}
// 暴露 open 和 closeDialog 方法给外部使用
defineExpose({ open, close })
</script>

<template>
  <dialog-box
    :dialogVisible="dialogVisible"
    title="标签"
    width="700"
    @close="dialogVisible = false"
  >
    <div class="tag-warp">
      <div class="tag-warp-left">
        <el-input v-model="keyword" :prefix-icon="Search" placeholder="请搜索需要添加的标签" @input="searchData" />
        <div
          style="display: flex; flex-direction: row; height: calc(100% - 44px); margin-top: 12px"
        >
          <div class="tag-warp-left-dimension" v-loading="loading">
            <el-empty description="暂无维度数据" v-if="tagData.length === 0"></el-empty>
            <div
              v-for="(item, i) in tagData"
              :class="{ active: selectTagIndex === i }"
              class="tag-warp-left-dimension-item"
              @click="handleChangeWeidu(i)"
            >
              {{ item.name }}
            </div>
          </div>
          <div class="tag-warp-left-tag">
            <el-empty description="暂无标签数据" v-if="labelData.length === 0"></el-empty>
            <div v-for="(item, i) in labelData" class="tag-warp-left-tag-item" :class="{ active: selectIds.includes(item.id)}" :key="i" @click="handleChangeLabel(item)">
              {{ item.name }}
            </div>
          </div>
        </div>
      </div>
      <div class="tag-warp-right">
        <div class="tag-warp-right-title">已选：{{ selectLabels.length }}个标签</div>
        <div class="tag-warp-right-list">
          <div v-for="(item, i) in selectLabels" :key="i" class="tag-warp-right-list-item pointer">
            <el-tooltip>
              <template #content>
                {{ item.wName }} + {{ item.name }}
              </template>
              <span class="ellipsis">{{ item.wName }} + {{ item.name }}</span>
            </el-tooltip>
            <el-icon  @click="handleDelete(i)">
              <CircleCloseFilled class="pointer" />
            </el-icon>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer res_el-dialog__footer">
        <el-button :loading="loading" @click.prevent="close"> 取消 </el-button>
        <el-button :loading="loading" type="primary" @click="submitHandle()"> 确定 </el-button>
      </span>
    </template>
  </dialog-box>
</template>

<style lang="scss" scoped>
.tag-warp {
  height: 500px;
  display: flex;
  box-sizing: border-box;
  margin-bottom: 15px;

  &-left {
    width: 70%;
    border: 1px solid #dfe0e3;
    border-radius: 6px;
    padding: 12px;

    &-dimension {
      flex: 1;
      height: 100%;
      border-right: 1px solid #dfe0e3;
      padding-right: 12px;

      &-item {
        padding-left: 12px;
        height: 32px;
        margin-bottom: 6px;
        display: flex;
        align-items: center;
        cursor: pointer;
        border-radius: 6px;

        &:hover {
          background: #e2e8f5;
          color: #3067ef;
        }
      }
      .active {
        background: #e2e8f5;
        color: #3067ef;
      }
    }

    &-tag {
      flex: 1;
      height: 100%;
      padding-left: 12px;

      &-item {
        padding-left: 12px;
        height: 32px;
        margin-bottom: 6px;
        display: flex;
        align-items: center;
        cursor: pointer;
        border-radius: 6px;

        &:hover {
          background: #e2e8f5;
          color: #3067ef;
        }
      }
      .active {
        background: #e2e8f5;
        color: #3067ef;
      }
    }
  }

  &-right {
    width: 30%;
    border: 1px solid #dfe0e3;
    border-radius: 6px;
    margin-left: 15px;
    padding: 12px;

    &-title {
      height: 19px;
      display: flex;
      align-items: center;
      margin-bottom: 12px;
    }

    &-list {
      height: calc(100% - 30px);
      overflow-y: auto;

      &-item {
        height: 32px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-radius: 6px 6px 6px 6px;
        border: 1px solid #dfe0e3;
        padding-left: 12px;
        padding-right: 12px;
        margin-bottom: 12px;
        font-weight: 400;
        font-size: 14px;
        color: #333333;
        line-height: 20px;
        span {
          cursor: pointer;
          display: inline-block;
          width: 90%;
        }
      }
    }
  }
}
</style>
