<template>
  <div class="project-member-page">
    <div class="header-section">
      <h3>{{ t('project.management.detail.menu.projectMember') }}</h3>
      <el-button v-hasPermi="['project:management:queryProjectMemberAddMember']" type="primary" icon="Plus"
        @click="handleAddMember">
        添加成员
      </el-button>
    </div>
    <el-divider />

    <el-card shadow="never">
      <el-table v-loading="loading" border :data="memberList" style="width: 100%">
        <el-table-column prop="id" :label="t('project.management.table.id')" width="60" align="center" />
        <el-table-column :label="t('project.management.member.name')" align="center" prop="name" width="150" />
        <el-table-column :label="t('project.management.member.phoneNumber')" align="center" prop="phoneNumber"
          width="150" />
        <el-table-column :label="t('project.management.member.dept')" align="center" prop="dept" min-width="200"
          show-overflow-tooltip />
        <el-table-column :label="t('project.management.member.time')" align="center" prop="time" width="180" />
        <el-table-column label="操作栏" align="center" width="150" fixed="right">
          <template #default="scope">
            <el-tooltip content="修改文件夹权限" placement="top">
              <el-button v-hasPermi="['project:management:queryProjectMemberAssignFolders']" type="primary" link
                icon="Setting" @click="handleAssignFolders(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 添加成员对话框 -->
    <el-dialog v-model="addDialog.visible" :title="addDialog.title" width="800px" append-to-body>
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input v-model="addForm.phoneNumber" placeholder="请输入手机号" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="addForm.nickname" placeholder="请输入昵称" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username" placeholder="请输入用户名" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password" type="password" placeholder="请输入密码" maxlength="20" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="addForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select v-model="addForm.deptId" :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属部门"
                check-strictly style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="addForm.roleIds" multiple placeholder="请选择角色" style="width: 100%">
                <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId"
                  :disabled="item.status == '1'" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="文件夹权限">
              <div style="width: 100%;">
                <el-checkbox v-model="isAllFoldersSelected" @change="handleSelectAllFolders"
                  style="margin-bottom: 10px;">
                  全选
                </el-checkbox>
                <div
                  style="width: 100%; max-height: 300px; overflow-y: auto; border: 1px solid #dcdfe6; border-radius: 4px; padding: 10px;">
                  <data-permision-tree ref="addFolderTreeRef" :data="folderOptions"
                    v-model:selected-keys="addSelectedFolders" @check="handleAddFolderCheck"
                    :disabled="isAllFoldersSelected">
                    <template #default="{ node, data }">
                      <span class="custom-tree-node">
                        <el-icon>
                          <Folder v-if="data.type === 0" />
                          <Location v-else-if="data.type === 1" />
                          <OfficeBuilding v-else-if="data.type === 2" />
                          <Document v-else />
                        </el-icon>
                        <span>{{ node.name }}</span>
                      </span>
                    </template>
                  </data-permision-tree>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="addForm.remark" type="textarea" :rows="4" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="addButtonLoading" type="primary" @click="submitAddForm">确定</el-button>
          <el-button @click="cancelAdd">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改文件夹权限对话框 -->
    <el-dialog v-model="folderDialog.visible" :title="folderDialog.title" width="600px" append-to-body>
      <div style="width: 100%;">
        <el-checkbox v-model="isAllFoldersSelectedForEdit" @change="handleSelectAllFoldersForEdit"
          style="margin-bottom: 10px;">
          全选
        </el-checkbox>
        <div
          style="width: 100%; max-height: 400px; overflow-y: auto; border: 1px solid #dcdfe6; border-radius: 4px; padding: 10px;">
          <data-permision-tree ref="folderTreeRef" :data="folderOptions" v-model:selected-keys="selectedFolders"
            @check="handleFolderCheck" :disabled="isAllFoldersSelectedForEdit">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <el-icon>
                  <Folder v-if="data.type === 0" />
                  <Location v-else-if="data.type === 1" />
                  <OfficeBuilding v-else-if="data.type === 2" />
                  <Document v-else />
                </el-icon>
                <span>{{ node.name }}</span>
              </span>
            </template>
          </data-permision-tree>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="folderButtonLoading" type="primary" @click="submitFolderForm">确定</el-button>
          <el-button @click="cancelFolder">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { inject, ref, onMounted, getCurrentInstance, toRefs } from 'vue';
