<template>
    <div>
        <TableSearch :query="query" :options="searchOpt" :search="handleSearch" :refresh="refreshTableData" />
        <div class="container">
            <div 
                v-loading="loading" 
                loading-text="加载中..." 
                style="min-height: 300px;" 
                >
                <TableCustom :columns="columns" :tableData="tableData" :total="page.total" :viewFunc="handleView"
                    :delFunc="handleDelete" :changePage="changePage" :currentPage="page.index" :editFunc="handleEdit" :refresh="GetModelPolicy">
                    <template #toolbarBtn>
                        <el-button type="warning" :icon="CirclePlusFilled" @click="visible_add = true">新增</el-button>
                        <el-button type="primary" :icon="Search" @click="get_user_permission_policy_visible = true">模型策略检测</el-button>
                    </template>
                </TableCustom>
            </div>

        </div>
        <el-dialog :title="isEdit ? '编辑': '编辑'" v-model="visible" width="900px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options_edit" :edit="isEdit" :update="handleUpdateModelPolicy" />
        </el-dialog>
        <el-dialog :title="isAdd ? '新增' : '新增'" v-model="visible_add" width="900px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options" :edit="isAdd" :update="handleAddModelPolicy" />
        </el-dialog>
        <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
            <TableDetail :data="viewData"></TableDetail>
        </el-dialog>
    </div>
    <div>
        <el-dialog title="策略匹配检测" v-model="get_user_permission_policy_visible" width="700px" destroy-on-close>
            <el-input v-model="model_policy_check_req" placeholder="请输入用户ID或用户名" style="width: 50%;"></el-input>
            <el-button type="warning" :icon="Search" @click="GetOneModelPolicy">模型策略检测</el-button>
            <div>
                <!-- 显示检测结果 -->
                 <div v-if="model_policy_check_res.ID">
                    <p>匹配到的权限策略：{{ model_policy_check_res.name }}</p>
                    <p>描述信息：{{ model_policy_check_res.info }}</p>
                 </div>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
//获取query参数
import { onMounted,ref, reactive } from 'vue';
import { CirclePlusFilled,Search } from '@element-plus/icons-vue';
import {ModelPolicyResponseData, ModelPolicyUserRange} from '@/types/model_policy';
import {getAllDefaultUsers} from '@/api/user';
import {Model} from "@/types/model";
import {GetModelPolicyService, DelModelPolicyService, UpdateModelPolicyService, AddModelPolicyService} from '@/api/model_policy';
import { ElMessage } from 'element-plus';
import { FormOption, FormOptionList } from '@/types/form-option';
import {FindModelService} from "@/api/model";

const tableData = ref<ModelPolicyUserRange[]>([]);
const allData = ref<ModelPolicyUserRange[]>([]);
const visible = ref(false);
const visible_add = ref(false);
const isEdit = ref(false);
const isAdd = ref(false);
const rowData = ref<ModelPolicyUserRange>({} as ModelPolicyUserRange);
const user_select_opts = ref([]);
const model_select_opts = ref([]);
const get_user_permission_policy_visible = ref(false);
const model_policy_check_req = ref("");
const model_policy_check_res = ref<ModelPolicyUserRange>({} as ModelPolicyUserRange);
const model_list = ref<Model[]>([]);
const loading = ref(false);
// 查询相关
const query = reactive({
    name: '',
});
const page = reactive({
    index: 1,
    size: 10,
    total: 122,
});
const searchOpt = {};
const viewData = ref({
    row: {},
    list: [

    ]
});
// 查看详情弹窗相关
const visible1 = ref(false);

