<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.name" />
                            </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.jtzb" />
                            </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" 
                                    @click="fetchElements">查询</el-button>
                                <el-button icon="el-icon-refresh"  @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-if="tableData.length > 0" class="tablebox" style="margin: .5rem;">
                    <div v-for="(element, elementIndex) in tableData" :key="elementIndex" 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-delete" 
                                    @click="handleDeleteElement(element, elementIndex)">删除要素</el-button>
                                <el-button type="primary" icon="el-icon-edit" 
                                    @click="handleUpdate(element)">编辑要素</el-button>
                                <el-button type="primary" icon="el-icon-plus"
                                    @click="showAddIndicatorDialog(element)">新增指标</el-button>
                            </div>
                        </div>
                        <el-table :data="element.list" style="width: 100%" border>
                            <el-table-column label="序号" width="80" align="center">
                                <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="详细要求" min-width="300"></el-table-column>
                            <el-table-column label="操作" width="180" align="center">
                                <template slot-scope="scope">
                                    <el-button  type="text"
                                        @click="handleUpdateIndicator(element, scope.row)">编辑</el-button>
                                    <el-button  type="text" style="color: #F56C6C;"
                                        @click="handleDeleteIndicator(element, scope.row, elementIndex, scope.$index)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
                <div v-else style="text-align: center; margin: 1rem;">暂无数据</div>
            </div>

            <!-- 要素新增对话框 -->
            <el-dialog title="新增要素" :visible.sync="dialogVisible" width="500px">
                <el-form :model="form" :rules="formRules" ref="elementForm" label-width="80px">
                    <el-form-item label="要素类型" prop="type">
                        <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
                            <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="要素名称" prop="name">
                        <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="submitElementForm">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 编辑要素对话框 -->
            <el-dialog title="编辑要素" :visible.sync="editDialogVisible" width="500px">
                <el-form :model="editForm" :rules="formRules" ref="editElementForm" label-width="80px">
                    <el-form-item label="要素类型" prop="type">
                        <el-select v-model="editForm.type" placeholder="请选择类型" style="width: 100%">
                            <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="要素名称" prop="name">
                        <el-input v-model="editForm.name" placeholder="请输入要素名称"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitEditElementForm">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 指标编辑/新增对话框 -->
            <el-dialog :title="indicatorForm.id ? '编辑指标' : '新增指标'" :visible.sync="indicatorDialogVisible" width="500px">
                <el-form :model="indicatorForm" :rules="indicatorRules" ref="indicatorForm" label-width="80px">
                    <el-form-item label="具体指标" prop="jtzb">
                        <el-input v-model="indicatorForm.jtzb" placeholder="请输入具体指标"></el-input>
                    </el-form-item>
                    <el-form-item label="详细要求" prop="xxyq">
                        <el-input type="textarea" :rows="3" 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="submitIndicatorForm">确 定</el-button>
                </span>
            </el-dialog>
        </div>

        <!-- 企业端 -->
        <div v-if="showCompanySection">
            <tianbao />
        </div>
    </div>
</template>

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

