<template>
    <div class="container" v-loading="loading">
        <header class="mb-20">
            <div class="flex between">
                <div>
                    <el-button type="primary" @click="handleAdd">
                        <template #icon>
                            <icon name="el-icon-Plus" />
                        </template>
                        新增</el-button
                    >
                </div>
                <div style="width: 50%">
                    <el-row>

                    </el-row>
                </div>
            </div>
            <div class="flex between mt-10 v-center">
                <div>
                    <div><span class="text-primary">个人极端暴力风险指数</span> =（基础因素得分百分比 × 15%）＋（诱发因素得分百分比 × 30%）＋（行为因素得分百分比 × 45%）＋（管控因素得分百分比 × 10%）</div>
                </div>
                <a
                    class="flex v-center gap file-link"
                    :href="`${BASE_PATH}/templates/【工作机制】个人极端暴力风险数字督察灵敏感知体系风险赋分及预警处置机制.doc`"
                    target="__blank"
                >
                    <icon name="local-icon-pdf" :size="38" />
                    <span>个人极端风险赋分规则.pdf</span>
                </a>
            </div>
        </header>
        <div class="table-container">
            <el-table ref="tableRef" :default-expand-all="false" :data="scoreRules" :expand-row-keys="[]" :tree-props="{children: 'children',hasChildren: 'hasChildren'}" row-key="id">
                <el-table-column
                    label="问题条目"
                    prop="riskName"
                    show-overflow-tooltip
                    width="180"
                />
                <el-table-column label="因素分值" prop="score" width="200" align="center">
                </el-table-column>
                <el-table-column
                    label="赋分规则"
                    prop="ruleDesc"
                    show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                    label="因素权重"
                    prop="weight"
                    width="100"
                    align="center"
                />
                <el-table-column
                    label="开启状态"
                    width="100"
                >
                    <template #default="{ row }">
                        <el-tag type="success" v-if="row.status === true"
                            >开启</el-tag
                        >
                        <el-tag type="danger" v-if="row.status === false"
                            >关闭</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column label="最后更新时间" prop="updateTime" width="180" />
                <el-table-column label="操作" width="160">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)"
                            >编辑</el-button
                        >
                        <el-button type="danger" link @click="handleDelete(row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>

    <el-dialog
        v-model="show"
        :title="mode === 'add' ? '新增赋分规则' : '编辑赋分规则'"
        width="600"
    >
        <el-form label-width="120" ref="formRef" :model="formData">
            <el-form-item
                label="父级节点"
                :rules="{
                    required: true,
                    message: '请选择父级节点',
                }"
                prop="pid"
            >
                <el-tree-select
                    class="flex-1"
                    v-model="formData.pid"
                    :data="treeOptions"
                    clearable
                    node-key="id"
                    :props="{
                        label: 'riskName',
                    }"
                    :default-expanded-keys="[MENU_ROOT_ID]"
                    placeholder="请选择父级节点"
                    check-strictly
                    filterable
                />
            </el-form-item>
            <el-form-item
                label="风险因素"
                prop="riskName"
                :rules="{
                    required: true,
                    message: '请输入风险因素',
                }"
            >
                <el-input
                    v-model="formData.riskName"
                    placeholder="请输入"
                    clearable
                />
            </el-form-item>
            <el-form-item label="因素分值" prop="score">
                <el-input
                    v-model="formData.score"
                    placeholder="请输入序号"
                    type="number"
                    clearable
                />
            </el-form-item>
            <el-form-item label="赋分规则" prop="ruleDesc">
                <el-input
                    v-model="formData.ruleDesc"
                    placeholder="请输入序号"
                    type="textarea"
                    clearable
                />
            </el-form-item>
            <el-form-item label="因素权重" prop="weight">
                <el-input
                    v-model="formData.weight"
                    placeholder="请输入序号"
                    type="number"
                    clearable
                />
            </el-form-item>
            <el-form-item label="序号" prop="sort">
                <el-input
                    v-model="formData.sortId"
                    placeholder="请输入序号"
                    type="number"
                    clearable
                />
            </el-form-item>
            <el-form-item
                label="状态"
                prop="status"
            >
                <el-switch
                    v-model="formData.status"
                    inline-prompt
                    active-text="开启"
                    inactive-text="关闭"
                    :active-value="true"
                    :inactive-value="false"
                />
            </el-form-item>
        </el-form>
        <footer class="flex end">
            <el-button @click="show = false">取消</el-button>
            <el-button type="primary" @click="submit">确定</el-button>
        </footer>
    </el-dialog>
</template>
<script lang="ts" setup>
import { BASE_PATH } from "@/api/request";
import { calculateScore } from "@/api/work/negative";
import { MENU_ROOT_ID } from "@/enums/appEnums";
import {
    listRiskScoreRuleTree,
    addRiskScoreRule,
    updateRiskScoreRule,
    delRiskScoreRule
} from "@/api/sensitivePerception/riskScoreRule";
import feedback from "@/utils/feedback";

const scoreRules = ref([]);
const treeOptions = ref([
    {
        id: MENU_ROOT_ID,
        riskName: "顶级",
        children: [],
    },
]);

function getList() {
    listRiskScoreRuleTree().then((data) => {
        scoreRules.value = data;
        treeOptions.value[0].children = data;
    });
}

onMounted(() => {
  getList();
})


const show = ref(false);
const formData = ref({
    status: 0
});
const formRef = ref();

const mode = ref<string>("add");
watch(mode, (val) => {
    if (val === "add") {
        formData.value = {};
        formRef.value.resetFields();
    }
});
async function submit() {
    await formRef.value.validate();
    if (mode.value === "add") {
        await addRiskScoreRule(formData.value);
        const parentCode = formData.value.parentCode;
        formData.value = {};
        formRef.value.resetFields();
        formData.value.parentCode = parentCode;
    } else {
        await updateRiskScoreRule(formData.value);
    }
    show.value = false;
    getList();
}

function handleAdd() {
    show.value = true;
    mode.value = "add";
}

function handleEdit(row) {
    show.value = true;
    mode.value = "edit";
    formData.value = {...row};
}

const handleDelete = async (row) => {
    await feedback.confirm(`确定要删除 "${row.name}"？`);
    await delRiskScoreRule(row.id);
    getList();
    feedback.msgSuccess("删除成功");
};

function getScoreRange(row) {
    const sorceSet = new Set();
    row.children.forEach((item) => {
        if (item.score) {
            sorceSet.add(item.score);
        }
        item.children.forEach((j) => {
            if (j.score) {
                sorceSet.add(j.score);
            }
        });
    });
    if (sorceSet.size === 0) {
        return ''
    }
    if (sorceSet.size === 1) {
        return sorceSet.values().next().value
    }
    const min = Math.min(...sorceSet);
    const max = Math.max(...sorceSet);
    return `${min}-${max}`
}

const loading = ref(false)
async function handleCalculate() {
    await feedback.confirm("确定要重新计算风险指数？");
    loading.value = true
    await calculateScore()
    feedback.msgSuccess("风险指数计算完成");
    loading.value = false
}
</script>
<style lang="scss" scoped>
.file-link {
    font-size: 16px;
    text-decoration: none;
    color: #19257d;
    padding: 0 8px;
    border-radius: 8px;
    &:hover {
        background-color: #eee;
    }
}
</style>
