<template>
  <div class="event-item">
    <div class="event-item__left">
      <div class="event-type">
        类型
        <div class="event-type__content">
          <div
            v-for="item in eventTypeOptions"
            :key="item.value"
            @click="handleEventTypeChange(item.value)"
            :class="
              eventValue == item.value
                ? 'event-type__content__item active'
                : 'event-type__content__item'
            "
            >{{ item.label }}
          </div>
        </div>
      </div>
    </div>
    <n-divider vertical style="height: 500px" />
    <div class="event-item__right">
      <n-tabs
        v-model:value="movementTab"
        type="card"
        addable
        closable
        tab-style="min-width: 80px;"
        @close="handleClose"
        @add="handleAdd"
      >
        <n-tab-pane
          v-for="(panel, panelIndex) in eventData.movementList"
          :key="panel.movement"
          :name="'动作' + (Number(panelIndex) + 1) + '-' + getEventName(panel.movement)"
        >
          <div class="event-item__right__content">
            <div class="event-type">
              执行动作
              <div class="event-type__content">
                <div
                  v-for="item in movementTypeOptions"
                  :key="item.value"
                  @click="handleMovementTypeChange(item.value, panelIndex)"
                  :class="
                    panel.movement == item.value
                      ? 'event-type__content__item active'
                      : 'event-type__content__item'
                  "
                  >{{ item.label }}
                </div>
              </div>
            </div>
            <n-divider vertical style="height: 450px" />

            <div class="movement-type">
              <template v-if="panel.movement != 'newaddress'">
                <div class="movement-type__element" v-if="panel.movement == 'style'">
                  关联组件（可选择分组里的单组件）
                  <n-select
                    v-model:value="panel.elementId"
                    placeholder="请选择"
                    :options="elementSelectSingleOptions"
                    @update:value="handleUpdateValue(panel.elementId, panel.movement, panelIndex)"
                  />
                </div>

                <div class="movement-type__element" v-if="panel.movement == 'callBackRequest'">
                  <CallBackEndApi
                    :panel="panel"
                    :index="panelIndex"
                    @changeCallBackEnd="changeCallBackEnd"
                  />
                </div>

                <div class="movement-type__element" v-else>
                  关联组件（可多选）
                  <n-select
                    v-model:value="panel.elementId"
                    placeholder="请选择"
                    :options="elementSelectOptions"
                    multiple
                  />
                </div>
              </template>

              <div class="movement-type__element" v-if="panel.movement == 'map'">
                组件交互方法
                <n-select
                  v-model:value="panel.funName"
                  placeholder="请选择"
                  :options="funSelectOptions"
                  @change="handlerMapFunChange"
                />
              </div>

              <div
                class="movement-type__element"
                v-if="
                  (panel.movement == 'map' && currentMapFunction?.group == 'layer') ||
                  panel.movement == 'graphic'
                "
              >
                选择图层对象
                <n-select
                  v-model:value="panel.params"
                  placeholder="请选择"
                  value-field="id"
                  label-field="name"
                  :options="layerOptions"
                />
              </div>

              <template v-if="panel.movement == 'newaddress'">
                <div class="movement-type__element">
                  跳转方式
                  <n-select
                    v-model:value="panel.skipType"
                    placeholder="请选择"
                    :options="skipTypeOptions"
                  />
                </div>
                <div class="movement-type__element">
                  是否在新页面打开
                  <n-switch v-model:value="panel.openNewPage" />
                </div>
                <!-- 外部链接 -->
                <div class="movement-type__element" v-if="panel.skipType == 'outLink'">
                  外部链接
                  <n-input v-model:value="panel.url" type="text" placeholder="请输入网址" />
                </div>
                <!-- 发布地址 -->
                <div class="movement-type__element" v-if="panel.skipType == 'publishLink'">
                  发布地址
                  <n-select
                    v-model:value="panel.url"
                    placeholder="请选择"
                    :options="publishOptions"
                  />
                </div>
                <!-- 路由 -->
                <div class="movement-type__element" v-if="panel.skipType == 'routeLink'">
                  路由地址
                  <n-select
                    v-model:value="panel.url"
                    placeholder="请选择"
                    :options="routeOptions"
                  />
                </div>
                <!-- 消息类型 -->
              </template>
              <div class="movement-type__element" v-if="eventType == 'websocket'">
                消息类型
                <n-select
                  v-model:value="panel.messageType"
                  placeholder="请选择"
                  :options="messageOptions"
                />
              </div>
              <!-- 自定义配置项 -->
              <div class="movement-component" v-if="panel.movement == 'style'">
                <EventComponent
                  v-if="chartConfig[panelIndex]"
                  :config="chartConfig[panelIndex].conKey"
                  :optionData="JSON.stringify(targetDataOption[panelIndex])"
                  :index="panelIndex"
                  @changeoption="changeOption"
                />
                <!-- <component :is="conKey[panelIndex]" :optionData="targetDataOption[panelIndex]" /> -->
              </div>
            </div>
          </div>
        </n-tab-pane>
        <template #prefix> 动作 <n-icon :component="DesktopOutline" /></template>
      </n-tabs>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ref, defineEmits, onMounted, watch, defineAsyncComponent } from 'vue';
  import { eventTypeOptions, movementTypeOptions } from '../../../../hooks/eventData.hook';
  import { goDialog, acquiesceAsyncComponent, previewPath, loadAsyncComponent } from '@/utils';
  import { DesktopOutline } from '@vicons/ionicons5';
  import { useTargetData } from '../../../../hooks/useTargetData.hook';
  import { getMenuList } from '@/api/sys/menu';
  import { projectListApi } from '@/api/path/project.api';
  import { funSelectOptions, layerOptions } from '@/hooks/ceshiFun.hook';
  import { getLoad } from '@/api/sys/sysDataItemDetail';
  import CallBackEndApi from './CallBackRequest.vue';

  const EventComponent = loadAsyncComponent(() => import('./EventComponent.vue'));
  const { targetData, chartEditStore } = useTargetData();
  const targetDataOption = ref([]);
  const chartConfig = ref([]);
  const componentGroupList = ref([]);
  // 选择组件样式
  const handleUpdateValue = (value, movement, index) => {
    componentGroupList.value.map((item: any) => {
      if (item.id == value) {
        console.log('item', item);
        targetDataOption.value[index] = item.option;
        chartConfig.value[index] = item.chartConfig;
        chartConfig.value[index].config = acquiesceAsyncComponent(
          () =>
            import(
              '../../../../../../../../packages/components/' +
                item.chartConfig.package +
                '/' +
                item.chartConfig.category +
                '/' +
                item.chartConfig.key +
                '/config.vue'
            ),
        );
      }
    });
  };

  const routeOptions = ref([]);
  const skipTypeOptions = ref([
    {
      label: '外部链接',
      value: 'outLink',
    },
    {
      label: '发布地址',
      value: 'publishLink',
    },
    {
      label: '路由',
      value: 'routeLink',
    },
  ]);
  const publishOptions = ref([]);
  const messageOptions = ref([]);
  const props = defineProps({
    eventData: {
      type: Object,
      default: () => ({
        type: 'click',
        movementList: [
          {
            movement: 'reveal',
            elementId: '',
          },
        ],
      }),
    },
    eventType: String,
  });
  console.log(props.eventData);
  props.eventData.movementList.forEach((element, index) => {
    targetDataOption.value[index] = element.option;
    chartConfig.value[index] = element.chartConfig;
  });
  props.eventData.movementList.forEach((element, index) => {
    targetDataOption.value[index] = element.option;
  });
  const emits = defineEmits(['changeTab']);
  const eventValue = ref(props.eventData.type);
  const handleEventTypeChange = (value: string) => {
    eventValue.value = value;
    props.eventData.type = value;
    emits('changeTab', value);
  };
  const movementTab = ref();
  movementTab.value =
    '动作1-' +
    movementTypeOptions.find((item) => item.value === props.eventData.movementList[0].movement)
      ?.label;
  const handleAdd = () => {
    movementTab.value =
      '动作' + (props.eventData.movementList.length + 1) + '-' + getEventName('reveal');
    props.eventData.movementList.push({
      movement: 'reveal',
      elementId: '',
    });
  };
  const handleClose = (name: string) => {
    const index = name.match(/动作(\S*)-/)[1];
    if (props.eventData.movementList.length > 1) {
      goDialog({
        message: '是否删除此动作?',
        onPositiveCallback: () => {
          props.eventData.movementList.splice(index - 1, 1);
          targetDataOption.value.splice(index - 1, 1);
          chartConfig.value.splice(index - 1, 1);
          if (index > 1) {
            const movement = props.eventData.movementList[index - 2].movement;
            movementTab.value = '动作' + (index - 1) + '-' + getEventName(movement);
          } else {
            const movement = props.eventData.movementList[0].movement;
            movementTab.value = '动作1' + '-' + getEventName(movement);
          }
        },
      });
    } else {
      window['$message'].error('至少保留一个动作');
    }
  };
  const handleMovementTypeChange = (value: string, index: number) => {
    props.eventData.movementList[index].movement = value;
    movementTab.value = '动作' + (index + 1) + '-' + getEventName(value);
  };
  const getEventName = (type: string) => {
    return movementTypeOptions.find((item) => item.value === type)?.label;
  };
  // 组件
  const elementSelectOptions = ref(
    chartEditStore.getComponentList.map((item) => {
      return {
        label: item.isGroup ? '分组-' + item.chartConfig.title : '组件-' + item.chartConfig.title,
        value: item.id,
      };
    }),
  );
  // 修改组件样式，可以选择分组里的某个单组件
  const elementSelectSingleOptions: any = ref([]);
  const treeIterator = (tree) => {
    tree.forEach((node) => {
      var obj = {};
      obj.label = node.item.name;
      obj.value = node.item.url;
      if (node.children.length > 0) {
        node.children && treeIterator(node.children);
      } else {
        routeOptions.value.push(obj);
      }
    });
  };
  // 获取路由列表
  const getRouteList = async () => {
    const data = await getMenuList();
    treeIterator(data);
    await data;
  };
  // 获取已发布页面列表
  const getPublishedPageList = async () => {
    const data = await projectListApi({
      state: 1,
      page: 1,
      limit: 1000,
    });
    publishOptions.value = data.items.map((item) => {
      return {
        label: item.projectName,
        // value: previewPath(item.id),
        value: item.id,
      };
    });
  };
  // 获取消息分类
  const getMsgTypeList = async () => {
    const data = await getLoad({
      code: 'websocket',
    });
    data.forEach((item) => {
      messageOptions.value.push({
        label: item.itemName,
        value: item.itemValue,
      });
    });
  };
  onMounted(() => {
    routeOptions.value = [
      {
        label: '首页',
        value: '/dashboard/analysis',
      },
    ];
    getRouteList();
    getPublishedPageList();
    getMsgTypeList();
    chartEditStore.getComponentList.forEach((item) => {
      if (item.isGroup) {
        item.groupList?.forEach((groupItem) => {
          elementSelectSingleOptions.value.push({
            label: '分组-' + item.chartConfig.title + '>> 组件-' + groupItem.chartConfig.title,
            value: groupItem.id,
          });
          componentGroupList.value.push({
            ...groupItem,
          });
        });
      }
      elementSelectSingleOptions.value.push({
        label: item.isGroup ? '分组-' + item.chartConfig.title : '组件-' + item.chartConfig.title,
        value: item.id,
      });
      componentGroupList.value.push({
        ...item,
      });
    });
  });

  // 地图交互方法改变
  const currentMapFunction = ref(null);
  const handlerMapFunChange = (e) => {
    let selected = funSelectOptions.filter((item, index) => {
      return item.value == e;
    });
    if (selected?.length > 0) {
      currentMapFunction.value = selected[0];
    }
  };

  const changeOption = (index, data) => {
    props.eventData.movementList[index].option = data;
    props.eventData.movementList[index].chartConfig = chartConfig.value[index];
  };

  const changeCallBackEnd = (index, data) => {
    props.eventData.movementList[index].callBackRequest = data;
  };
  watch(
    () => targetDataOption.value,
    (newData) => {
      newData.forEach((item, index) => {
        props.eventData.movementList[index].option = item;
      });
    },
    { deep: true },
  );
  watch(
    () => chartConfig.value,
    (newData) => {
      newData.forEach((item, index) => {
        props.eventData.movementList[index].chartConfig = item;
      });
    },
    { deep: true },
  );
</script>
<style lang="scss" scoped>
  .event-item {
    display: flex;
    .event-item__left {
      width: 30%;
    }
    .event-item__right {
      width: 60%;
    }
  }
  .event-type {
    .event-type__content {
      // background-color: #f5f5f5;
      padding: 10px 20px;
      border-radius: 6px;
      .event-type__content__item {
        padding: 4px 10px;
        cursor: pointer;
        &.active {
          background: rgba(24, 160, 88, 0.1);
          color: #18a058;
          border-left: 2px solid #18a058;
        }
      }
    }
  }
  .event-item__right__content {
    display: flex;
    .event-type {
      width: 30%;
    }
    .movement-type {
      width: 60%;
    }
  }
  .movement-type__element {
    margin-top: 10px;
  }
  .movement-component {
    height: 400px;
    overflow: auto;
  }
</style>
