<template>
    <lay-container fluid="true" class="organization-box">
        <div style="display: flex">
            <div :style="{ width: isFold ? `0px` : `300px` }" class="left-tree">
                <!-- tree -->
                <div v-show="!isFold">
                    科室列表
                </div>
                <lay-tree v-show="!isFold" style="margin-top: 10px" :data="data" v-model:selectedKey="leftId"
                    :showLine="false" @node-click="handleClick">
                    <template #title="{ data }">
                        <span :class="leftId == data.id ? 'isChecked' : ''">
                            {{ data.name }}
                        </span>
                    </template>
                </lay-tree>
                <div class="isFold" @click="isFold = !isFold">
                    &nbsp;<lay-icon v-if="!isFold" class="layui-icon-left"></lay-icon>
                    <lay-icon v-else class="layui-icon-right"></lay-icon>
                </div>
            </div>
            <div style="flex: 1; padding: 10px;">
                <div style="padding: 10px">
                    <span style="font-size: 18px;vertical-align: center;margin-right: 20px">考评级别设置</span>
                    <lay-button  type="primary" @click="openNew()" size="sm">新增</lay-button>
                </div>
                <lay-table :page="page" :height="'100%'" :columns="columns" :loading="loading" :data-source="dataSource"
                    v-model:selected-keys="selectedKeys" @change="change" @sortChange="sortChange">
                    <template #status="{ row }">
                        <lay-switch :model-value="row.status" @change="changeStatus($event, row)"></lay-switch>
                    </template>
                    <template #role="{ row }">
                        <lay-tag color="#165DFF" variant="light">{{ row.role }}</lay-tag>
                    </template>
                    <template v-slot:operator="{ row }">
                        <lay-space size="lg">
                            <span style="color: #00A394;cursor: pointer"  @click="changeVisible11('编辑', row)">编辑</span>
                            <lay-popconfirm trigger="click" content="确定要删除吗？"  @confirm="confirm(row.id)" @cancel="cancel">
                                <span style="color: #00A394;cursor: pointer">删除</span>
                            </lay-popconfirm>
                        </lay-space>
                    </template>
                </lay-table>
            </div>
        </div>
        <lay-layer v-model="visible11" :type="4" :title="title" :area="['700px', '100%']">
            <div style="padding: 20px">
                <lay-form :model="model11" ref="layFormRef11" required>
                    <lay-form-item label="所属科室" prop="department">
                        <lay-input v-model="model11.department" disabled></lay-input>
                    </lay-form-item>
                    <lay-form-item label="级别名称" prop="levelName">
                        <lay-input v-model="model11.levelName" placeholder="请输入级别名称"></lay-input>
                    </lay-form-item>
                    <lay-form-item label="名额" prop="quota">
                        <lay-input-number v-model="model11.quota" :min="0"></lay-input-number>
                    </lay-form-item>
                    <lay-form-item label="最高评分" prop="maxScore">
                        <lay-input-number v-model="model11.maxScore" :min="0" :max="100"></lay-input-number>
                    </lay-form-item>
                    <lay-form-item label="最低评分" prop="minScore">
                        <lay-input-number v-model="model11.minScore" :min="0" :max="100"></lay-input-number>
                    </lay-form-item>
                </lay-form>
                <div style="width: 100%; text-align: center">
                    <lay-button size="sm" type="primary" @click="toSubmit">保存</lay-button>
                    <lay-button size="sm" @click="toCancel">取消</lay-button>
                </div>
            </div>
        </lay-layer>
    </lay-container>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { layer } from '@layui/layui-vue'
import { getUserGroupNew, getEvaluationlevelData, getEvaluationlevelCreate, getEvaluationlevelUpdate, getEvaluationlevelDelete } from '@/api/module/home';

onMounted(() => {
    getLeftList();

})

const leftId = ref(0);
const data = ref()
const getLeftList = () => {
    getUserGroupNew({}).then((res) => {
        console.log(res)
        if (res.code == 1) {
            data.value = res.data;
            leftId.value = res.data[0].id;
            if (res.data && res.data.length > 0) {
                selectedNode.value = {
                    id: res.data[0].id,
                    name: res.data[0].name
                };
            }
            change(page)
        } else {
            layer.msg(res.msg, { icon: 2 })
        }
    })
}
const selectedNode = ref({
    id: 0,
    name: ''
})
const isFold = ref(false)

function handleClick(node: any) {
    selectedNode.value = JSON.parse(JSON.stringify(node))
    leftId.value = selectedNode.value.id
    page.current = 1
    change(page)
}