export default {
    name: 'ElementManagement',
    dicts: ['yslx'],
    components: { tianbao },
    data() {
        return {
            // 搜索表单
            searchForm: {
                name: '',
                jtzb: ''
            },

            // 表格数据
            tableData: [],

            // 对话框控制
            dialogVisible: false,
            editDialogVisible: false,
            indicatorDialogVisible: false,

            // 新增表单数据
            form: {
                type: '',
                name: ''
            },

            // 编辑表单数据
            editForm: {
                id: 0,
                type: '',
                name: '',
                oldName: '',
                oldType: ''
            },

            // 指标表单数据
            indicatorForm: {
                id: 0,
                jtzb: '',
                xxyq: '',
                elementId: 0
            },

            // 当前操作的要素
            currentElement: null,
            currentElementIndex: -1,

            // 验证规则
            formRules: {
                type: [{ required: true, message: '请选择要素类型', trigger: 'change' }],
                name: [{ required: true, message: '请输入要素名称', trigger: 'blur' }]
            },

            indicatorRules: {
                jtzb: [{ required: true, message: '请输入具体指标', trigger: 'blur' }],
                xxyq: [{ required: true, message: '请输入详细要求', trigger: 'blur' }]
            },

            // 接口版本控制
            useNewApi: true
        };
    },
    computed: {
        showCompanySection() {
            const isCompany = this.checkRole(['company']);
            const isCommon = this.checkRole(['common']);
            return isCompany && !isCommon;
        }
    },
    created() {
        this.fetchElements();
    },
    methods: {
        checkPermi,
        checkRole,

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

        // 获取要素列表
        fetchElements() {
            const params = {
                name: this.searchForm.name,
                jtzb: this.searchForm.jtzb
            };

            getAllElements(params).then(response => {
                if (response.code === 200) {
                    this.tableData = response.data.map(item => ({
                        ...item,
                        list: item.list || []
                    }));
                } else {
                    this.$message.error(response.msg || '获取数据失败');
                }
            }).catch(error => {
                this.$message.error('获取数据失败: ' + (error.message || '未知错误'));
            });
        },

        // 重置搜索表单
        resetSearchForm() {
            this.searchForm = {
                name: '',
                jtzb: ''
            };
            this.fetchElements();
        },

        // 重置新增要素表单
        resetForm() {
            this.form = {
                type: '',
                name: ''
            };
            this.$nextTick(() => {
                if (this.$refs.elementForm) {
                    this.$refs.elementForm.clearValidate();
                }
            });
        },

        // 重置指标表单
        resetIndicatorForm() {
            this.indicatorForm = {
                id: 0,
                jtzb: '',
                xxyq: '',
                elementId: 0
            };
            this.$nextTick(() => {
                if (this.$refs.indicatorForm) {
                    this.$refs.indicatorForm.clearValidate();
                }
            });
        },

        // 提交新增要素表单
        submitElementForm() {
            this.$refs.elementForm.validate(valid => {
                if (valid) {
                    this.handleAddElement();
                }
            });
        },

        // 提交编辑要素表单
        submitEditElementForm() {
            this.$refs.editElementForm.validate(valid => {
                if (valid) {
                    this.handleEditElement();
                }
            });
        },

        // 提交指标表单
        submitIndicatorForm() {
            this.$refs.indicatorForm.validate(valid => {
                if (valid) {
                    if (this.indicatorForm.id) {
                        this.handleEditIndicator();
                    } else {
                        this.handleAddIndicator();
                    }
                }
            });
        },

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

            addElement(payload).then(response => {
                if (response.code === 200) {
                    this.$message.success('新增成功');
                    this.dialogVisible = false;
                    this.fetchElements();
                } else {
                    this.$message.error(response.msg || '新增失败');
                }
            }).catch(error => {
                this.$message.error('新增失败: ' + (error.message || '未知错误'));
            });
        },

        // 编辑要素
        handleEditElement() {
            const payload = {
                newName: this.editForm.name,
                newType: this.editForm.type,
                oldName: this.editForm.oldName,
                oldType: this.editForm.oldType
            };

            updateYsElement(payload).then(response => {
                if (response.code === 200) {
                    this.$message.success('编辑成功');
                    this.editDialogVisible = false;
                    this.fetchElements();
                } else {
                    this.$message.error(response.msg || '编辑失败');
                }
            }).catch(error => {
                this.$message.error('编辑失败: ' + (error.message || '未知错误'));
            });
        },

        // 准备编辑要素
        handleUpdate(element) {
            this.currentElement = element;
            this.editForm = {
                id: element.id,
                type: element.type.toString(),
                name: element.name,
                oldName: element.name,
                oldType: element.type.toString()
            };
            this.editDialogVisible = true;
        },

        // 删除要素
        handleDeleteElement(element, elementIndex) {
            this.$confirm(`确定删除要素"${element.name}"吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const deletePromise = this.useNewApi
                    ? deleteYsElement({ name: element.name, lx: element.type })
                    : deleteElemention([element.id]);

                deletePromise.then(response => {
                    if (response.code === 200) {
                        this.$message.success('删除成功');
                        this.tableData.splice(elementIndex, 1);
                    } else {
                        this.$message.error(response.msg || '删除失败');
                    }
                }).catch(error => {
                    this.$message.error('删除失败: ' + (error.message || '未知错误'));
                });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },

        // 显示新增指标对话框
        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
            };

            addElement(payload).then(response => {
                if (response.code === 200) {
                    this.$message.success('新增成功');
                    this.indicatorDialogVisible = false;
                    this.fetchElements();
                } else {
                    this.$message.error(response.msg || '新增失败');
                }
            }).catch(error => {
                this.$message.error('新增失败: ' + (error.message || '未知错误'));
            });
        },

        // 编辑指标
        handleEditIndicator() {
            const user = this.getUserInfo();
            const payload = {
                ...this.indicatorForm,
                name: this.currentElement.name,
                type: this.currentElement.type,
                updateBy: user.userName,
                updateId: user.userId
            };

            editElemention(payload).then(response => {
                if (response.code === 200) {
                    this.$message.success('编辑成功');
                    this.indicatorDialogVisible = false;
                    this.fetchElements();
                } else {
                    this.$message.error(response.msg || '编辑失败');
                }
            }).catch(error => {
                this.$message.error('编辑失败: ' + (error.message || '未知错误'));
            });
        },

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

        // 删除指标
        handleDeleteIndicator(element, indicator, elementIndex, indicatorIndex) {
            this.$confirm('确定删除该指标吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteElemention([indicator.id]).then(response => {
                    if (response.code === 200) {
                        this.$message.success('删除成功');
                        this.tableData[elementIndex].list.splice(indicatorIndex, 1);
                    } else {
                        this.$message.error(response.msg || '删除失败');
                    }
                }).catch(error => {
                    this.$message.error('删除失败: ' + (error.message || '未知错误'));
                });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        }
    }
};
</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>