<template>
  <div class="app-container">
    <div class="container">
      <el-form :model="queryParams"
        ref="queryRef"
        inline
        label-width="68px"
        v-show="showSearch">
        <el-form-item label="报表名称"
          prop="name">
          <el-input v-model="queryParams.name"
            placeholder="搜索报表名称"
            clearable
            style="width: 240px"
            @input="getReportList" />
        </el-form-item>
        <el-form-item label="报表类目"
          prop="category">
          <el-select v-model="queryParams.category"
            placeholder="选择报表类目"
            clearable
            filterable
            @change="getReportList"
            style="width: 240px">
            <el-option v-for="item in categoryList"
              :label="item.name"
              :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <el-row :gutter="10"
        class="mb8">
        <!-- <el-col :span="1.5">
          <el-button type="primary"
            plain
            icon="Plus"
            :disabled="reportMultipleBtnDis"
            @click="handleAssign">分配用户</el-button>
        </el-col> -->
        <!-- <right-toolbar v-model:showSearch="showSearch"
          @queryTable="getReportList"></right-toolbar> -->
      </el-row>

      <!-- 表格数据 -->
      <el-table v-loading="loading"
        :data="reportList"
        @selection-change="handleSelectionReport">
        <!-- <el-table-column type="selection"
          width="50" /> -->
        <el-table-column label="报表名称"
          key="name"
          prop="name"
          align="left"
          sortable>
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <svg-icon icon-class="bg-document"></svg-icon>
              <el-link :href="getReportPreviewUrl(row)"
                target="_blank"
                style="margin-left: 10px">{{ row.name }}</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="报表类目"
          key="categoryName"
          prop="categoryName"
          align="left"
          width="180"
          sortable />
        <el-table-column label="创建人"
          key="createBy"
          prop="createBy"
          align="left"
          width="180"
          sortable />
        <el-table-column label="创建时间"
          prop="createTime"
          align="left"
          width="180"
          sortable>
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </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.hasShare === true ? 'success' : 'danger'">{{ row.hasShare === true ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作"
          class-name="small-padding fixed-width"
          align="left"
          width="100">
          <template #default="scope">
            <xl-tool-tip content="分配用户"
              placement="top">
              <el-button link
                type="primary"
                icon="User"
                @click="handleAssign(scope.row)"></el-button>
            </xl-tool-tip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getReportList" />

      <!-- 分配用户 -->
      <el-dialog v-model="showSelUser"
        draggable
        overflow
        modal-class="assign-user-dialog"
        @closed="closeSelUserDialog">
        <template #header>
          <el-form :model="userParams"
            inline>
            <el-form-item label="部门选择"
              prop="roleName">
              <el-tree-select v-model="userParams.deptId"
                :data="deptOptions"
                filterable
                clearable
                highlight-current
                node-key="id"
                check-strictly
                :default-expanded-keys="defaultExpandedKeys"
                style="width: 200px"
                @change="getUserList" />
            </el-form-item>
            <el-form-item label="用户昵称"
              prop="nickName">
              <el-input v-model="userParams.nickName"
                placeholder="请输入用户昵称"
                clearable
                style="width: 150px"
                @input="getUserList" />
            </el-form-item>
            <el-form-item label="用户工号"
              prop="userName">
              <el-input v-model="userParams.userName"
                placeholder="请输入用户工号"
                clearable
                style="width: 150px"
                @input="getUserList" />
            </el-form-item>
            <el-form-item label="手机号码"
              prop="phonenumber">
              <el-input v-model="userParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                style="width: 150px"
                @input="getUserList" />
            </el-form-item>
          </el-form>
        </template>

        <el-row>
          <el-table ref="refTable"
            :data="userList"
            :loading="userLoading"
            @select="handleSelectChange"
            @selectAll="handleSelectAll">
            <el-table-column type="selection"
              width="55"></el-table-column>
            <el-table-column label="用户昵称"
              prop="nickName"
              :show-overflow-tooltip="true" />
            <el-table-column label="用户工号"
              prop="userName"
              :show-overflow-tooltip="true" />
            <el-table-column label="手机"
              prop="phonenumber"
              :show-overflow-tooltip="true" />
            <el-table-column label="状态"
              align="center"
              prop="status">
              <template #default="scope">
                <dict-tag :options="sys_normal_disable"
                  :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column label="创建时间"
              align="center"
              prop="createTime"
              width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>

        </el-row>
        <template #footer>
          <div class="dialog-footer">
            <div class="pagination-wrap">
              <pagination v-show="userTotal > 0"
                :total="userTotal"
                v-model:page="userParams.pageNum"
                v-model:limit="userParams.pageSize"
                @pagination="getUserList" />
            </div>
            <el-button type="primary"
              @click="handleSelectUser">确 定</el-button>
            <el-button @click="showSelUser = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup
  name="Role">
  import { selReportListAPI, selReportCategoryAPI, deptTreeSelectList, listUser, batchAuthReportAPI, selReportAuthUserListAPI } from "@/api"

  const { proxy } = getCurrentInstance()
  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 showSearch = ref(true)
  const queryParams = reactive({
    name: undefined, // 报表名称
    category: undefined, // 报表类目
    pageNum: 1,
    pageSize: 10
  })
  // 获取设置报表类目下拉菜单
  const categoryList = ref([])
  const getCategoryList = () => {
    selReportCategoryAPI().then(res => {
      categoryList.value = res.data;
    })
  }
  getCategoryList()

  // 批量分配报表
  const reportMultipleBtnDis = ref(true) // 是否多选报表
  const checkedReportRowList = ref([]) // 选择的报表对象
  const handleSelectionReport = (val) => {
    checkedReportRowList.value = val
    reportMultipleBtnDis.value = !(checkedReportRowList.value.length > 0)
  }

  // 获取报表列表
  const loading = ref(true)
  const reportList = ref([])
  const total = ref(0)
  // 查询报表列表
  function getReportList() {
    loading.value = true
    selReportListAPI(queryParams).then(response => {
      reportList.value = response.data.rows
      total.value = response.data.total
      loading.value = false
    })
  }
  getReportList()
  // 报表预览地址
  const getReportPreviewUrl = (row) => {
    return `${reportBaseDomain}${reportShareViewURL}${row.previewUrl}`
  }

  /**************** 分配用户 ****************/
  const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
  const showSelUser = ref(false)
  /** 查询用户列表 */
  const userList = ref([])
  const userLoading = ref(false)
  const userTotal = ref(0)
  const userParams = ref({
    deptId: undefined, // 部门 ID
    pageNum: 1,
    pageSize: 10
  })
  const selUserList = ref([]) // 当前表已经分配给的用户列表
  // 开始分配
  const handleAssign = async (obj) => {
    const res = await selReportAuthUserListAPI({
      reportId: obj.id,
      pageSize: 100
    })
    console.log('查询到', res)
    selUserList.value = res.data || []
    showSelUser.value = true
    if (obj.id) {
      // 如果 obj 有值则是单个分配
      checkedReportRowList.value = [obj]
    }
    handleRowClick()
  }

  // 部门查询
  const deptOptions = ref([]); // 部门树结构
  const defaultExpandedKeys = ref([]) // 默认展开 id

  function getDeptList() {
    deptTreeSelectList().then(response => {
      deptOptions.value = response.data;
      defaultExpandedKeys.value = [response.data[0].id];
    });
  }
  getDeptList()

  function getUserList() {
    userLoading.value = true;
    listUser(userParams.value).then(res => {
      userLoading.value = false;
      userList.value = res.data.rows;
      userTotal.value = res.data.total;
      handleRowClick()
    })
  }
  getUserList()

  // 单选用户
  const handleSelectChange = (selection, row) => {
    if (selection.includes(row)) {
      // 如果当前用户不在已分配用户列表中
      if (!selUserList.value.some(item => item.userId === row.userId)) {
        selUserList.value.push(row)
      }
    } else {
      // 取消选择
      const index = selUserList.value.findIndex(o => o.userId === row.userId)
      if (index !== -1) {
        selUserList.value.splice(index, 1)
      }
    }

    console.log(selUserList.value.map(o => o.userId), '当前')
  }
  // 全选反选用户
  const handleSelectAll = (selection) => {
    if (selection.length === 0) {
      // 取消当前页
      userList.value.forEach(o => {
        const index = selUserList.value.findIndex(item => item.userId === o.userId)
        if (index !== -1) {
          selUserList.value.splice(index, 1)
        }
      })
    } else {
      // 全选当前页
      userList.value.forEach(o => {
        // 如果当前用户不在已分配用户列表中
        if (!selUserList.value.some(item => item.userId === o.userId)) {
          selUserList.value.push(o)
        }
      })
    }

    console.log(selUserList.value, '当前')
  }

  // 确定分配给用户
  const handleSelectUser = async () => {
    const reportId = checkedReportRowList.value[0].id
    const userIds = selUserList.value.map(o => o.userId)
    await batchAuthReportAPI({
      reportId,
      userIds
    })
    // 通知成功并关闭弹窗
    proxy.$modal.msgSuccess('分配成功')
    showSelUser.value = false

  }

  // 表格动态设置复选框选中效果
  const handleRowClick = () => {
    // 这里添加设置选中状态的逻辑
    nextTick(() => {
      if (proxy.$refs.refTable) {
        proxy.$refs.refTable.clearSelection()
        const selectedIds = selUserList.value ? selUserList.value.map(o => o.userId) : []
        userList.value.forEach(row => {
          if (selectedIds.includes(row.userId)) {
            proxy.$refs.refTable.toggleRowSelection(row, true)
          }
        })
      }
    })
  }

  // 关闭分配用户弹窗
  const closeSelUserDialog = () => {
    userParams.value.pageNum = 1
    userParams.value.pageSize = 10
    getUserList()
  }

</script>
<style scoped
  lang="scss">
  .el-tree {
    height: 310px;
    overflow-y: scroll;

    /* 灰色滚动条背景 */
    &::-webkit-scrollbar-track {
      background-color: transparent;
    }
  }

  /* 分配用户 */
  ::v-deep(.assign-user-dialog) {
    color: white;

    .el-overlay-dialog .el-dialog .el-dialog__header {
      height: auto !important;
      padding-bottom: 0px;
    }
  }

</style>