<template>
  <div class="node-box" v-if="node?.nodeInfo">
    <NodeHead :nodeName="node.text" />
    <a-tabs v-model:activeKey="nodeKey">
      <a-tab-pane key="1" :tab="t('基本信息')">
        <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-form-item :label="t('节点名称')" required>
            <a-input v-model:value="node.text" :disabled="!node.isUserDefined" />
          </a-form-item>
          <a-form-item :label="t('日志记录')" v-if="node.isUserDefined">
            <a-radio-group v-model:value="node.isLogRecord">
              <a-radio :value="true">是</a-radio>
              <a-radio :value="false">否</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="2" :tab="t('过程处理')" v-if="node.isUserDefined">
        <div class="process-top">
          <NodeHead nodeName="过程处理事件列表" />
          <a-button type="primary" @click="addProcess" :disabled="fromMobile">
            {{ t('添加') }}
          </a-button>
        </div>
        <a-table
          :columns="columns"
          :data-source="node.nodeInfo.processEvent"
          :key="tableKey"
          :pagination="false"
        >
          <template #headerCell="{ column }">
            <template v-if="column.key === 'sort'">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-fangxiang1" />
              </svg>
            </template>
          </template>
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'sort'">
              <svg class="icon draggable-icon" aria-hidden="true" style="cursor: move">
                <use xlink:href="#icon-paixu" />
              </svg>
            </template>
            <template v-if="column.key === 'operateType'">
              <a-select v-model:value="record[column.dataIndex]" :disabled="fromMobile">
                <a-select-option value="api">{{ t('执行API') }}</a-select-option>
                <a-select-option value="liteflow">{{ t('规则引擎') }}</a-select-option>
                <a-select-option value="ruleProcess">{{ t('规则流程') }}</a-select-option>
                <a-select-option value="js">JS脚本</a-select-option>
                <a-select-option value="pushMessage">{{ t('推送消息') }}</a-select-option>
              </a-select>
            </template>
            <template v-if="column.key === 'operateConfig'">
              <a-input
                v-if="record.operateType === 'api'"
                v-model:value="record[column.dataIndex].path"
                :disabled="fromMobile"
                @click="showConfig(index)"
              >
                <template #suffix>
                  <Icon icon="ant-design:ellipsis-outlined" />
                </template>
              </a-input>
              <a-input
                v-model:value="record.showValue"
                v-else-if="record.operateType === 'js'"
                @click="showJSConfig(index)"
              >
                <template #suffix>
                  <Icon icon="ant-design:ellipsis-outlined" />
                </template>
              </a-input>
              <a-select
                v-else-if="record.operateType === 'liteflow'"
                v-model:value="record[column.dataIndex]"
                :options="liteFlowOptions"
                :disabled="fromMobile"
                :field-names="{ label: 'chainName', value: 'id' }"
                @change="
                  (val, option) => {
                    handleLiteChange(val, option, record);
                  }
                "
              />
              <SelectRuleProcess
                v-else-if="record.operateType === 'ruleProcess'"
                :ruleConfig="record.ruleConfig"
                @change="
                  (val) => {
                    record.ruleConfig = val;
                  }
                "
              />
              <SelectPushMessage
                v-model="record.operateConfig"
                v-else-if="record.operateType === 'pushMessage'"
              />
            </template>
            <template v-if="column.key === 'action'">
              <span
                style="color: #ff8080; cursor: pointer"
                @click="deleteEvent(index)"
                v-if="!fromMobile"
              >
                删除
              </span>
            </template>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <ApiConfig
      v-if="apiConfigDialog"
      :title="t('API配置')"
      v-model:apiConfigDialog="apiConfigDialog"
      v-model:apiConfig="node.nodeInfo.processEvent[configIndex].operateConfig"
    />
    <ScriptConfig
      @register="registerModal"
      @success="submitConfig"
      :disabled="fromMobile ? true : false"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, nextTick, inject, Ref } from 'vue';
  import { Icon } from '/@/components/Icon';
  import { ApiConfig } from '/@/components/ApiConfig';
  import { getLiteflowList } from '/@/api/liteflow';
  import { FormEventColumnConfig, selectedNodeConfig } from '/@/model/generator/formEventConfig';
  import Sortable from 'sortablejs';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import ScriptConfig from '/@/components/Designer/src/components/componentProperty/settings/ScriptConfig.vue';
  import SelectPushMessage from '/@/components/Designer/src/components/componentProperty/settings/SelectPushMessage.vue';
  import SelectRuleProcess from '/@/components/Designer/src/components/componentProperty/settings/SelectRuleProcess.vue';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { isNullAndUnDef } from '/@/utils/is';
  import { cloneDeep } from 'lodash-es';

  const { t } = useI18n();
  const nodeKey = ref<string>('1');
  const tableKey = ref(0);
  const props = defineProps({
    columnList: {
      type: Object as PropType<FormEventColumnConfig>,
      default: () => {},
    },
    selectedNode: {
      type: Object as PropType<selectedNodeConfig>,
    },
  });
  const node = ref<any>();
  const configIndex = ref(0);
  const apiConfigDialog = ref(false);
  const liteFlowOptions = ref();
  const widgetForm = inject<Ref>('widgetForm');
  const fromMobile = inject<Boolean>('fromMobile', false);
  const [registerModal, { openModal }] = useModal();

  const columns = ref([
    {
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: t('操作类别'),
      dataIndex: 'operateType',
      key: 'operateType',
      width: '32%',
      align: 'center',
    },
    {
      title: t('操作配置'),
      dataIndex: 'operateConfig',
      key: 'operateConfig',
      width: '50%',
      align: 'center',
    },
    {
      title: t('操作'),
      dataIndex: 'action',
      key: 'action',
      width: '18%',
      align: 'center',
    },
  ]);

  watch(
    () => props.selectedNode,
    (val) => {
      if (val) {
        node.value = props.columnList[val.columnIndex!][val.index];
        if (!node.value.isUserDefined) nodeKey.value = '1';
      } else {
        node.value = {};
      }
    },
    {
      deep: true,
    },
  );

  watch(
    () => node.value,
    (val) => {
      if (val.nodeInfo?.processEvent && val.nodeInfo?.processEvent.length) {
        nextTick(() => {
          const tbody: any = document.querySelector('.node-box .ant-table-tbody');
          Sortable.create(tbody, {
            handle: '.draggable-icon',
            onEnd: ({ oldIndex, newIndex }) => {
              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || newIndex === oldIndex) {
                return;
              }
              const columns = cloneDeep(node.value.nodeInfo.processEvent);
              if (oldIndex > newIndex) {
                columns.splice(newIndex, 0, columns[oldIndex]);
                columns.splice(oldIndex + 1, 1);
              } else {
                columns.splice(newIndex + 1, 0, columns[oldIndex]);
                columns.splice(oldIndex, 1);
              }
              node.value.nodeInfo.processEvent = cloneDeep(columns);
              tableKey.value++;
            },
          });
        });
        delete val.nodeInfo.processEvent[configIndex.value]?.operateConfig?.script;
      }
      if (val.isUserDefined && !Array.isArray(liteFlowOptions.value)) getList();
    },
    { deep: true },
  );

  const showConfig = (index) => {
    configIndex.value = index;
    apiConfigDialog.value = true;
  };

  const showJSConfig = (index) => {
    const operateConfig = node.value?.nodeInfo.processEvent[index].operateConfig;
    const content = typeof operateConfig !== 'string' ? '' : operateConfig;
    openModal(true, {
      content,
      formList: widgetForm?.value,
      index,
    });
  };
  const submitConfig = (_, script, index) => {
    node.value.nodeInfo.processEvent[index].operateConfig = script;
    node.value.nodeInfo.processEvent[index].showValue = script ? '已配置' : '';
  };

  const addProcess = () => {
    node.value.nodeInfo.processEvent.push({
      operateType: 'api',
      operateConfig: {},
    });
  };

  const deleteEvent = (index) => {
    if (fromMobile) return;
    node.value.nodeInfo.processEvent.splice(index, 1);
  };

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

  const handleLiteChange = (_, option, record) => {
    record.operateName = option.chainName;
  };
</script>

<style lang="less" scoped>
  .node-box {
    position: absolute;
    top: 0;
    right: 0;
    box-shadow: -7px -1px 7px #dadcde;
    padding: 20px 30px 20px 20px;
    height: 100%;
    width: 410px;

    :deep(.ant-form-item) {
      margin-bottom: 10px;
    }

    .process-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    :deep(.ant-select) {
      width: 100%;
    }
  }

  :deep(.ant-table-cell) {
    padding: 10px !important;
  }

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