const loading = ref(false)
const selectedKeys = ref()
const page = reactive({ current: 1, limit: 10, total: 100 })
const columns = ref([
    { title: '所属科室', width: '120px', key: 'department', align: 'center' },
    { title: '级别名称', width: '120px', key: 'levelName', align: 'center' },
    { title: '名额', width: '80px', key: 'quota', align: 'center' },
    { title: '最高评分', width: '100px', key: 'maxScore', align: 'center' },
    { title: '最低评分', width: '100px', key: 'minScore', align: 'center' },
    {
        title: '操作',
        width: '150px',
        customSlot: 'operator',
        key: 'operator',
        fixed: 'right',
        align: 'center'
    }
])
const change = (page: any) => {
    loading.value = true

    // 准备请求参数
    const params = {
        page: page.current,
        limit: page.limit,
        group_id: leftId.value
    };

    // 调用API获取数据
    getEvaluationlevelData(params).then(res => {
        if (res.code === 1) {
            // 映射API返回数据到组件所需格式
            dataSource.value = res.data.data.map((item: any) => ({
                id: item.id,
                department: selectedNode.value.name || '',
                levelName: item.level,
                quota: Number(item.minge),
                maxScore: Number(item.highest_score),
                minScore: Number(item.lowest_score),
                status: true // 假设默认状态为true，实际应根据API返回值调整
            }));
            page.total = res.data.count || 0;
        } else {
            layer.msg(res.msg || '获取数据失败', { icon: 2 });
            dataSource.value = [];
        }
        loading.value = false;
    }).catch(() => {
        loading.value = false;
        dataSource.value = [];
    });
}
const sortChange = (key: any, sort: number) => {
    layer.msg(`字段${key} - 排序${sort}, 你可以利用 sort-change 实现服务端排序`)
}
const dataSource = ref([])
const changeStatus = (isChecked: boolean, row: any) => {
    dataSource.value.forEach((item) => {
        if (item.id === row.id) {
            layer.msg('Success', { icon: 1 }, () => {
                item.status = isChecked
            })
        }
    })
}
const model11 = ref({
    department: '',
    levelName: '',
    quota: 0,
    maxScore: 0,
    minScore: 0,
    status: true
})
const layFormRef11 = ref()
const visible11 = ref(false)
const title = ref('新增')
const changeVisible11 = (text: any, row: any) => {
    title.value = text
    if (row != null) {
        let info = JSON.parse(JSON.stringify(row))
        model11.value = info
    } else {
        model11.value = {
            department: '',
            levelName: '',
            quota: 0,
            maxScore: 0,
            minScore: 0,
            status: true
        }
    }
    visible11.value = !visible11.value
}

function toSubmit() {
    layFormRef11.value.validate((isValidate: boolean, model: any) => {
        if (!isValidate) {
            return;
        }

        // 准备提交的数据，根据数据库字段进行映射
        const submitData = {
            id: model11.value.id || '',
            group_id: leftId.value,
            level: model11.value.levelName,
            minge: model11.value.quota,
            highest_score: model11.value.maxScore,
            lowest_score: model11.value.minScore
        };

        // 根据操作类型调用不同API
        const apiFunction = title.value === '新增'
            ? getEvaluationlevelCreate
            : getEvaluationlevelUpdate;

        apiFunction(submitData).then(res => {
            if (res.code === 1) {
                layer.msg('保存成功！', { icon: 1, time: 1000 });
                visible11.value = false;
                // 刷新数据
                change(page);
            } else {
                layer.msg(res.msg || '操作失败', { icon: 2 });
            }
        });
    });
}
function toCancel() {
    visible11.value = false
    visible22.value = false
}
function confirm(id) {
    // 获取当前选中行的ID
    getEvaluationlevelDelete({ id }).then(res => {
        if (res.code === 1) {
            layer.msg('您已成功删除', { icon: 1 });
            // 刷新数据
            change(page);
        } else {
            layer.msg(res.msg || '删除失败', { icon: 2 });
        }
    });
}
function cancel() {
    layer.msg('您已取消操作')
}

const model22 = ref({
    organization: '',
    name: '',
    fullName: '',
    code: '',
    type: '',
    sort: 0,
    remark: ''
})
const layFormRef22 = ref()
const visible22 = ref(false)
const title22 = ref('新建')

const openNew = () => {
    model11.value = {
        department: selectedNode.value.name || data.value?.[0]?.name || '',
        levelName: '',
        quota: 0,
        maxScore: 0,
        minScore: 0,
        status: true
    }
    title.value = '新增'
    visible11.value = true
}
</script>

<style scoped>
.organization-box {
    width: calc(100vw - 240px);
    height: calc(100vh - 110px);
    margin-top: 10px;
    box-sizing: border-box;
    background-color: #fff;
    overflow: hidden;
}

.left-tree {
    display: inline-block;
    padding: 20px 15px 0 5px;
    height: 1200px;
    border-right: 1px solid #e6e6e6;
    box-sizing: border-box;
    position: relative;
}

/* todo layui-tree-entry 设置无效 */
.layui-tree-entry {
    position: relative;
    padding: 10px 0;
    height: 20px;
    line-height: 20px;
    white-space: nowrap;
}

.isFold {
    position: absolute;
    top: 36%;
    right: -10px;
    width: 26px;
    height: 26px;
    line-height: 26px;
    border-radius: 13px;
    background-color: #fff;
    border: 1px solid #e6e6e6;
    cursor: pointer;
}

.search-input {
    display: inline-block;
    width: 98%;
    margin-right: 10px;
}

.isChecked {
    display: inline-block;
    background-color: #e8f1ff;
    color: red;
}
</style>
