<template>
    <div>
        <TableSearch :query="query" :options="searchOpt" :search="handleSearch" :refresh="getData" />
        <div class="container">
            <TableCustom :columns="columns" :tableData="tableData" :total="page.total" :viewFunc="handleView"
                :delFunc="handleDelete" :changePage="changePage" :currentPage="page.index"  :editFunc="handleEdit">
                <template #toolbarBtn>
                    <el-button type="warning" :icon="CirclePlusFilled" @click="visible_add = true">新增</el-button>
                    <el-button type="primary" @click="showUserTreeVisibale">查看组织架构</el-button>
                </template>
            </TableCustom>

        </div>
        <el-dialog :title="isEdit ? '编辑': '编辑'" v-model="visible" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options_edit" :edit="isEdit" :update="updateData" />
        </el-dialog>
        <el-dialog :title="isAdd ? '新增' : '新增'" v-model="visible_add" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options" :edit="isAdd" :update="addData" />
        </el-dialog>
        <el-dialog :title="'新建用户组'" v-model="visible_add_group" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData_" :options="options_gourp" :edit="isAddGroup" :update="addGroupData" />
        </el-dialog>
        <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
            <TableDetail :data="viewData"></TableDetail>
        </el-dialog>

        <el-dialog title="调整组织架构" v-model="visible_change_group" width="500px" destroy-on-close>
            <div>
                <el-row>
                    <p>当前用户/用户组：{{ currentNode.name }}</p>
                </el-row>
                
                <el-row style="margin-top: 20px;">
                    <p>用户组：</p>
                    <el-select v-model="currentNode.prev" placeholder="选择类型">
                        <el-option v-for="opt in opts_group" :label="opt.label" :value="opt.value"></el-option>
                    </el-select>
                </el-row>
                <el-row style="margin-top: 20px;">
                    <el-button type="primary" @click="updateUserCatalogue(currentNode)">确 定</el-button>
                </el-row>
            </div>
        </el-dialog>

        <el-dialog title="组织架构" v-model="visible_system" width="900px" destroy-on-close>
            <div>
                <el-button type="primary" link @click="append_group({id:0,name:'根目录',type:0})">
                    添加用户组
                </el-button>
                <el-tree
                ref="treeRef"
                style="max-width: 800px;"
                :data="treeData" 
                :props="treeProps"
                :filter-method="filterMethod"
                :height="400"
                show-checkbox
                default-expand-all
                :expand-on-click-node="false"
            >
            <template #default="{ node, data }">
                <div class="custom-tree-node">
                <span>{{ node.label }}</span>
                <div>
                    <el-button type="primary" link @click="handleNodeClick(data)">
                    调整
                    </el-button>
                    <el-button type="primary" link @click="append_user(data)" v-if="data.type != 0">
                    添加用户
                    </el-button>
                    <el-button type="primary" link @click="append_group(data)" v-if="data.type != 0">
                    添加用户组
                    </el-button>
                    <el-button type="primary" link @click="show_get_token_visible(data)" v-if="data.type == 0">
                    获取token
                    </el-button>
                    <el-button
                    style="margin-left: 4px"
                    type="danger"
                    link
                    @click="remove(node, data)"
                    >
                    删除
                    </el-button>
                </div>
                </div>
            </template>
            </el-tree>
        </div>


        </el-dialog>

        <el-dialog title="获取用户Token" v-model="getTokenVisible" width="500px" destroy-on-close
            :close-on-click-modal="false" @close="closeTokenDialog">
            <div>
                <el-form :model="getTokenParams" label-width="120px">
                    <el-form-item label="用户ID：">
                        <el-input v-model="getTokenParams.user_id" disabled />
                    </el-form-item>
                    <el-form-item label="访问令牌有效期：">
                        <el-input-number v-model="getTokenParams.expire_in" :min="60" :max="8640000" :step="60" />
                        <span style="margin-left: 10px;">秒 (默认3600秒)</span>
                    </el-form-item>
                    <el-form-item label="刷新令牌有效期：">
                        <el-input-number v-model="getTokenParams.refresh_expire_in" :min="300" :max="60480000" :step="300" />
                        <span style="margin-left: 10px;">秒 (默认86400秒)</span>
                    </el-form-item>
                </el-form>
                <el-row style="margin-top: 20px; text-align: center;">
                    <el-button type="primary" @click="getTokenCode" :loading="tokenLoading">获取Token</el-button>
                </el-row>
                
                <!-- Token结果显示区域 -->
                <div v-if="tokenResult" style="margin-top: 20px;">
                    <el-divider>获取结果</el-divider>
                    <el-form :model="tokenResult" label-width="100px">
                        <el-form-item label="访问Token：">
                            <el-input 
                                v-model="tokenResult.access_token" 
                                type="textarea" 
                                :rows="3" 
                                readonly 
                                style="font-family: monospace;"
                            />
                            <el-button type="text" @click="copyToClipboard(tokenResult.access_token)">复制</el-button>
                        </el-form-item>
                        <el-form-item label="刷新Token：">
                            <el-input 
                                v-model="tokenResult.refresh_token" 
                                type="textarea" 
                                :rows="2" 
                                readonly 
                                style="font-family: monospace;"
                            />
                            <el-button type="text" @click="copyToClipboard(tokenResult.refresh_token)">复制</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                
                <div v-if="tokenError" style="margin-top: 20px;">
                    <el-alert :title="tokenError" type="error" show-icon />
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { UserInfo } from '@/types/user';
import { fetchUserData } from '@/api';
import { SearchUserService,AdminAddUserRequestService,UpdateUserCatalogueService,AdminDeleteUserRequestService,AdminAddUserGroupRequestService,GetUserTokenService } from "@/api/user";
import {GetUserInfoService} from "@/api/user";
import {updateUserInfoService} from "@/api/user";
import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import TableSearch from '@/components/table-search.vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import {getAllDefaultUsers} from '@/api/user';
import { tr, vi } from 'element-plus/es/locale';
import { group } from 'console';

