<template>
    <div>
        <TableSearch :query="query" :options="searchOpt" :search="handleSearch" :refresh="GetPermissPolicy" />
        <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="GetPermissPolicy">
                    <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="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="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="permiss_policy_check_req" placeholder="请输入用户ID或用户名" style="width: 50%;"></el-input>
            <el-button type="warning" :icon="Search" @click="GetOnePermissPolicy">权限策略检测</el-button>
            <div>
                <!-- 显示检测结果 -->
                 <div v-if="permiss_policy_check_res.ID">
                    <p>匹配到的权限策略：{{ permiss_policy_check_res.name }}</p>
                    <p>描述信息：{{ permiss_policy_check_res.info }}</p>
                    <p>Redis权限：{{ permiss_policy_check_res.redis>0 ? '有' : '无' }}</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 {PermissPolicyResponseData, PolicyUserRange} from '@/types/permiss_policy';
import {GetPermissPolicyService, DelPermissPolicyService, UpdatePermissPolicyService, AddPermissPolicyService} from '@/api/permiss_policy';
import { ElMessage } from 'element-plus';
import { FormOption, FormOptionList } from '@/types/form-option';

const tableData = ref<PolicyUserRange[]>([]);
const allData = ref<PolicyUserRange[]>([]);
const visible = ref(false);
const visible_add = ref(false);
const isEdit = ref(false);
const isAdd = ref(false);
const rowData = ref<PolicyUserRange>({} as PolicyUserRange);
const user_select_opts = ref([]);
const get_user_permission_policy_visible = ref(false);
const permiss_policy_check_req = ref("");
const permiss_policy_check_res = ref<PolicyUserRange>({} as PolicyUserRange);
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参数
    GetPermissPolicy();

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

const handleAddPermissPolicy = async () => {
    // 添加权限策略
    let req = {
        "policy_name": "测试策略",
        "user_range": [{'id':1}]
    };
    try {
        const response = await AddPermissPolicyService(req);
        if (response['code'] !== 0) {
            ElMessage.error('添加权限策略失败:' + response["message"]);
            return;
        }
        ElMessage.success('添加权限策略成功');
    } catch (error) {
        console.error('获取权限策略失败:', error);
    }

};

const handleUpdatePermissPolicy = async () => {
    // 更新权限策略
    let req = {
        "id": 1,
        "policy_name": "测试策略",
        "user_range": [{'id':1}]
    };
        try {
        const response = await UpdatePermissPolicyService(req);
        if (response['code'] !== 0) {
            ElMessage.error('更新权限策略失败:' + response["message"]);
            return;
        }
        ElMessage.success('更新权限策略成功');
    } catch (error) {
        console.error('更新权限策略失败:', error);
    }

};
const handleDeletePermissPolicy = async () => {
    // 删除权限策略
    let req = {
        "id": 1,
    };
    try {
        const response = await DelPermissPolicyService(req);
        if (response['code'] !== 0) {
            ElMessage.error('删除权限策略失败:' + response["message"]);
            return;
        }
        ElMessage.success('删除权限策略成功');
    } catch (error) {
        console.error('删除权限策略失败:', error);
    }
};
const GetOnePermissPolicy = async () => {
    try {
        let req={
            type: 1,
            user_id: 0,
            user_name: ""
        }
        if (isNaN(Number(permiss_policy_check_req.value))) {
            req.user_name = permiss_policy_check_req.value;
        } else {
            req.user_id = parseInt(permiss_policy_check_req.value);
        }
        
        const response = await GetPermissPolicyService(req);
        if (response['code'] !== 0) {
            console.error('获取权限策略失败:', response["message"]);
            return;
        }
        // allData.value = response.data;
        let temp: PermissPolicyResponseData = response.data;
        let temp_ :PolicyUserRange = {
                ID: temp.policy.ID,
                CreatedAt: temp.policy.CreatedAt,
                UpdatedAt: temp.policy.UpdatedAt,
                DeletedAt: temp.policy.DeletedAt,
                name: temp.policy.name,
                info: temp.policy.info,
                redis: temp.policy.redis, // Redis 相关权限
                run_shell: temp.policy.run_shell, // 运行 Shell 相关权限
                upload: temp.policy.upload, // 上传相关权限
                cid: temp.policy.cid, // 同上
                file: temp.policy.file, // 同上
                device: temp.policy.device, // 设备相关权限
                upload_size: temp.policy.upload_size, // 同上
                upload_max_size: temp.policy.upload_max_size, // 同上
                send_mail: temp.policy.send_mail, // 发送邮件相关权限
                range: temp.range,
            };
            permiss_policy_check_res.value = temp_;
        
    } catch (error) {
        console.error('获取权限策略失败:', error);
    }
};
const sleep = (ms: number): Promise<void> => {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
};
const GetPermissPolicy = async () => {
    try {
        loading.value = true;
        const response = await GetPermissPolicyService({});
        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: PermissPolicyResponseData = response.data[i];
            let temp_ :PolicyUserRange = {
                ID: temp.policy.ID,
                CreatedAt: temp.policy.CreatedAt,
                UpdatedAt: temp.policy.UpdatedAt,
                DeletedAt: temp.policy.DeletedAt,
                name: temp.policy.name,
                info: temp.policy.info,
                redis: temp.policy.redis, // Redis 相关权限
                run_shell: temp.policy.run_shell, // 运行 Shell 相关权限
                upload: temp.policy.upload, // 上传相关权限
                cid: temp.policy.cid, // 同上
                file: temp.policy.file, // 同上
                device: temp.policy.device, // 设备相关权限
                upload_size: temp.policy.upload_size, // 同上
                upload_max_size: temp.policy.upload_max_size, // 同上
                send_mail: temp.policy.send_mail, // 发送邮件相关权限
                range: temp.range,
            };
            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);
        console.log("allData:", allData.value);
        loading.value = false;
    } catch (error) {
        console.error('获取权限策略失败:', error);
        loading.value = false;
    }
};
const handleEdit = async (row: PolicyUserRange) => {
    let data = row;
    rowData.value = data;
    //console.log("edit_row_data:", rowData.value);
    isEdit.value = true;
    visible.value = true;
};

