<template>
    <div>
        <!-- 政务端 -->
        <div v-if="checkRole(['common'])">
            <div class="headerbox">
                <el-form size="small" :inline="true" label-width="7rem">
                    <el-row style="margin-top: 1rem;">
                        <el-col :span="6">
                            <el-form-item label="关键要素" style="width: 100%;">
                                <el-input placeholder="请输入关键要素" clearable style="width: 14rem;"
                                    v-model="searchForm.keyElement" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="具体指标" style="width: 100%;">
                                <el-input placeholder="请输入具体指标" clearable style="width: 14rem;"
                                    v-model="searchForm.specificIndicator" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item style="margin-left: 2.5rem;">
                                <el-button type="primary" icon="el-icon-search" size="mini"
                                    @click="fetchElements">查询</el-button>
                                <el-button icon="el-icon-refresh" size="mini" @click="resetSearchForm">重置</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <div class="tablebox" style="margin: .5rem;">
                <el-button type="primary" icon="el-icon-plus"
                    @click="dialogVisible = true; resetForm()">新增要素</el-button>

                <!-- 渲染所有要素 -->
                <div v-for="(element, index) in tableData" :key="index" class="tablebox">
                    <div class="boxheader">
                        <div class="headerone">
                            <div>{{ element.type == 1 ? '关键要素' : '重要要素' }}：</div>
                            <div>{{ element.name }}</div>
                        </div>
                        <div class="headertwo">
                            <el-button type="primary" icon="el-icon-edit" size="mini"
                                @click="handleDeleteElement(element)">删除要素</el-button>
                            <el-button type="primary" icon="el-icon-edit" size="mini"
                                @click="handleUpdate(element)">编辑要素</el-button>
                            <el-button type="primary" icon="el-icon-plus"
                                @click="showAddIndicatorDialog(element)">新增指标</el-button>
                        </div>
                    </div>
                    <el-table :data="element.indicators" style="width: 100%">
                        <el-table-column label="序号" width="180">
                            <template slot-scope="scope">
                                {{ scope.$index + 1 }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="jtzb" label="具体指标" width="180"></el-table-column>
                        <el-table-column prop="xxyq" label="详细要求" width="950"></el-table-column>
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button size="mini" type="text"
                                    @click="handleUpdateIndicator(element, scope.row)">编辑指标</el-button>
                                <el-button size="mini" type="text" @click="handleDelete(element, scope.row)"
                                    style="color: #F25353;">删除指标</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>

            <!-- 新增/编辑要素弹窗 -->
            <el-dialog :title="form.id ? '编辑要素' : '新增要素'" :visible.sync="dialogVisible" width="30%">
                <el-form :model="form" label-width="80px">
                    <el-form-item label="类型">
                        <el-select v-model="form.type" placeholder="请选择类型">
                            <el-option v-for="dict in dict.type.yslx" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="名称">
                        <el-input v-model="form.name" placeholder="请输入名称"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleAddElement">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 新增/编辑指标弹窗 -->
            <el-dialog :title="indicatorForm.id ? '编辑指标' : '新增指标'" :visible.sync="indicatorDialogVisible" width="30%">
                <el-form :model="indicatorForm" label-width="80px">
                    <el-form-item label="具体指标">
                        <el-input v-model="indicatorForm.jtzb" placeholder="请输入具体指标"></el-input>
                    </el-form-item>
                    <el-form-item label="详细要求">
                        <el-input v-model="indicatorForm.xxyq" placeholder="请输入详细要求"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="indicatorDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleAddIndicator">确 定</el-button>
                </span>
            </el-dialog>
        </div>
        <!-- 企业端 -->
        <div v-if="showCompanySection">
            <tianbao />
        </div>
    </div>
</template>

<script>
import { addElement, getAllElements, editElemention, deleteElemention } from '@/api/ManageApi/index';
import { checkPermi, checkRole } from "@/utils/permission";
import tianbao from '@/views/components/tianbao/tianbao.vue'

export default {
    dicts: ['yslx'],
    components: { tianbao },
    data() {
        return {
            searchForm: {
                keyElement: '',
                specificIndicator: ''
            },
            tableData: [],
            dialogVisible: false,
            indicatorDialogVisible: false,
            form: {
                id: null,
                type: '',
                name: '',
            },
            indicatorForm: {
                id: null,
                jtzb: '',
                xxyq: '',
                elementId: null
            },
            currentElement: null
        };
    },
    methods: {
        checkPermi,
        checkRole,

        // 获取用户信息
        getUserInfo() {
            const user = this.$store.state.user || {};
            return {
                name: user.name || 'admin',
                userId: user.userId || 1,
                userName: user.userName || 'admin'
            };
        },

        // 查询要素
        fetchElements() {
            getAllElements(this.searchForm).then(response => {
                this.tableData = response.data.map(item => ({
                    ...item,
                    indicators: item.list || []
                }));
            })
        },

        // 重置查询表单
        resetSearchForm() {
            this.searchForm = {
                keyElement: '',
                specificIndicator: ''
            };
            this.fetchElements();
        },

        // 重置要素表单
        resetForm() {
            this.form = {
                id: null,
                type: '',
                name: ''
            };
        },

        // 重置指标表单
        resetIndicatorForm() {
            this.indicatorForm = {
                id: null,
                jtzb: '',
                xxyq: '',
                elementId: null
            };
        },

        // 新增或编辑要素
        handleAddElement() {
            const user = this.getUserInfo();
            const payload = {
                ...this.form,
                createBy: user.userName,
                createId: user.userId,
                updateBy: user.userName,
                updateId: user.userId
            };

            const api = this.form.id ? editElemention : addElement;
            api(payload).then(response => {
                this.$message.success(this.form.id ? '编辑成功' : '新增成功');
                this.dialogVisible = false;
                this.fetchElements();
            })
        },

        // 编辑要素
        handleUpdate(element) {
            this.currentElement = element;
            this.form = {
                id: element.id,
                type: element.type,
                name: element.name
            };
            this.dialogVisible = true;
        },

        // 删除要素
        handleDeleteElement(element) {
            this.$confirm('确定删除该要素及其所有指标吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteElemention([element.id]).then(() => {
                    this.$message.success('删除成功');
                    this.fetchElements();
                })
            });
        },

        // 显示新增指标弹窗
        showAddIndicatorDialog(element) {
            this.currentElement = element;
            this.resetIndicatorForm();
            this.indicatorForm.elementId = element.id;
            this.indicatorDialogVisible = true;
        },

        // 新增或编辑指标
        handleAddIndicator() {
            const user = this.getUserInfo();
            const payload = {
                ...this.indicatorForm,
                name: this.currentElement.name,
                type: this.currentElement.type,
                createBy: user.userName,
                createId: user.userId,
                updateBy: user.userName,
                updateId: user.userId
            };

            const api = this.indicatorForm.id ? editElemention : addElement;

            api(payload).then(response => {
                this.$message.success(this.indicatorForm.id ? '指标编辑成功' : '指标新增成功');
                this.indicatorDialogVisible = false;
                this.fetchElements();
            }).catch(error => {
                this.$message.error('操作失败: ' + (error.message || '未知错误'));
            });
        },

        // 编辑指标
        handleUpdateIndicator(element, indicator) {
            this.currentElement = element;
            this.indicatorForm = {
                ...indicator,
                elementId: element.id
            };
            this.indicatorDialogVisible = true;
        },


        // 删除指标
        handleDelete(element, indicator) {
            this.$confirm('确定删除该指标吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteElemention([indicator.id]).then(() => {
                    this.$message.success('删除成功');
                    this.fetchElements();
                }).catch(error => {
                    this.$message.error('删除失败: ' + (error.message || error));
                });
            });
        }
    },
    computed: {
        showCompanySection() {
            const isCompany = this.checkRole(['company']);
            const isCommon = this.checkRole(['common']);
            return isCompany && !isCommon;
        }
    },
    mounted() {
        this.fetchElements();
    }
};
</script>

<style scoped>
.headerbox {
    background-color: #fff;
    border-radius: 0.5rem;
    margin: 0.5rem;
    border: 1px solid #eee;
}

.tablebox {
    background-color: #fff;
    border-radius: 0.5rem;
    padding: 1rem;
    margin: 0.5rem;
    border: 1px solid #eee;
}

.boxheader {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: .5rem;
    background-color: #F5F7FE;
}

.headerone {
    color: #000000;
    font-weight: bold;
    display: flex;
}

.headertwo {
    display: flex;
}
</style>