<script setup lang="ts">
import {onMounted, ref} from "vue";
import {
  deleteById,
  fileSave,
  folderSave,
  getPermissionsByUserCode,
  getReportCenterTree,
  modifyTheFileName,
  move
} from "@/api/base-data/report-center";
import {CyMessageBox} from "@/components/cy/message-box";
import {SaveFile} from "@/api/base-data/type/magic-api";
import {useCompRef} from "@/utils/useCompRef";
import {ElTree} from "element-plus";
import {Document, Folder} from "@element-plus/icons-vue";
import RightClickMenu from "@/components/menu-item/RightClickMenu.vue";
import {ReportForms} from "@/api/reports/report-query-center";
import {createFile, pageHelpV2Mitt, REPORT_FOLDER} from "@/views/data-base/page-editor-help-v2/page-help-v2";
import type Node from 'element-plus/es/components/tree/src/model/node'
import type {DragEvents} from 'element-plus/es/components/tree/src/model/useDragNode'
import type {
  NodeDropType,
} from 'element-plus/es/components/tree/src/tree.type'
import CyAutoSize from "@/components/cy/auto-size/cy-auto-size.vue";
import {useElementSize} from "@vueuse/core";

enum FILE_ENUM {
  FILE = 0,
  FOLDER = 1,
}

interface Props {
  nodeClick?: (data: ReportForms) => void,
  editor?: boolean
}

//@ts-ignore
const props = withDefaults(defineProps<Props>(), {
  editor: false,
})

const treeData = ref([])
const treeRef = useCompRef(ElTree)
const mousePosition = ref()
const inputValue = ref('')
const headerRef = ref()

const {height: headerHeight} = useElementSize(headerRef)


function generateRandomPath() {
  const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';
  let lastCharTypeIsLowerCase = true; // 用于记录上一个字符是否为小写

  // 第一个字符为小写
  result += characters.charAt(Math.floor(Math.random() * 26));

  for (let i = 1; i < 7; i++) {
    let charIndex;
    if (lastCharTypeIsLowerCase) {
      charIndex = Math.floor(Math.random() * 52);
    } else {
      charIndex = Math.floor(Math.random() * 26);
    }
    result += characters.charAt(charIndex);
    lastCharTypeIsLowerCase = (charIndex < 26); // 判断当前字符类型
  }

  return "/" + result;
}

async function createANewReport(flag: FILE_ENUM, parentId: string = REPORT_FOLDER) {
  const res = await CyMessageBox.prompt({
    message: `输入 ${flag === FILE_ENUM.FILE ? '文件' : '文件夹'} 名称！`,
    type: "info"
  })

  const path = generateRandomPath();

  if (flag === FILE_ENUM.FILE) {
    const data: SaveFile = {
      groupId: parentId,
      headers: [],
      method: 'POST',
      name: res.value,
      options: [],
      parameters: [],
      path: generateRandomPath(),
      paths: [],
      script: `var data = db.select("""""")

return {
    data: data,
    columns: []
}`,
      pageJson: createFile()
    }
    await fileSave(data)
  } else {
    await folderSave({name: res.value, path, parentId, type: 'api'})
  }
  queryData()
}

const contextmenu = (event: Event, data: ReportForms) => {
  if (!props.editor) {
    return
  }
  mousePosition.value = {
    event,
    data: data,
    index: data['$treeNodeId']
  }
}
const config = [
  {
    name: '新增文件夹',
    click: (data) => {
      createANewReport(FILE_ENUM.FOLDER, data.id)
    }
  },
  {
    name: '新增文件',
    click: (data) => {
      createANewReport(FILE_ENUM.FILE, data.id)
    }
  },
  {
    name: '修改文件名',
    click: async (data) => {
      const box = await CyMessageBox.prompt({
        message: `输入新的文件名！`,
        type: 'info',
        inputDefaultValue: data.name
      })
      await modifyTheFileName({
        id: data.id,
        name: box.value,
        type: data.type
      })
      data.name = box.value
    }
  },
  {
    name: '删除',
    click: async (data) => {
      await CyMessageBox.confirm({
        message: `确认删除【${data.name}】吗？`
      })
      await deleteById(data.id)
      queryData()
    }
  }
]

function nodeClick(data: ReportForms) {
  if (data.type === 1) {
    return
  }
  if (props.nodeClick) {
    props.nodeClick(data)
  } else {
    pageHelpV2Mitt.emit('changePageJson', data)
  }
}

function handleDragEnd(
    draggingNode: Node,
    dropNode: Node,
    dropType: NodeDropType,
    _ev: DragEvents) {
  let src = draggingNode.data.id
  let groupId = ''
  if (dropType === 'inner') {
    groupId = dropNode.data.id
  } else {
    groupId = dropNode.data.parentId || REPORT_FOLDER
  }
  move(src, groupId)
}


function queryData() {
  getReportCenterTree().then(res => {
    treeData.value = res
  })
}

function handleInputChange(val) {
  treeRef.value!.filter(val)
}

function handelFilter(value, data) {
  return data.name.includes(value)
}

function rowClick(row) {
  getPermissionsByUserCode(row.code).then(res => {
    treeRef.value!.setCheckedKeys(res)
  })
}


onMounted(() => {
  queryData()

  pageHelpV2Mitt.on('queryTree', () => {
    queryData()
  })
})
</script>

<template>
  <RightClickMenu v-if="props.editor" :config="config" :mouse-position="mousePosition"/>
  <cy-auto-size>
    <template #default="{height , width}">
      <div ref="headerRef">
        <div v-if="props.editor">
          <el-button-group>
            <el-button @click="createANewReport(FILE_ENUM.FOLDER)"> 文件夹</el-button>
            <el-button @click="createANewReport(FILE_ENUM.FILE)">文件</el-button>
          </el-button-group>
        </div>
        <div>
          <el-input placeholder="搜索报表" @input="handleInputChange" v-model="inputValue"/>
        </div>
      </div>
      <div :style="{height : height - headerHeight - 10 + 'px'  , width: width - 5 + 'px' }" style="overflow: auto">
        <el-tree :data="treeData"
                 ref="treeRef"
                 :filter-node-method="handelFilter"
                 @node-click="nodeClick"
                 @node-contextmenu="contextmenu"
                 @node-drag-end="handleDragEnd"
                 highlight-current
                 :draggable="props.editor"
                 node-key="id"
                 default-expand-all>
          <template #default="{node,data}">
            <el-icon>
              <Document v-if="data.type === 0"/>
              <Folder v-else/>
            </el-icon>
            {{ data.name }}
          </template>
        </el-tree>
      </div>
    </template>
  </cy-auto-size>
</template>

<style scoped lang="scss">

</style>