const addData = async (data) => {
    console.log("add_data:", data);
    let result ={}
      try{
        let req={
            policy_name: data.name,
            policy_info: data.info
        }
        result = await AddPermissPolicyService(req);
        if (result['code'] === 0) {
          ElMessage.success("新增成功");
        } else {
          ElMessage.error("新增失败:"+result['message']);
        }

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

const updateData = async (data) => {

    let result ={}
      try{
        let req={
            token:localStorage.getItem("token"),
            id: data.ID,
        };
        result = await UpdatePermissPolicyService(req);
        if (result['code'] === 0) {
          ElMessage.success("更新成功");
        } else {
          ElMessage.error("更新失败");
        }

      }catch(e){
        console.log(e);
      }
      closeDialog();
};
const handleSearch = async () => {
    // query.name是否是数字
    if (isNaN(Number(query.name))) {
        ElMessage.error('请输入数字');
        return;
    }
    let req={
        token: localStorage.getItem('token'),
        type: "ID",
        id: parseInt(query.name) || 1
    }
    await GetPermissPolicy();
    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: 'range', required: true, opts:user_select_opts.value ,multiple: true},
        { type: 'switch', label: 'Redis权限', prop: 'redis', required: false, activeText: '开启', inactiveText: '关闭' },
        { type: 'switch', label: '运行Shell权限', prop: 'run_shell', required: false, activeText: '开启', inactiveText: '关闭' },
        { type: 'switch', label: '上传权限', prop: 'upload', required: false, activeText: '开启', inactiveText: '关闭' },
        { type: 'switch', label: '设备权限', prop: 'device', required: false, activeText: '开启', inactiveText: '关闭' },
        { type: 'switch', label: '发送邮件权限', prop: 'send_mail', required: false, activeText: '开启', inactiveText: '关闭' },
    ]
})

//编辑弹窗
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: 'range', required: true, opts:user_select_opts.value ,multiple: true},
        { type: 'switch', label: 'Redis权限', prop: 'redis', required: false, activeText: '开启', inactiveText: '关闭' },
        { type: 'switch', label: '运行Shell权限', prop: 'run_shell', required: false, activeText: '开启', inactiveText: '关闭' },
        { type: 'switch', label: '上传权限', prop: 'upload', required: false, activeText: '开启', inactiveText: '关闭' },
        { type: 'switch', label: '设备权限', prop: 'device', required: false, activeText: '开启', inactiveText: '关闭' },
        { type: 'switch', label: '发送邮件权限', prop: 'send_mail', required: false, activeText: '开启', inactiveText: '关闭' },
    ]
})

const handleView =async (row: Function) => {
    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: PermissPolicyResponseData) => {
    let req={
        token: localStorage.getItem('token'),
        id: row.policy.ID,
    }
    try{
        let result = await DelPermissPolicyService(req);
        if(result['code'] === 0){
            ElMessage.success("删除成功");
            GetPermissPolicy();
        }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>