<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="工作间名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入工作间名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="leaderUserId">
        <el-select
          v-model="queryParams.leaderUserId"
          @change="handleSupervisorChange"
          placeholder="请选择负责人"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="user in users"
            :key="user.id"
            :label="user.nickname"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="工作间地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入工作间地址"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
    
      <!-- <el-form-item label="负责人" prop="leaderUserId">
        <el-select
          v-model="queryParams.leaderUserId"
          @change="handleQuery"
          placeholder="请选择负责人"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.nickname"
            :value="user.id"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择工作间状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:dept:create']"
        >
          <Icon icon="ep:plus" /> 新增
        </el-button>
        <!-- <el-button type="danger" plain @click="toggleExpandAll">
          <Icon icon="ep:sort" class="mr-5px" /> 展开/折叠
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :default-expand-all="isExpandAll"
      v-if="refreshTable"
    >
    <!-- <el-table-column label="序号" align="center">
        <template #default="scope">
          {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column> -->
      <el-table-column type="index" width="50" />
      <el-table-column prop="name" label="工作间名称" align="center" />
      <el-table-column prop="leader" label="负责人" align="center">
        <template #default="scope">
          {{ userList.filter((user) => scope.row.leaderUserId.includes(user.id)).map(user => user.nickname).join(', ') }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系电话" align="center" />
      <el-table-column prop="email" label="邮箱" align="center" />
      <el-table-column prop="address" label="工作间地址" align="center" />
      <el-table-column prop="description" label="简介" align="center">
  <template #default="scope">
    <span>
      {{ stripHtml(scope.row.description).substring(0, 10) + (stripHtml(scope.row.description).length > 10 ? '...' : '') }}
    </span>
  </template>
</el-table-column>

      <!-- <el-table-column prop="sort" label="排序" /> -->
      <!-- <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:dept:update']"
          >
            修改
          </el-button>
          <el-button type="text" @click="openUserAchievement(scope.row.id)">
            详情
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:dept:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
  <!-- 表单弹窗：添加/修改 -->
  <DeptForm ref="formRef" @success="handleFormSuccess" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import DeptForm from './DeptForm.vue'
import * as UserApi from '@/api/system/user'
import { useRouter } from 'vue-router'

defineOptions({ name: 'SystemDept' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref() // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  name: undefined,
  leaderUserId: [],
  phone: undefined,
  email: undefined,
  address: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

/** 查询部门列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeptApi.getDeptPage(queryParams)
    console.log(data,'111');
    list.value = handleTree(data)
  } finally {
    loading.value = false
  }
}

//获取所有导师
const users = ref()
const getSupervisor= async () => {
  try {
    const response = await UserApi.getSupervisor()
    users.value = response
  } catch (error) {
    console.error('Error fetching user data:', error)
  }
}
//传supervisorId给queryParams.leaderUserId
const handleSupervisorChange = (value: number) => {
  const selectedUser = users.value.find(user => user.id === value);
  if (selectedUser) {
    queryParams.leaderUserId = selectedUser.id;
    handleQuery();
    // queryParams.supervisor = selectedUser.nickname;
  }
}

const extractedImageUrls = ref<string[]>([]); // 用于保存提取的图片 URL
const handleFormSuccess = (urls) => {
  getList();
  extractedImageUrls.value = urls; // 接收从子组件传递的图片 URL
  console.log('接收到的图片 URL:', extractedImageUrls.value);
}

const router = useRouter()
const openUserAchievement = (id) => {
  router.push({ 
    name: 'DeptInfo', 
    query: { id: id }, 
  });
}

const stripHtml = (html) => {
  if (!html) return '';
  return html.replace(/<[^>]*>/g, ''); // 去除所有 HTML 标签
};

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  console.log("当前查询参数:", queryParams);
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNo = 1
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 删除操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeptApi.deleteDept(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}


/** 初始化 **/
onMounted(async () => {
  await getList()
  // 获取用户列表
  userList.value = await UserApi.getSimpleUserList()
  console.log(userList.value,'000');
  getSupervisor()
})
</script>