interface Tree {
  id: number
  label: string
  children?: Tree[]
}

const visible_add_group = ref(false);
const opts_group = ref([]);
const currentNode = ref(null);
const currentPrev = ref(0); // 当前选中的父节点ID
const treeData = ref([]);
const treeProps = ref({
        id: 'id',       // 节点唯一标识字段（对应数据中的 id）
        label: 'name',  // 节点显示文本字段（对应数据中的 name）
        children: 'children' // 子节点数组字段（转换后会添加 children 字段）
      });
// 查询相关
const query = reactive({
    name: '',
});

const getTokenVisible = ref(false);

const getTokenParams = ref({
    "expire_in": 3600,
    "refresh_expire_in": 86400,
    "user_id": 0,
})

const tokenLoading = ref(false)
const tokenResult = ref(null)
const tokenError = ref('')

const getTokenCode = async () => {
    tokenLoading.value = true
    tokenError.value = ''
    tokenResult.value = null
    
    try {
        const response = await GetUserTokenService({
            user_id: getTokenParams.value.user_id,
            expire_in: getTokenParams.value.expire_in,
            refresh_expire_in: getTokenParams.value.refresh_expire_in
        })
        
        if (response["code"] === 0) {
            tokenResult.value = response.data
            ElMessage.success('获取Token成功')
        } else {
            tokenError.value = '获取失败: ' + response["message"]
            ElMessage.error(tokenError.value)
        }
    } catch (error) {
        console.error('获取Token失败:', error)
        tokenError.value = '获取Token失败: ' + error.message
        ElMessage.error(tokenError.value)
    } finally {
        tokenLoading.value = false
    }
}

const copyToClipboard = async (text) => {
    try {
        await navigator.clipboard.writeText(text)
        ElMessage.success('已复制到剪贴板')
    } catch (err) {
        console.error('复制失败:', err)
        ElMessage.error('复制失败')
    }
}

const closeTokenDialog = () => {
    tokenResult.value = null
    tokenError.value = ''
    getTokenParams.value = {
        "expire_in": 3600,
        "refresh_expire_in": 86400,
        "user_id": 0,
    }
}

const showUserTreeVisibale = async () => {
    await GetAllDefaultUsers();
    visible_system.value = true;
};

const show_get_token_visible = (data) => {
    currentNode.value = data;
    getTokenVisible.value = true;
    getTokenParams.value.user_id = data.id;
};


const updateUserCatalogue = async (data) => {
    try {
        let req={
            user_id: data.id,
            group_id: data.prev,
        }
        let result = await UpdateUserCatalogueService(req);
        if (result["code"] === 0) {
            ElMessage.success("调整成功");
            closeDialog();
        } else {
            ElMessage.error("调整失败:"+result["message"]);
        }
    } catch (error) {
        console.error('调整组织架构失败:', error);
    }
    GetAllDefaultUsers();
};

const GetAllDefaultUsers = async () => {
    try {
        const response = await getAllDefaultUsers();
        if (response['code'] !== 0) {
            console.error('获取默认用户失败:', response["message"]);
            return;
        }
        buildTree(response['data']);

        opts_group.value = [];

        for (const item of response['data']) {
            if (item.type === 1) { // 1为用户组
                opts_group.value.push({ label: item.name, value: item.id });
            }
        }
        opts_group.value.unshift({ label: '根目录', value: 0 });
    } catch (error) {
        console.error('获取默认用户失败:', error);
    }
};

