<template>
  <div class="basic-box">
    <div class="form-box">
      <div class="list-box">
        <div class="opr-box">
          <div class="button-box">
            <a-button type="primary" @click="add" class="!rounded">{{ t('添加运维') }}</a-button>
          </div>
        </div>
        <div :class="prefixCls" v-if="state.eventConfigs">
          <a-table
            :dataSource="state.eventConfigs"
            :columns="configColumns"
            :pagination="false"
            :key="tableKey"
            size="middle"
            :class="`table-box`"
            ><template #headerCell="{ column }">
              <div 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`]"
                  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.type"
                  :placeholder="t('请选择类型')"
                  style="width: 160px"
                  @change="
                    () => {
                      record.value = null;
                    }
                  "
                >
                  <a-select-option v-for="item in typeOptions" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </template>
              <template v-if="column.key === 'value'">
                <SelectConfigApi
                  v-if="record.type === NodeEventExType.API"
                  style="width: 100%"
                  v-model="record['apiConfig']"
                  :need-hide-components="true"
                  :paramConfigs="props.paramConfigs"
                />
              </template>
              <template v-if="column.key === 'operation'">
                <div class="text-[#FF5461]" @click="deleteItem(index)">删除</div>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { nextTick, onMounted, reactive, ref, watch } from 'vue';
  import Sortable from 'sortablejs';
  import { NodeEventExType } from '/@/enums/workflowEnum';
  import { randomNum } from '/@bpmn/util/random';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useDesign } from '/@/hooks/web/useDesign';
  import SelectConfigApi from './SelectConfigApi.vue';
  import { isNullAndUnDef } from '/@/utils/is';
  import { cloneDeep } from 'lodash-es';
  import { message, TreeProps } from 'ant-design-vue';
  const { prefixCls } = useDesign('basic-table');
  const { t } = useI18n();
  let props = withDefaults(
    defineProps<{
      paramConfigs?: TreeProps['treeData'];
      eventConfigs?: Array<any>;
    }>(),
    {
      paramConfigs: () => {
        return [];
      },
      eventConfigs: () => {
        return [];
      },
    },
  );
  const state: {
    eventConfigs: any;
  } = reactive({
    eventConfigs: [],
  });
  const configColumns = [
    {
      title: t('排序'),
      dataIndex: 'sort',
      key: 'sort',
      align: 'center',
      width: 80,
    },
    {
      title: t('运维类型'),
      dataIndex: 'type',
      key: 'type',
      width: 160,
      align: 'center',
    },
    {
      title: t('运维配置'),
      dataIndex: 'value',
      key: 'value',
      align: 'center',
    },
    {
      title: t('操作'),
      dataIndex: 'operation',
      key: 'operation',
      width: 88,
      align: 'center',
    },
  ];
  let typeOptions = [
    {
      id: NodeEventExType.API,
      name: t('执行API'),
    },
  ];
  const tableKey = ref(0);
  watch(
    () => state.eventConfigs,
    (val) => {
      if (val && val.length) {
        nextTick(() => {
          const tbody: any = document.querySelector(`.table-box .ant-table-tbody`);
          Sortable.create(tbody, {
            handle: `.draggable-icon`,
            onEnd: ({ oldIndex, newIndex }) => {
              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || newIndex === oldIndex) {
                return;
              }
              const columns = cloneDeep(state.eventConfigs);
              const oldColumns = cloneDeep(state.eventConfigs);
              columns[newIndex] = oldColumns[oldIndex];
              columns[oldIndex] = oldColumns[newIndex];
              state.eventConfigs = cloneDeep(columns);
              tableKey.value++;
            },
          });
        });
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );
  onMounted(() => {
    state.eventConfigs = props.eventConfigs;
  });
  // 新增
  function add() {
    state.eventConfigs.push({
      id: randomNum(),
      type: NodeEventExType.API,
      apiConfig: {},
    });
  }
  //删除
  function deleteItem(index: number) {
    state.eventConfigs.splice(index, 1);
  }
  async function validateForm() {
    if (state.eventConfigs && state.eventConfigs.length > 0) {
      return true;
    } else {
      message.error(t('请填写运维配置'));
      return false;
    }
  }
  function getFormData() {
    return state.eventConfigs;
  }
  defineExpose({
    validateForm,
    getFormData,
  });
</script>

<style lang="less" scoped>
  .basic-box {
    height: 100%;
    overflow: hidden auto;
    background-color: #fff;
    border-radius: 16px;
    padding: 24px;
  }

  .form-box {
    width: 70%;
    height: 100%;
    margin: 0 auto;
  }

  .list-box {
    .opr-box {
      display: flex;
      justify-content: flex-end;
      margin: 0 10px 10px;
    }
  }

  .delete-icon {
    color: @clear-color;
  }

  .pop-desc {
    font-size: 12px;
    color: rgb(0 0 0 / 40%);
  }

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