import { useI18n } from 'vue-i18n';
import { queryProjectMember, addProjectMember, getFolders, assignFolders } from '@/api/project/management';
import { ProjectMemberVO, ProjectMemberQuery, AddProjectMemberForm, AssignFoldersForm } from '@/api/project/management/types';
import { deptTreeSelect, getUser } from '@/api/system/user';
import { DeptTreeVO } from '@/api/system/dept/types';
import { RoleVO } from '@/api/system/role/types';
import { listFolderOnProject } from '@/api/document/folder';
import { FolderListVO } from '@/api/document/folder/types';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import type { ComponentInternalInstance } from 'vue';
import { Folder, Location, OfficeBuilding, Document } from '@element-plus/icons-vue';
import DataPermisionTree from '@/components/DataPermisionTree/index.vue';

const { t } = useI18n();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_user_sex } = toRefs<any>(proxy?.useDict('sys_user_sex'));

// 接收从父组件传递的项目ID
const projectId = inject<any>('projectId');

// 列表数据
const memberList = ref<ProjectMemberVO[]>([]);
const loading = ref(true);
const total = ref(0);

// Form refs
const addFormRef = ref<FormInstance>();
const folderTreeRef = ref<any>();
const addFolderTreeRef = ref<any>();

// 添加成员对话框
const addDialog = ref({
  visible: false,
  title: '添加成员'
});

// 文件夹权限对话框
const folderDialog = ref({
  visible: false,
  title: '修改文件夹权限'
});

// 按钮 loading
const addButtonLoading = ref(false);
const folderButtonLoading = ref(false);

// 部门和角色选项
const deptOptions = ref<DeptTreeVO[]>([]);
const roleOptions = ref<RoleVO[]>([]);
const folderOptions = ref<FolderListVO[]>([]);

// 文件夹选中的ID列表
const selectedFolders = ref<number[]>([]);
const addSelectedFolders = ref<number[]>([]);

// 全选文件夹相关
const isAllFoldersSelected = ref(false);
const isAllFoldersSelectedForEdit = ref(false);

// 当前操作的用户
const currentMember = ref<ProjectMemberVO | null>(null);

// 添加成员表单
const addForm = ref<AddProjectMemberForm>({
  projectId: 0,
  phoneNumber: '',
  nickname: '',
  username: '',
  password: '',
  email: '',
  gender: '',
  roleIds: [],
  deptId: 0,
  folders: ''
});

/**
 * 处理全选文件夹
 * @param checked 是否选中
 */
const handleSelectAllFolders = (checked: boolean) => {
  if (checked) {
    // 全选时，设置folders为"*"
    addForm.value.folders = '*';
    // 清空树形组件的选中状态，避免冲突
    addSelectedFolders.value = [];
  } else {
    // 取消全选时，清空folders
    addForm.value.folders = '';
  }
};

/**
 * 处理修改权限时的全选文件夹
 * @param checked 是否选中
 */
const handleSelectAllFoldersForEdit = (checked: boolean) => {
  if (checked) {
    // 全选时，设置folders为"*"
    // 注意：这里我们不直接修改表单，而是在提交时处理
    // 清空树形组件的选中状态，避免冲突
    selectedFolders.value = [];
  }
};


// 表单验证规则
const addRules = {
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789][0-9]\d{8}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度必须介于2和20之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 20, message: '密码长度必须介于5和20之间', trigger: 'blur' },
    { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\ |', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  roleIds: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  deptId: [
    { required: true, message: '请选择归属部门', trigger: 'change' }
  ]
};

// 查询参数
const queryParams = ref<ProjectMemberQuery>({
  pageNum: 1,
  pageSize: 10,
  id: projectId?.value || 0
});

/** 查询项目成员列表 */
const getList = async () => {
  loading.value = true;
  try {
    queryParams.value.id = projectId?.value || 0;
    const res = await queryProjectMember(queryParams.value);
    memberList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('Failed to fetch project members:', error);
  } finally {
    loading.value = false;
  }
};

/** 获取部门树 */
const getDeptTree = async () => {
  try {
    const res = await deptTreeSelect();
    deptOptions.value = res.data;
  } catch (error) {
    console.error('Failed to fetch dept tree:', error);
  }
};

/** 获取文件夹列表 */
const getFolderList = async () => {
  try {
    const res = await listFolderOnProject(projectId?.value || 0);
    folderOptions.value = res.data || [];
  } catch (error) {
    console.error('Failed to fetch folder list:', error);
  }
};

/** 打开添加成员对话框 */
const handleAddMember = async () => {
  // 重置表单
  addForm.value = {
    projectId: projectId?.value || 0,
    phoneNumber: '',
    nickname: '',
    username: '',
    password: '',
    email: '',
    gender: '',
    roleIds: [],
    deptId: undefined,
    folders: ''
  };
  addSelectedFolders.value = [];
  isAllFoldersSelected.value = false;
  addFormRef.value?.resetFields();

  // 获取部门和角色数据
  await getDeptTree();
  try {
    const res = await getUser();
    roleOptions.value = res.data.roles || [];
  } catch (error) {
    console.error('Failed to fetch roles:', error);
  }

  // 获取文件夹列表
  await getFolderList();

  addDialog.value.visible = true;
};

