<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="分类管理" :centered="true" width="80%" :useWrapper="true" :footer="null">
    <div style="background-color: #ececec; padding: 10px">
      <a-row :gutter="8">
        <a-col :span="12">
          <div :style="{ overflow: 'hidden', height: '85vh' }">
            <ShowFileCotent ref="refShowFileCotent" />
          </div>
        </a-col>
        <a-col :span="12">
          <a-card style="height: calc(85vh)">
            <vxe-toolbar ref="toolbarRef">
              <template #buttons>
                <vxe-button @click="insertEvent">新增</vxe-button>
                <vxe-button @click="handleSubmit">保存</vxe-button>
              </template>
              <template #tools>
                <vxe-button status="text" @click="reloadData">刷新</vxe-button>
                <vxe-button status="text" @click="handleClose">关闭</vxe-button>
              </template>
            </vxe-toolbar>
            <div :style="{ overflow: 'hidden', height: '75vh' }">
              <vxe-table
                size="small"
                class="mytable-style"
                :cell-class-name="cellClassName"
                show-overflow
                keep-source
                ref="tableRef"
                height="auto"
                :row-config="{}"
                :column-config="{ resizable: true }"
                :print-config="{}"
                :export-config="{}"
                :loading="loading"
                :scroll-y="{ enabled: true, gt: 50 }"
                :tree-config="{ transform: true, rowField: 'id', parentField: 'parentId' }"
                :edit-config="{ trigger: 'click', mode: 'cell', showStatus: false }"
                :data="tableData"
              >
                <vxe-column field="parentId" tree-node width="50" />
                <vxe-column field="name" title="名称" :edit-render="{ autofocus: '.vxe-input--inner', placeholder: '请输入内容' }">
                  <template #edit="{ row }">
                    <vxe-input v-model="row.name" mode="text" />
                  </template>
                </vxe-column>

                <vxe-column title="操作" width="260">
                  <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)" />
                    </template>
                    <vxe-button mode="text" status="danger" @click="removeRow(row)">删除</vxe-button>
                  </template>
                </vxe-column>
              </vxe-table>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, nextTick } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { VXETable, VxeTableInstance, VxeToolbarInstance } from 'vxe-table';
  import { allList, saveOrUpdate, saveOrUpdateSingle, deleteOne, batchDelete } from '../api/AuditFileContentCategories.api';
  import ShowFileCotent from './ShowFileContent.vue';

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

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

  const fileId = ref();

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

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

    fileId.value = data.record.fileId;
    tableData.value = await allList({ fileId: fileId.value });
    refShowFileCotent.value.setDocFile(data?.record);
  });

  async function reloadData() {
    tableData.value = await allList({ fileId: fileId.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].name == '') {
          createMessage.error('请输入名称');
          //await $table.clearEdit();
          return false;
        }
      }

      await saveOrUpdate(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 = {
          name: ``,
          id: rid,
          parentId: currRow.parentId,
          fileId: fileId.value,
        };
        const { row: newRow } = await $table.insertAt(record, currRow);
        await $table.setEditRow(newRow);
      } else if (locat === 'top') {
        const record = {
          name: ``,
          id: rid,
          parentId: currRow.id,
          fileId: fileId.value,
        };
        const { row: newRow } = await $table.insert(record);
        await $table.setTreeExpand(currRow, true);
        await $table.setEditRow(newRow);
      } else if (locat === 'bottom') {
        const record = {
          name: ``,
          id: rid,
          parentId: currRow.id,
          fileId: fileId.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 = {
        name: ``,
        id: '',
        parentId: null,
        fileId: fileId.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.name == '') {
      createMessage.error('请输入名称');
      return false;
    }
    const $grid = tableRef.value;
    if ($grid) {
      if (row.id == '') {
        await saveOrUpdateSingle(row, false);
      } else {
        await saveOrUpdateSingle(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 === 'name') {
      if (row.parentId != null) {
        return 'col-child';
      }
      // else if (row.parentId != null && row.hasChild == true) {
      //   return 'col-grandChild';
      // }
    }
    return null;
  }
</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>