onMounted(async () => {
    // 获取query参数
    GetModelPolicy();

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

const getModelList = async () => {
    let req={
        token: localStorage.getItem('token'),
        type: "UserID"
    }
    try{
        let result = await FindModelService(req);
        if(result["code"] !== 0){
            ElMessage.error("获取模型列表失败:"+result["message"]);
            return;
        }
        model_list.value.length = 0;
        model_list.value = result["data"];
        model_select_opts.value.length = 0;
        for(let i=0;i<model_list.value.length;i++){
            let model = model_list.value[i];
            model_select_opts.value.push({
                value: model.ID,
                label: model.Type +"-"+ model.Description
            });
        }
        //console.log("model_select_opts:", model_select_opts.value);
    }catch(e){
        ElMessage.error("获取模型列表失败");
    }
}

getModelList();


const handleAddModelPolicy = async (data) => {
    // 添加权限策略
    let req = {
        "policy_name": data.name,
        "policy_info": data.info,
        "user_range": [],
        "model_id": [],
    };
    for(let i=0;i<data.range.length;i++){
        req.user_range.push({"id":data.range[i]});
    }
    for(let i=0;i<data.model_id.length;i++){
        req.model_id.push({"id":data.model_id[i]});
    }
    try {
        const response = await AddModelPolicyService(req);
        if (response['code'] !== 0) {
            ElMessage.error('添加权限策略失败:' + response["message"]);
            return;
        }
        ElMessage.success('添加权限策略成功');
        visible_add.value = false;
        GetModelPolicy();
    } catch (error) {
        console.error('获取权限策略失败:', error);
    }

};

const GetAllDefaultUsers = async () => {
    try {
        const response = await getAllDefaultUsers();
        if (response['code'] !== 0) {
            console.error('获取默认用户失败:', response["message"]);
            return;
        }
        user_select_opts.value.length = 0;
        for (let i = 0; i < response.data.length; i++) {
            let user = response.data[i];
            user_select_opts.value.push({
                value: user.id,
                label: (user.type === 0 ? "user":"group" )+ ":"+user.name
            });
        }
        // console.log("user_select_opts:", user_select_opts.value);
    } catch (error) {
        console.error('获取默认用户失败:', error);
    }
};

GetAllDefaultUsers();

const handleUpdateModelPolicy = async (data) => {
    // 更新权限策略
    let req = {
        "id": data.ID,
        "policy_name": data.name,
        "policy_info": data.info,
        "user_range": [],
        "model_id": [],
    };
    //upload_size和upload_max_size必须是数字
    for(let i=0;i<data.range.length;i++){
        req.user_range.push({"id":data.range[i]});
    }
    for(let i=0;i<data.model_id.length;i++){
        req.model_id.push({"id":data.model_id[i]});
    }
    //console.log("update req:", req);
        try {
        const response = await UpdateModelPolicyService(req);
        if (response['code'] !== 0) {
            ElMessage.error('更新权限策略失败:' + response["message"]);
            return;
        }
        ElMessage.success('更新权限策略成功');
        GetModelPolicy();
    } catch (error) {
        console.error('更新权限策略失败:', error);
    }

};
const handleDeleteModelPolicy = async () => {
    // 删除权限策略
    let req = {
        "id": 1,
    };
    try {
        const response = await DelModelPolicyService(req);
        if (response['code'] !== 0) {
            ElMessage.error('删除权限策略失败:' + response["message"]);
            return;
        }
        ElMessage.success('删除权限策略成功');
    } catch (error) {
        console.error('删除权限策略失败:', error);
    }
};
const GetOneModelPolicy = async () => {
    try {
        let req={
            type: 1,
            user_id: 0,
            user_name: ""
        }
        if (isNaN(Number(model_policy_check_req.value))) {
            req.user_name = model_policy_check_req.value;
        } else {
            req.user_id = parseInt(model_policy_check_req.value);
        }
        
        const response = await GetModelPolicyService(req);
        if (response['code'] !== 0) {
            console.error('获取权限策略失败:', response["message"]);
            return;
        }
        // allData.value = response.data;
        let temp: ModelPolicyResponseData = response.data;
        const jsonList: Array<{ id: number }> = JSON.parse(temp.policy.model_id);
        let temp_ :ModelPolicyUserRange = {
                ID: temp.policy.ID,
                CreatedAt: temp.policy.CreatedAt,
                UpdatedAt: temp.policy.UpdatedAt,
                DeletedAt: temp.policy.DeletedAt,
                name: temp.policy.name,
                info: temp.policy.info,
                model_id: jsonList.map(item => item.id),
                range: temp.range.map(item => item.id),
            };
            model_policy_check_res.value = temp_;
        
    } catch (error) {
        console.error('获取权限策略失败:', error);
    }
};
const sleep = (ms: number): Promise<void> => {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
};

const refreshTableData = () => {
    getModelList();
    GetModelPolicy();
    getAllDefaultUsers();
};
const GetModelPolicy = async () => {
    try {
        loading.value = true;
        const response = await GetModelPolicyService({});
        if (response['code'] !== 0) {
            console.error('获取权限策略失败:', response["message"]);
            return;
        }
        await sleep(100);
        
        // allData.value = response.data;
        allData.value = [];
        for (let i = 0; i < response.data.length; i++) {
            let temp: ModelPolicyResponseData = response.data[i];
            const jsonList: Array<{ id: number }> = JSON.parse(temp.policy.model_id);
            let temp_ :ModelPolicyUserRange = {
                ID: temp.policy.ID,
                CreatedAt: temp.policy.CreatedAt,
                UpdatedAt: temp.policy.UpdatedAt,
                DeletedAt: temp.policy.DeletedAt,
                name: temp.policy.name,
                info: temp.policy.info,
                model_id: jsonList.map(item => item.id),
                range: temp.range.map(item => item.id),
            };
            allData.value.push(temp_);
        }
        page.total = allData.value.length;
        page.index = 1;
        // 分页
        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);
        loading.value = false;
    } catch (error) {
        console.error('获取权限策略失败:', error);
        loading.value = false;
    }
};
const handleEdit = async (row) => {
    let data = row;
    // console.log("edit_row_data:", data);
    rowData.value = data;
    isEdit.value = true;
    visible.value = true;
};


const handleSearch = async () => {
    await GetModelPolicy();
    page.total = allData.value.length;
    page.index = 1;
    // 分页
    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 columns = ref([
    // { type: 'index', label: '序号', width: 55, align: 'center' },
    { prop: 'ID', label: '权限策略ID' },
    {prop: 'name', label: '名称'},
    { prop: 'info', label: '描述信息' },
    { prop: 'CreatedAt', label: '创建时间',type: 'date' },
    { prop: 'operator', label: '操作', width: 250 , operate: { view: true, edit: true, delete: true,push: {link: false,label:"继续该会话"},gen: {show: false,label:"下载文件"}, genv2:{type:"", label:"", show:false} }},
])

// 新增弹窗
let options = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', label: '名称', prop: 'name', required: true },
        { type: 'input', label: '描述', prop: 'info', required: true },
        { type: 'select', label: '模型范围', prop: 'model_id', required: true, opts:model_select_opts.value ,multiple: true},
        { type: 'select', label: '生效范围', prop: 'range', required: true, opts:user_select_opts.value ,multiple: true},
    ]
})

