<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="分类管理" :centered="true" width="60%" :useWrapper="true" :footer="null">
    <a-card style="height: calc(85vh)">
      <vxe-toolbar ref="toolbarRef">
        <template #buttons>
          <vxe-button status="primary" mode="text" @click="insertEvent">新增</vxe-button>
          <vxe-button status="primary" mode="text" @click="handleSubmit">保存</vxe-button>
        </template>
        <template #tools>
          <vxe-button status="primary" mode="text" @click="reloadData">刷新</vxe-button>
          <vxe-button status="primary" mode="text" @click="handleClose">关闭</vxe-button>
        </template>
      </vxe-toolbar>
      <div :style="{ overflow: 'hidden', height: '75vh' }">
       
       
        <vxe-table
          size="small"
          :cell-class-name="cellClassName"
          show-overflow
          keep-source
          ref="tableRef"
          height="auto"
          :row-config="{drag: true}"
          :column-config="{ resizable: true }"
          :row-drag-config="rowDragConfig"
          :print-config="{}"
          :export-config="{}"
          :loading="loading"
          :scroll-y="{ enabled: true, gt: 50 }"
          :tree-config="{ transform: true, rowField: 'id', parentField: 'parentId' }"
          :edit-config="{ trigger: 'dblclick', mode: 'cell', showStatus: false }"
          :data="tableData"
        >
         <vxe-column field="parentId"  title="" width="0"  fixed="left"></vxe-column>
          <vxe-column field="title" title="标题"   fixed="left" tree-node   drag-sort :edit-render="{ autofocus: '.my-input', autoselect: true }">
            <template #default="{ row }" >
              <span >{{ row.title }}</span>
            </template>
            <template #edit="{ row }">
              <vxe-input v-model="row.title" mode="text" />
            </template>
          </vxe-column>

          <vxe-column title="操作" width="180">
            <template #default="{ row }">
              <vxe-button mode="text" status="primary" @click="insertRow(row, 'bottom')">添加子节点</vxe-button>
              <template v-if="hasActiveEditRow(row)">
                <vxe-button mode="text" size="small" content="取消" @click="cancelRowEvent(row)" />
                <vxe-button mode="text" size="small" status="primary" content="保存" @click="saveRowEvent(row)" />
              </template>
              <template v-else>
                <vxe-button mode="text" size="small" content="编辑" @click="editRowEvent(row)" />
                <vxe-button mode="text" status="danger" @click="removeRow(row)">删除</vxe-button>
              </template>
            
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </a-card>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, nextTick,reactive } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { VxeUI, VxeTableInstance, VxeToolbarInstance,VxeTablePropTypes } from 'vxe-table';
  import { listAll, saveOrUpdate,batchSaveOrUpdate, deleteOne, batchDelete } from '../AuditProjectReportTitle.api';

  const { createMessage } = useMessage();
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  interface RowVO {
    id: number;
    parentId: number | null;
    title: string;
    projectId:number;
  }

  const loading = ref(false);
  const tableData = ref<RowVO[]>([]);
  const projectId = ref();

  const tableRef = ref<VxeTableInstance<RowVO>>();
  const toolbarRef = ref<VxeToolbarInstance>();

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    projectId.value = data.projectId;
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    tableData.value = await listAll({projectId: projectId.value});
  });

  async function reloadData() {
    tableData.value = await listAll({projectId: projectId.value });
  }

  async function handleSubmit() {
    try {
      const $table = tableRef.value;
      if (!$table) {
        return false;
      }
      setModalProps({ confirmLoading: true });
      const insertRecords = $table.getInsertRecords();
      const updateRecords = $table.getUpdateRecords();
      const mlist = mergeArrays(insertRecords, updateRecords);
      if (mlist.length == 0) return;

      for (let i = 0; i < mlist.length; i++) {
        if (mlist[i].title == '') {
          createMessage.error('请输入名称');
          //await $table.clearEdit();
          return false;
        }
      }

      await batchSaveOrUpdate(mlist);
      reloadData();
      await $table.clearEdit();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function mergeArrays(...arrays) {
    return arrays.reduce((accumulator, currentArray) => {
      if (Array.isArray(currentArray)) {
        return accumulator.concat(currentArray);
      }
      return accumulator;
    }, []);
  }

  const insertRow = async (currRow, locat) => {
    const $table = tableRef.value;
    if ($table) {
      const rid = '';
      if (locat === 'current') {
        const record = {
          title: ``,
          id: rid,
          parentId: currRow.parentId,
          projectId: projectId.value,
        };
        const { row: newRow } = await $table.insertAt(record, currRow);
        await $table.setEditRow(newRow);
      } else if (locat === 'top') {
        const record = {
          title: ``,
          id: rid,
          parentId: currRow.id,
          projectId: projectId.value,
        };
        const { row: newRow } = await $table.insert(record);
        await $table.setTreeExpand(currRow, true);
        await $table.setEditRow(newRow);
      } else if (locat === 'bottom') {
        const record = {
          title: ``,
          id: rid,
          parentId: currRow.id,
          projectId: projectId.value,
        };

        const { row: newRow } = await $table.insertAt(record, -1);
        await $table.setTreeExpand(currRow, true);
        await $table.setEditRow(newRow);
      }
    }
  };

  const removeRow = async (row: RowVO) => {
    const $table = tableRef.value;
    if ($table) {
      await batchDelete({ ids: row.id }, async function () {
        await $table.remove(row);
        //VXETable.modal.message({ content: '删除成功', status: 'warning' });
      });
    }
  };

  const insertEvent = async () => {
    const $table = tableRef.value;
    if ($table) {
      const record = {
        title: ``,
        id: '',
        parentId: null,
        projectId: projectId.value,
      };
      const { row: newRow } = await $table.insert(record);
      await $table.setEditRow(newRow);
    }
  };
  const hasActiveEditRow = (row) => {
    const $grid = tableRef.value;
    if ($grid) {
      return $grid.isEditByRow(row);
    }
    return false;
  };
  const editRowEvent = (row) => {
    const $grid = tableRef.value;
    if ($grid) {
      $grid.setEditRow(row);
    }
  };
  const cancelRowEvent = (row: RowVO) => {
    const $table = tableRef.value;
    if ($table) {
      $table.clearEdit().then(() => {
        // 还原行数据
        $table.revertData(row);
      });
    }
  };
  const saveRowEvent = async (row) => {
    if (row.title == '') {
      createMessage.error('请输入名称');
      return false;
    }
    const $grid = tableRef.value;
    if ($grid) {
      if (row.id == '') {
        await saveOrUpdate(row, false);
      } else {
        await saveOrUpdate(row, true);
      }
      reloadData();
      await $grid.clearEdit();
    }
  };

  function handleClose() {
    closeModal();
  }

  nextTick(() => {
    // 将表格和工具栏进行关联
    const $table = tableRef.value;
    const $toolbar = toolbarRef.value;
    if ($table && $toolbar) {
      $table.connect($toolbar);
    }
  });

  function cellClassName({ row, column }) {
    if (column.field === 'title') {
      if (row.parentId != null) {
        return 'col-child';
      }
    }
    return null;
  }

  
const rowDragConfig = reactive<VxeTablePropTypes.RowDragConfig<RowVO>>({
  isCrossDrag: true,
  isSelfToChildDrag: true,
  isToChildDrag: true,
  showGuidesStatus: true,
  async dragEndMethod(event) {
    const { newRow, oldRow, dragRow, dragPos } = event;

    const type = await VxeUI.modal.confirm({
      content: '是否确认调整顺序？'
    });

    if (type === 'confirm') {
      if (dragPos === "top") {
        dragRow.parentId = newRow.parentId; // 拖拽到目标节点的上方
      } else {
        dragRow.parentId = newRow.id; // 拖拽到目标节点的下方或内部
      }

      // 保存拖拽节点
      const retRow = await saveOrUpdate(dragRow, !!dragRow.id);

      return true;
    } else {
      VxeUI.modal.message({
        content: '操作已取消',
        status: 'warning'
      });
      return false;
    }
  }
});
</script>

<style lang="less" scoped>
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
  ::v-deep(.mytable-style.vxe-table .vxe-body--column.col-child) {
    padding: 0 20px;
  }
  ::v-deep(.mytable-style.vxe-table .vxe-header--column.col-grandChild) {
    padding: 0 40px;
  }
</style>
