<template>
  <div class="process-top">
    <a-button type="primary" @click="addEvent" class="!rounded">
      {{ t(`添加${event}`) }}
    </a-button>
  </div>
  <div :class="prefixCls" style="height: calc(100% - 42px)">
    <a-table
      size="middle"
      :columns="columns"
      :data-source="formInfoVal[eventInfo[props.eventIndex]]"
      :pagination="false"
      :key="tableKey"
      :class="`table-box${eventIndex}`"
      :scroll="{ y: 'calc(100% - 51px)' }"
    >
      <template #headerCell="{ column }">
        <div v-if="column.key === 'sort'" class="header-cell__custom-title">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-fangxiang1" />
          </svg>
        </div>
        <div v-else class="header-cell__custom-title">{{ column.title }}</div>
      </template>
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'sort'">
          <svg
            :class="['icon', `draggable-icon${eventIndex}`]"
            aria-hidden="true"
            style="cursor: move; display: inline-block"
          >
            <use xlink:href="#icon-paixu" />
          </svg>
        </template>
        <template v-if="column.key === 'type'">
          <a-select v-model:value="record[column.dataIndex]">
            <a-select-option :value="NodeEventExType.API">{{ t('执行API') }}</a-select-option>
            <a-select-option :value="NodeEventExType.LITEFLOW">{{ t('规则引擎') }}</a-select-option>
            <a-select-option :value="NodeEventExType.RULE_PROCESS">{{
              t('规则流程')
            }}</a-select-option>
            <a-select-option :value="NodeEventExType.PUSH_MESSAGE">{{
              t('推送消息')
            }}</a-select-option>
          </a-select>
        </template>
        <template v-if="column.key === 'operateConfig'">
          <ScriptApiSelect
            v-if="record.type === NodeEventExType.API"
            style="width: 100%"
            v-model="record['apiConfig']"
            :need-hide-components="true"
          />
          <SelectRuleProcess
            v-else-if="record.type === NodeEventExType.RULE_PROCESS"
            :ruleConfig="record.ruleConfig"
            @change="
              (val) => {
                record.ruleConfig = val;
              }
            "
          />
          <SelectPushMessage
            v-else-if="record.type === NodeEventExType.PUSH_MESSAGE"
            style="width: 100%"
            v-model="record['messageConfig']"
            :need-hide-components="true"
          />
          <a-select
            style="width: 100%"
            v-else-if="record.type === NodeEventExType.LITEFLOW"
            v-model:value="record['liteflowId']"
            :options="liteFlowOptions"
            :field-names="{ label: 'chainName', value: 'id' }"
          />
        </template>
        <template v-if="column.key === 'action'">
          <div @click="deleteEvent(index)" class="text-[#FF5461]">{{ t('删除') }}</div>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, watch, nextTick } from 'vue';
  import { NodeEventExType } from '/@/enums/workflowEnum';
  import { getLiteflowList } from '/@/api/liteflow';
  import ScriptApiSelect from '/@bpmn/components/arguments/ScriptApiSelect.vue';
  import SelectPushMessage from '/@bpmn/components/arguments/SelectPushMessage.vue';
  import SelectRuleProcess from '/@bpmn/components/arguments/SelectRuleProcess.vue';
  import { NodeEventConfig } from '/@/model/workflow/workflowConfig';
  import { isNullAndUnDef } from '/@/utils/is';
  import { useI18n } from '/@/hooks/web/useI18n';
  import Sortable from 'sortablejs';
  import { cloneDeep } from 'lodash-es';
  import { useDesign } from '/@/hooks/web/useDesign';
  const { prefixCls } = useDesign('basic-table');
  const props = defineProps({
    eventIndex: {
      type: Number,
      default: 0,
    },
    event: {
      type: String,
      default: '',
    },
    formInfo: {
      type: Object,
      default: () => {},
    },
  });
  const emits = defineEmits(['update:formInfo']);

  const { t } = useI18n();
  const eventInfo = ref([
    'startEventConfigs',
    'endEventConfigs',
    'agreeEventConfigs',
    'rejectEventConfigs',
    'withdrawEventConfigs',
    'timeoutEventConfigs',
  ]);
  const columns = ref([
    {
      dataIndex: 'sort',
      key: 'sort',
      align: 'center',
      width: 50,
    },
    {
      title: t('操作类别'),
      dataIndex: 'type',
      key: 'type',
      width: '35%',
      align: 'center',
    },
    {
      title: t('操作配置'),
      dataIndex: 'operateConfig',
      key: 'operateConfig',
      align: 'center',
    },
    {
      title: t('操作'),
      dataIndex: 'action',
      key: 'action',
      width: 88,
      align: 'center',
    },
  ]);
  const formInfoVal = ref(props.formInfo);
  const tableKey = ref(0);

  const liteFlowOptions = ref();
  onMounted(async () => {
    liteFlowOptions.value = (await getLiteflowList()) || [];
  });

  watch(
    () => formInfoVal.value,
    (val) => {
      emits('update:formInfo', val);
    },
    {
      deep: true,
    },
  );

  watch(
    () => formInfoVal.value,
    () => {
      if (formInfoVal.value[eventInfo.value[props.eventIndex]]?.length > 0) {
        nextTick(() => {
          const tbody: any = document.querySelector(
            `.table-box${props.eventIndex} .ant-table-tbody`,
          );
          Sortable.create(tbody, {
            handle: `.draggable-icon${props.eventIndex}`,
            onEnd: ({ oldIndex, newIndex }) => {
              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || newIndex === oldIndex) {
                return;
              }
              const columns = cloneDeep(formInfoVal.value[eventInfo.value[props.eventIndex]]);

              if (oldIndex > newIndex) {
                columns.splice(newIndex - 1, 0, columns[oldIndex - 1]);
                columns.splice(oldIndex, 1);
              } else {
                columns.splice(newIndex, 0, columns[oldIndex - 1]);
                columns.splice(oldIndex - 1, 1);
              }
              formInfoVal.value[eventInfo.value[props.eventIndex]] = cloneDeep(columns);
              tableKey.value++;
            },
          });
        });
      }
    },
    { deep: true, immediate: true },
  );

  const addEvent = () => {
    formInfoVal.value[eventInfo.value[props.eventIndex]].push({
      type: NodeEventExType.API,
      apiConfig: {},
      messageConfig: {},
      ruleConfig: {},
    } as NodeEventConfig);
  };

  const deleteEvent = (index) => {
    formInfoVal.value[eventInfo.value[props.eventIndex]].splice(index, 1);
  };
</script>
<style lang="less" scoped>
  .process-top {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin: 0 10px 10px;
  }

  .icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentcolor;
    overflow: hidden;
  }
</style>