//编辑弹窗
let options_edit = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', label: '名称', prop: 'name', required: true },
        { type: 'input', label: '描述', prop: 'info', required: true },
        { type: 'select', label: '模型范围', prop: 'model_id', required: true, opts:model_select_opts.value ,multiple: true},
        { type: 'select', label: '生效范围', prop: 'range', required: true, opts:user_select_opts.value ,multiple: true},
    ]
})

const handleView =async (row) => {
    viewData.value.row = row;
    viewData.value.list = [
        {
            prop: 'ID',
            label: '模型策略ID',
        },
        {
            prop: 'name',
            label: '名称',
        },
        {
            prop: 'info',
            label: '描述',
        },
        {
            prop: 'CreatedAt',
            label: '创建时间',
            type: 'date'
        },
        {
            prop: 'UpdatedAt',
            label: '更新时间',
            type: 'date'
        },
    ]
    visible1.value = true;
};

// 删除相关
const handleDelete = async (row) => {
    let req={
        id: row.ID,
    }
    try{
        let result = await DelModelPolicyService(req);
        if(result['code'] === 0){
            ElMessage.success("删除成功");
            GetModelPolicy();
        }else{
            ElMessage.error("删除失败");
        }
    }catch(e){
        console.log(e);
    }
}

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);
};

</script>