<template>
  <div class="app-container">
    <div class="container">
      <el-row :gutter="20"
        class="client-fix-height container">
        <category-tree v-model="queryParams.reportType"
          :options="floderList"
          :defaultProps="{ label: 'title', children: 'children' }"
          node-key="id"
          placeholder="搜索文件夹名称"
          :defaultExpandList="defaultExpandList"
          :colSpan="4"
          :customOptions="{
            showIcon: true
          }"
          @search="handleNodeClick">
        </category-tree>

        <el-col :span="20"
          :xs="24"
          class="right_col">
          <el-form :model="queryParams"
            ref="queryRef"
            :inline="true"
            label-width="68px">
            <el-form-item label="报表名字"
              prop="name">
              <el-input v-model="queryParams.name"
                placeholder="请输入用户工号"
                clearable
                style="width: 240px"
                @input="getReportList" />
            </el-form-item>
          </el-form>

          <el-row :gutter="10"
            class="mb8">
            <el-col :span="1.5">
              <el-button type="primary"
                plain
                icon="Plus"
                @click="handleAdd">新建报表</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="info"
                plain
                icon="Upload"
                @click="handleImport">导入报表</el-button>
            </el-col>
          </el-row>

          <el-table v-loading="loading"
            :data="reportList">
            <el-table-column type="selection"
              width="50" />
            <el-table-column label="报表名称"
              key="name"
              prop="name"
              align="left">
              <template #default="{ row }">
                <div>
                  <svg-icon icon-class="bg-document"></svg-icon>
                  <span style="margin-left: 10px">{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作"
              class-name="small-padding fixed-width"
              align="left"
              width="200">
              <template #default="scope">
                <xl-tool-tip content="预览报表"
                  placement="top">
                  <el-button link
                    type="primary"
                    icon="View"
                    @click="handlePreview(scope.row)"></el-button>
                </xl-tool-tip>
                <xl-tool-tip content="修改"
                  placement="top">
                  <el-button link
                    type="primary"
                    icon="Edit"
                    @click="handleEdit(scope.row)"></el-button>
                </xl-tool-tip>
                <xl-tool-tip content="删除"
                  placement="top"
                  v-if="scope.row.userId !== 1">
                  <el-button link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"></el-button>
                </xl-tool-tip>
                <xl-tool-tip content="复制报表"
                  placement="top"
                  v-if="scope.row.userId !== 1">
                  <el-button link
                    type="primary"
                    icon="CopyDocument"
                    @click="handleCopy(scope.row)"></el-button>
                </xl-tool-tip>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getReportList" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { getToken } from '@/utils/auth'
import { getReportFolderStructureAPI, getDesignReportListAPI, deleteReportAPI, copyReportAPI, addReportAPI, importReportAPI } from '@/api'
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const reportViewURL = import.meta.env.VITE_APP_REPORT_PREVIEW_URL // 预览
const reportEditURL = import.meta.env.VITE_APP_REPORT_EDIT_URL // 新增/编辑

/************ 文件夹分组 ********************/
const floderList = ref([{ // 文件夹结构
  id: '0',
  izLeaf: 0,
  pid: '-1',
  sortNo: 0,
  title: '文件夹',
  value: '0',
  children: []
}])
const defaultExpandList = ref([])

const getReportFolderStructure = async (obj) => {
  // 递归判断每个 res.result 数组里的对象去请求，有数据放到 children 里，没有则停止递归
  const res = await getReportFolderStructureAPI({
    parentId: obj.id
  })

  obj.children = [...res.result]
  floderList.value = [...floderList.value]

  // 确保返回数据有效
  res.result.forEach(o => {
    if (o.izLeaf === 0) {
      // 还有底层数据继续请求
      getReportFolderStructure(o)
    }
  })

  // 只需要在初始化时设置一次展开
  if (defaultExpandList.value.length === 0) {
    defaultExpandList.value = [floderList.value[0].id]
    // 选中最外层文件夹
    queryParams.reportType = floderList.value[0].id
  }
}
getReportFolderStructure(floderList.value[0])

// 某行点击
const handleNodeClick = (row) => {
  queryParams.reportType = row ? row.id : '0' // 文件夹 id 固定是 0（当不选择左侧文件夹默认查询所有）
  getReportList()
}

/**************** 报表列表 ***************/
// 报表搜索
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  reportType: '', // 文件夹 ID
  name: '', // 搜索名字字段
  token: getToken()
})
const loading = ref(false)
const reportList = ref([])
const total = ref(0)
const getReportList = async () => {
  loading.value = true
  const res = await getDesignReportListAPI(queryParams)
  loading.value = false
  reportList.value = res.result.records
  total.value = res.result.total
}
getReportList()


/********* 报表功能按钮 ***********/
// 新建报表
const handleAdd = async () => {
  const res = await addReportAPI()
  window.open(`${reportEditURL}/${res.result.id}?menuType=${queryParams.reportType}&token=${getToken()}&tenantId=${userStore.$state.userInfo.deptId}`)
}
// 导入报表
const handleImport = () => {
  proxy.chooseFile({
    accept: '.json'
  }).then(async file => {
    // 在这里可以添加文件上传的逻辑
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', queryParams.reportType)
    const res = await importReportAPI(formData)
    proxy.$modal.msgSuccess(res.result)
     getReportList()
  }).catch(err => {
    proxy.$modal.msgError(err)
  })
 
}
// 预览报表
const handlePreview = (row) => {
  window.open(`${reportViewURL}/${row.id}?token=${getToken()}&tenantId=${userStore.$state.userInfo.deptId}`)
}
// 修改报表
const handleEdit = (row) => {
  window.open(`${reportEditURL}/${row.id}?token=${getToken()}&tenantId=${userStore.$state.userInfo.deptId}`)
}
// 删除报表
const handleDelete = (row) => {
  proxy.$modal.confirm('确定删除该报表吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用删除接口
    deleteReportAPI({
      id: row.id,
      token: getToken()
    }).then(res => {
      proxy.$modal.msgSuccess('删除成功')
      getReportList()
    }).catch(err => {
      proxy.$modal.msgError(err.message)
    })
  })
}
// 复制报表
const handleCopy = (row) => {
  // 确认提示框
  proxy.$modal.confirm('确定复制该报表吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    copyReportAPI({
      id: row.id,
      token: getToken()
    }).then(res => {
      proxy.$modal.msgSuccess('复制成功')
      getReportList()
    }).catch(err => {
      proxy.$modal.msgError(err.message)
    })
  })
}

</script>

<style scoped></style>