const visible_change_group = ref(false);
const handleNodeClick = (data) => {
    currentPrev.value = data.id;
    currentNode.value = data;
    visible_change_group.value = true;
};

// GetAllDefaultUsers();

const append_user = (data) => {
    currentPrev.value = data.id;
    visible_add.value = true;
};

const append_group = (data) => {
    currentPrev.value = data.id;
    visible_add_group.value = true;
};

const remove =  async (node, data) => {
    await AdminDelUser(data);
    await GetAllDefaultUsers();
    // if(data.prev === 0){
    //     node.remove();
    //     return;
    // }
    // const parent = node.parent;
    // if (parent) {
    //     const index = parent.data.children.findIndex(item => item.id === data.id);
    //     if (index !== -1) {
    //       parent.data.children.splice(index, 1);
    //     }
    //   } else {
    //     // 如果没有父节点，说明是根节点，直接从 treeData 中删除
    //     const index = treeData.value.findIndex(item => item.id === data.id);
    //     if (index !== -1) {
    //       treeData.value.splice(index, 1);
    //     }
    //   }
};

const buildTree = (data) => {
      // 1. 用 map 存储所有节点（key 为 id，value 为节点对象），方便快速查找父节点
      const nodeMap = {};
      data.forEach(node => {
        // 为每个节点初始化 children 数组（避免后续添加子节点时 undefined 错误）
        nodeMap[node.id] = { ...node, children: [] };
      });

      // 2. 遍历所有节点，根据 prev 字段找到父节点，添加到父节点的 children 中
      const tree = [];
      Object.values(nodeMap).forEach(node => {
        const parentId = node["prev"];
        if (parentId === 0) {
          // prev 为 0 表示根节点，直接加入树形结构的顶层
          tree.push(node);
        } else {
          // 找到父节点，将当前节点添加到父节点的 children 中
          const parentNode = nodeMap[parentId];
          if (parentNode) {
            parentNode.children.push(node);
          }
        }
      });
        treeData.value = tree;
    };

const filterMethod =(node, value) =>{
      // node 是当前节点对象，value 是过滤输入的值
      return node.name.toLowerCase().includes(value.toLowerCase());
    }
const searchOpt = ref<FormOptionList[]>([
    { type: 'input', label: '用户名或ID：', prop: 'name' }
])
const handleSearch = async () => {
    let search_id= -1;
    let keyword_ = "";
    if (query.name === ''){
        ElMessage.error('请输入用户名或ID');
        return;
    }
    // 判断query.name是否是数字
    if (isNaN(Number(query.name))) {
        keyword_ = query.name;
    } else {
        search_id = parseInt(query.name);
    }
    let req={
        token: localStorage.getItem('token'),
        id: search_id,
        keyword: keyword_,
    }
    let result = await SearchUserService(req);
    page.total = result.data.length;
    page.index = 1;
    allData.value = result.data;
    // 分页
    let start = (page.index - 1) * page.size;
    let end = start + page.size;
    if (end > page.total) {
        end = page.total;
    }
    if (start > page.total) {
        start = page.total;
    }
    tableData.value = result.data.slice(start, end);
};

const visible_system = ref(false);

// 表格相关
let columns = ref([
    { type: 'index', label: '序号', width: 55, align: 'center' },
    { prop: 'ID', label: '用户ID' },
    { prop: 'Name', label: '用户名' },
    { prop: 'Age', label: '年龄'},
    { prop: 'Role', label: '角色' },
    { prop: 'CreatedAt', label: '创建时间',type: 'date' },
    { prop: 'Email', label: '邮箱' },
    { prop: 'operator', label: '操作', width: 250 ,operate: { view: true, edit: true, delete: true ,push: {link: false,label:"继续该会话"},gen: {show: false,label:"下载文件"}}},
])
const page = reactive({
    index: 1,
    size: 10,
    total: 122,
})
const tableData = ref<UserInfo[]>([]);
const allData = ref<UserInfo[]>([]);
const getData = async () => {
    let req={
        token: localStorage.getItem('token'),
        id: -1,
        keyword: "_121",
    }
    let result = await SearchUserService(req);
    page.total = result.data.length;
    page.index = 1;
    allData.value = result.data;
    // 分页
    let start = (page.index - 1) * page.size;
    let end = start + page.size;
    if (end > page.total) {
        end = page.total;
    }
    if (start > page.total) {
        start = page.total;
    }
    tableData.value = result.data.slice(start, end);
};
getData();