/** 处理添加成员文件夹选中 */
const handleAddFolderCheck = () => {
  // 如果全选状态下，不处理单个文件夹的选择
  if (isAllFoldersSelected.value) {
    return;
  }

  // 直接使用addSelectedFolders，因为DataPermisionTree已经过滤了顶级节点
  addForm.value.folders = addSelectedFolders.value.join(',');
};

/** 提交添加成员表单 */
const submitAddForm = () => {
  addFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      addButtonLoading.value = true;
      try {
        // 如果不是全选状态，才需要设置文件夹
        if (!isAllFoldersSelected.value) {
          // 直接使用addSelectedFolders，因为DataPermisionTree已经过滤了顶级节点
          addForm.value.folders = addSelectedFolders.value.join(',');
        }

        await addProjectMember(addForm.value);
        ElMessage.success('添加成员成功');
        addDialog.value.visible = false;
        await getList();
      } catch (error) {
        console.error('Failed to add member:', error);
      } finally {
        addButtonLoading.value = false;
      }
    }
  });
};

/** 取消添加成员 */
const cancelAdd = () => {
  addDialog.value.visible = false;
  addForm.value = {
    projectId: 0,
    phoneNumber: '',
    nickname: '',
    username: '',
    password: '',
    email: '',
    gender: '',
    roleIds: [],
    deptId: 0,
    folders: ''
  };
  addSelectedFolders.value = [];
  isAllFoldersSelected.value = false;
};

/** 打开修改文件夹权限对话框 */
const handleAssignFolders = async (row: ProjectMemberVO) => {
  currentMember.value = row;

  // 重置全选状态
  isAllFoldersSelectedForEdit.value = false;

  // 获取文件夹列表
  await getFolderList();

  // 获取用户当前的文件夹权限
  try {
    const res = await getFolders(row.id, projectId?.value || 0);
    const folders = res.data.folders;
    // 检查是否为全选状态
    if (folders === '*') {
      isAllFoldersSelectedForEdit.value = true;
      selectedFolders.value = [];
    } else if (folders) {
      selectedFolders.value = folders.split(',').map(id => parseInt(id)).filter(id => !isNaN(id));
    } else {
      selectedFolders.value = [];
    }
  } catch (error) {
    console.error('Failed to fetch user folders:', error);
    selectedFolders.value = [];
  }

  folderDialog.value.visible = true;
};

/** 处理文件夹选中 */
const handleFolderCheck = () => {
  // 如果全选状态下，不处理单个文件夹的选择
  if (isAllFoldersSelectedForEdit.value) {
    return;
  }
  // 不需要处理，提交时再获取
};

/** 提交文件夹权限表单 */
const submitFolderForm = async () => {
  if (!currentMember.value) return;

  folderButtonLoading.value = true;
  try {
    let foldersValue = '';

    // 如果全选状态，设置为"*"
    if (isAllFoldersSelectedForEdit.value) {
      foldersValue = '*';
    } else {
      // 直接使用selectedFolders，因为DataPermisionTree已经过滤了顶级节点
      foldersValue = selectedFolders.value.join(',');
    }

    const data: AssignFoldersForm = {
      userId: currentMember.value.id,
      projectId: projectId?.value || 0,
      folders: foldersValue
    };

    await assignFolders(data);
    ElMessage.success('修改文件夹权限成功');
    folderDialog.value.visible = false;
    await getList();
  } catch (error) {
    console.error('Failed to assign folders:', error);
  } finally {
    folderButtonLoading.value = false;
  }
};

/** 取消修改文件夹权限 */
const cancelFolder = () => {
  folderDialog.value.visible = false;
  selectedFolders.value = [];
  currentMember.value = null;
  isAllFoldersSelectedForEdit.value = false;
};

// 组件挂载时加载数据
onMounted(() => {
  getList();
});
</script>

<style scoped>
.project-member-page {
  height: 100%;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.info-section {
  padding: 16px 0;
}

.info-section p {
  line-height: 2;
  font-size: 14px;
  color: #606266;
  margin: 8px 0;
}

.info-section strong {
  color: #303133;
  margin-right: 8px;
}

h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.info-tip {
  color: #909399;
  font-style: italic;
  margin-top: 16px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
}

.custom-tree-node .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

.custom-tree-node span {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
