<template>
  <div @click="handleShow" class="slot-item">
    <slot></slot>
  </div>
  <ModalPanel
    :width="1200"
    :visible="visible"
    :title="t('表单设置')"
    @submit="handleSubmit"
    @close="close"
  >
    <template #left>
      <NodeHead class="header-title" :node-name="t('参数名称')" />
      <div style="height: calc(100% - 50px)" class="overflow-auto py-2.5" v-if="visible">
        <a-tree
          v-model:checkedKeys="checkedKeys"
          checkable
          blockNode
          defaultExpandAll
          :tree-data="treeData"
          @check="handleCheck"
        />
      </div>
    </template>
    <div class="relative h-full" v-if="visible">
      <NodeHead class="header-title" :node-name="t('摘要内容列表')" />
      <div
        :class="[prefixCls, data.length > 0 ? prefixCls + '-form-has-pagenation' : '']"
        style="height: calc(100% - 50px)"
      >
        <a-table
          :key="tableKey"
          :columns="columns"
          :data-source="data"
          :pagination="{
            size: 'none',
            showQuickJumper: true,
            showSizeChanger: true,
            showLessItems: true,
          }"
          size="middle"
          class="table-box"
        >
          <template #headerCell="{ column }">
            <div class="header-cell__custom-title">{{ column.title }}</div>
          </template>
          <template #bodyCell="{ column, index }">
            <template v-if="column.dataIndex === 'index'"> {{ index + 1 }}</template>
            <template v-if="column.dataIndex === 'sort'">
              <svg class="icon sortDraggable-icon" aria-hidden="true" style="cursor: move">
                <use xlink:href="#icon-fangxiang1" />
              </svg>
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </ModalPanel>
</template>
<script lang="ts" setup>
  import { ref, watch, nextTick } from 'vue';
  import { getUsedFormList } from '/@bpmn/config/info';
  import { useI18n } from '/@/hooks/web/useI18n';
  import type { TreeProps } from 'ant-design-vue';
  import Sortable from 'sortablejs';
  import { isNullAndUnDef } from '/@/utils/is';
  import { cloneDeep } from 'lodash-es';
  import { ModalPanel } from '/@/components/ModalPanel/index';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { useDesign } from '/@/hooks/web/useDesign';
  const { prefixCls } = useDesign('basic-table');
  const { t } = useI18n();

  const treeData: TreeProps['treeData'] = [
    {
      title: '流程基本信息',
      key: 'basicInfo',
      children: [
        {
          title: '发起人名称',
          key: 'name',
          parentName: '流程基本信息',
          parentKey: 'basicInfo',
        },
        {
          title: '发起人所属部门名称',
          key: 'deptName',
          parentName: '流程基本信息',
          parentKey: 'basicInfo',
        },
        {
          title: '发起人所属公司名称',
          key: 'companyName',
          parentName: '流程基本信息',
          parentKey: 'basicInfo',
        },
        {
          title: '发起人所属岗位名称',
          key: 'postName',
          parentName: '流程基本信息',
          parentKey: 'basicInfo',
        },
        {
          title: '发起人所属角色名称',
          key: 'roleName',
          parentName: '流程基本信息',
          parentKey: 'basicInfo',
        },
        {
          title: '流程模板名称',
          key: 'templateName',
          parentName: '流程基本信息',
          parentKey: 'basicInfo',
        },
        {
          title: '流程模板分类',
          key: 'templateCategory',
          parentName: '流程基本信息',
          parentKey: 'basicInfo',
        },
        {
          title: '流程发起时间(yyyy-MM-dd HH:mm:ss)',
          key: 'startTimeHH',
          parentName: '流程基本信息',
          parentKey: 'basicInfo',
        },
        {
          title: '流程发起时间(yyyy-MM-dd)',
          key: 'startTime',
          parentName: '流程基本信息',
          parentKey: 'basicInfo',
        },
      ],
    },
    {
      title: '系统表单',
      key: 'system',
      children: [],
    },
    {
      title: '自定义表单',
      key: 'custom',
      children: [],
    },
  ];
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 70,
      align: 'center',
    },
    {
      title: '排序',
      dataIndex: 'sort',
      width: 70,
      align: 'center',
    },
    {
      title: '来源',
      dataIndex: 'formName',
      width: 200,
      align: 'center',
    },
    {
      title: '内容',
      dataIndex: 'fieldName',
      align: 'center',
    },
  ];
  const hiddenComponents = [
    'title',
    'text',
    'divider',
    'button',
    'form',
    'form-view',
    'one-for-one',
    'image',
    'qrcode',
    'opinion',
    'tab',
    'card',
    'grid',
    'iframe',
  ];
  const props = defineProps({
    summaryInfo: Array,
  });
  const emits = defineEmits(['success', 'info']);
  const data = ref<any>([]);
  const visible = ref(false);
  const checkedKeys = ref<string[]>([]);
  const tableKey = ref<number>(0);

  watch(
    () => props.summaryInfo,
    (val: any) => {
      let info = '';
      if (val && val.length) {
        const infoArr = val.map((x) => x.fieldName);
        info = infoArr.join(':,').concat('。');
      }
      emits('info', info);
    },
    {
      immediate: true,
      deep: true,
    },
  );

  watch(
    () => data.value,
    (val) => {
      if (val && val.length) {
        nextTick(() => {
          const tbody: any = document.querySelector('.table-box .ant-table-tbody');
          if (!tbody) return;
          Sortable.create(tbody, {
            handle: '.sortDraggable-icon',
            onEnd: ({ oldIndex, newIndex }) => {
              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || newIndex === oldIndex) {
                return;
              }
              const columns = cloneDeep(data.value);
              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);
              }
              data.value = cloneDeep(columns);
              tableKey.value++;
            },
          });
        });
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );

  const handleShow = async () => {
    treeData[1].children = [];
    treeData[2].children = [];
    let { formKeyList } = getUsedFormList();
    visible.value = true;
    if (props.summaryInfo) {
      data.value = props.summaryInfo;
      checkedKeys.value = data.value.map((x) =>
        x.formKey === 'basicInfo' ? x.fieldId : x.formKey + x.fieldId,
      );
    }
    for (let key in formKeyList) {
      const itemChildren = formKeyList[key].children
        ?.filter((x) => !hiddenComponents.includes(x.type))
        .map((child, index) => {
          return {
            title: child.fieldName,
            fieldId: child.fieldId,
            key: formKeyList[key].key + (child.fieldId || index),
            parentName: formKeyList[key].formName,
            parentKey: formKeyList[key].key,
          };
        });
      const children = {
        title: formKeyList[key].formName,
        key: formKeyList[key].key,
        children: itemChildren,
      };
      if (formKeyList[key].formType === 1) {
        treeData[2].children!.push(children);
      }
      if (formKeyList[key].formType === 0) {
        treeData[1].children!.push(children);
      }
    }
  };

  const handleCheck = (_, { checkedNodes }) => {
    data.value = checkedNodes
      .filter((x) => !x.children)
      .map((item) => {
        return {
          formName: item.parentName,
          fieldName: item.title,
          fieldId: item.fieldId || item.key,
          formKey: item.parentKey,
          key: item.key,
        };
      });
  };

  const close = () => {
    visible.value = false;
    treeData[1].children = [];
    treeData[2].children = [];
  };

  const handleSubmit = () => {
    emits('success', data.value);
    visible.value = false;
  };
</script>
<style lang="less" scoped>
  .header-title {
    height: 50px;
    border-bottom: 1px solid #eee;
    padding: 0 16px;
  }

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