const addGroupData = async (data) => {
    let result ={}
      try{
        let req={
            prev: currentPrev.value,
            name: data.Name,
        }
        result = await AdminAddUserGroupRequestService(req);
        if (result["code"] === 0) {
            ElMessage.success("新增成功");
            closeDialog();
        } else {
            ElMessage.error("新增失败:"+result["message"]);
        }
        }catch(e){
            console.log(e);
        }
    GetAllDefaultUsers();
};
const addData = async (data) => {
    let result ={}
      try{
        let req={
            prev: currentPrev.value,
            name: data.Name,
            email: data.Email,
            password: data.Password,
        }
        
        result = await AdminAddUserRequestService(req);
        if (result["code"] === 0) {
            ElMessage.success("新增成功");
            closeDialog();
        } else {
            ElMessage.error("新增失败:"+result["message"]);
        }
        }catch(e){
            console.log(e);
        }
    getData(); 
    GetAllDefaultUsers();
};

const changePage = (val: number) => {
        page.index = val;
    //分页
    let start = (page.index - 1) * page.size;
    let end = start + page.size;
    if (end > page.total) {
        end = page.total;
    }
    if (start > page.total) {
        start = page.total;
    }
    tableData.value = allData.value.slice(start, end);
};

// 新增弹窗
let options = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', label: '用户名', prop: 'Name', required: true },
        { type: 'input', label: '密码', prop: 'Password', required: true },
        { type: 'input', label: '邮箱', prop: 'Email', required: true },
    ]
})

let options_gourp = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', label: '用户组名', prop: 'Name', required: true },
    ]
})

//编辑弹窗
let options_edit = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        {prop: 'Avatar',label: '头像', type: 'input', required: false},
        { type: 'input', label: '用户名', prop: 'Name', required: true },
        { type: 'input', label: '年龄', prop: 'Age', required: false },
        { type: 'input', label: '密码', prop: 'Password', required: false },
        { type: 'input', label: '邮箱', prop: 'Email', required: true },
        { type: 'select', label: '性别', prop: 'Gender', required: false,opts:[{label: '男', value:"男"},{label: '女', value:"女"}]},
        //select 选择框,可选择admin与user两种角色
        { type: 'select', label: '角色', prop: 'Role', opts: [{label:"管理员",value:"admin"},{label:"普通用户",value:"user"}],required: false },

    ]
})

const visible = ref(false);
const visible_add = ref(false);
const isEdit = ref(false);
const isAdd = ref(false);
const isAddGroup = ref(false);
const rowData = ref({});
const rowData_ = ref({});
const handleEdit = async (row: UserInfo) => {
    let data = await getUserInfo(row.ID);

    rowData.value = data;
    isEdit.value = true;
    visible.value = true;
};
const updateData = async (data) => {
    let result ={}
      try{
        let req={
            token:localStorage.getItem("token"),
            id: data.ID,
            name: data.Name,
            age: data.Age,
            gender: data.Gender,
            password: data.Password,
            email: data.Email,
            avatar: data.Avatar,
            role: data.Role,
        };

        result = await updateUserInfoService(req)
        if (result["code"] === 0) {
          ElMessage.success("更新成功");
        } else {
          ElMessage.error("更新失败");
        }

      }catch(e){
        console.log(e);
      }
      closeDialog();
    getData();
};

const getUserInfo = async (id) => {
      let result = {};
      try{
        //获取用户信息
        let req={
            token: localStorage.getItem('token'),
            id: id,
        };
        result = await GetUserInfoService(req)
        if(result['code'] === 0){
          return result['data'];
        }
      }catch(e){
        console.log(e);
      }
      return {};
    }

const closeDialog = () => {
    visible.value = false;
    visible_add.value = false;
    isEdit.value = false;
    visible_add_group.value = false;

};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
    row: {},
    list: []
});
const handleView =async (row: UserInfo) => {
    let data = await getUserInfo(row.ID);
    viewData.value.row = data;
    viewData.value.list = [
        {
            prop: 'Avatar',
            label: '头像', //显示头像
            type: 'image',
            width: 100,
        },
        {
            prop: 'ID',
            label: '用户ID',
        },
        {
            prop: 'Name',
            label: '用户名',
        },
        {
            prop: 'Email',
            label: '邮箱',
        },
        {
            prop: 'Gender',
            label: '性别',
        },
        {
            prop: 'Role',
            label: '角色',
        },
        {
            prop: 'CreatedAt',
            label: '注册日期',
            type: 'date',
        },
    ]
    visible1.value = true;
};

const AdminDelUser =async (data) => {
   console.log("删除用户:",data);
    try{
        let req={
            id: data.id,
        }

        let result = await AdminDeleteUserRequestService(req);
        if (result["code"] === 0) {
            ElMessage.success("删除成功");
        }else{
            ElMessage.error("删除失败:"+result["message"]);
        }
    }catch(e){
        console.log(e);
    }
};

// 删除相关
const handleDelete = (row: UserInfo) => {
    ElMessage.success('删除成功');
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>