<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>
                  <el-link :href="getReportEditUrl(row)"
                    target="_blank"
                    style="margin-left: 10px">{{ row.name }}</el-link>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="是否被分享"
              key="hasShare"
              prop="hasShare"
              align="center"
              width="120"
              sortable>
              <!-- 使用 tag 标记颜色 -->
              <template #default="{ row }">
                <el-tag :type="row.shareViewUrl ? 'success' : 'danger'">{{ row.shareViewUrl ? '是' : '否'
                }}</el-tag>
              </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="handleView(scope.row)"></el-button>
                </xl-tool-tip>
                <xl-tool-tip content="分享报表"
                  placement="top">
                  <el-button link
                    type="primary"
                    icon="Share"
                    @click="handleShare(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-dialog title="创建分享链接"
          v-model="dialogVisible">
          <div v-if="shareReportUrl">
            <el-form-item label="分享链接">
              <el-input v-model="shareReportUrl"
                style="width: 80%; margin-right: 20px;"
                placeholder="分享链接" />
              <el-button type="primary"
                v-copyText="shareReportUrl"
                v-copyText:callback="copyTextSuccess">复制链接剪切板</el-button>
            </el-form-item>
          </div>
          <div v-else>
            <el-form label-width="180px"
              v-model="shareForm">
              <el-form-item label="过期时间">
                <el-radio-group v-model="shareForm.termOfValidity">
                  <el-radio value="1">永久有效</el-radio>
                  <el-radio value="2">7天</el-radio>
                  <el-radio value="3">1天</el-radio>
                </el-radio-group>
              </el-form-item>
              <!-- <el-form-item label="是否开启密码">
              <el-radio-group v-model="shareForm.isPasswordEnabled">
                <el-radio label="否">否</el-radio>
                <el-radio label="是">是</el-radio>
              </el-radio-group>
            </el-form-item> -->
              <!-- <el-form-item label="是否检验分享token">
              <el-switch v-model="shareForm.isCheckToken" />
            </el-form-item> -->
            </el-form>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary"
                @click="handleConfirm">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </el-row>
    </div>
  </div>
</template>

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

const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const reportBaseDomain = import.meta.env.VITE_APP_REPORT_URL // 基础域名
const reportViewURL = import.meta.env.VITE_APP_REPORT_PREVIEW_URL // 预览
const reportShareViewURL = import.meta.env.VITE_APP_REPORT_SHARE_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 getReportEditUrl = (row) => {
  return `${reportBaseDomain}${reportEditURL}/${row.id}?&token=${getToken()}&tenantId=${userStore.$state.userInfo.deptId}`
}

/********* 报表功能按钮 ***********/
// 新建报表
const handleAdd = async () => {
  const res = await addReportAPI()
  window.open(`${reportBaseDomain}${reportEditURL}/${res.result.id}?&token=${getToken()}&tenantId=${userStore.$state.userInfo.deptId}&menuType=${queryParams.reportType}`)
}
// 导入报表
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 handleView = (row) => {
  window.open(`${reportBaseDomain}${reportViewURL}/${row.id}?token=${getToken()}&tenantId=${userStore.$state.userInfo.deptId}`)
}

// 分享报表
const shareReportUrl = ref('') // 分享报表地址链接
const dialogVisible = ref(false)
const nowShareRow = ref(null) // 当前分享报表数据对象
const shareForm = reactive({
  termOfValidity: '1', // 1：永久有效 2：7天 3：1天
  // isPasswordEnabled: '否',
  verifyShareToken: true
})
const handleShare = async (row) => {
  const res = await selShareReportAPI({
    reportId: row.id
  })
  shareReportUrl.value = res.result?.previewUrl ? reportBaseDomain + reportShareViewURL + res.result?.previewUrl : ''
  nowShareRow.value = row
  dialogVisible.value = true
}
// 确认分享
const handleConfirm = async () => {
  if (shareReportUrl.value) {
    dialogVisible.value = false
    return
  }
  const res = await addOrEditShareReportAPI({
    id: nowShareRow.value.id,
    lastUpdateTime: new Date().getTime(),
    previewLock: "",
    previewLockStatus: "0",
    previewUrl: "",
    reportId: nowShareRow.value.id,
    shareToken: Math.random().toString(36).substring(2),
    status: "0",
    termOfValidity: shareForm.termOfValidity,
    verifyShareToken: shareForm.verifyShareToken ? '1' : '0'
  })
  shareReportUrl.value = reportBaseDomain + reportShareViewURL + res.result?.previewUrl
  // 将分享链接复制到剪贴板
  const input = document.createElement('input')
  input.setAttribute('value', shareReportUrl.value)
  document.body.appendChild(input)
  input.select()
  document.execCommand('copy')
  document.body.removeChild(input)
  proxy.$modal.msgSuccess('链接已复制到剪切板')
  dialogVisible.value = false
  getReportList()
}
// 点击分享地址复制
function copyTextSuccess() {
  proxy.$modal.msgSuccess('链接已复制到剪切板')
}


// 修改报表
const handleEdit = (row) => {
  window.open(`${reportBaseDomain}${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>