<template>
    <div class="list_container">
        <div class="title_examine">
            <div class="pub_title">组织列表</div>
            <div style="margin-left: auto;">
                <el-input v-model="checkOrg" placeholder="请输入组织" size="normal" clearable @input="changeOrg"
                    style="margin-right: 10px; width: 200px"></el-input>
                <el-select v-model="checkArea" placeholder="选择区域" clearable filterable @change="changeArea"
                    style="margin-right: 10px">
                    <el-option v-for="item in regionCList" :key="item.id" :label="item.name" :value="item.name">
                    </el-option>
                </el-select>
                <el-button type="primary" size="small" @click="add_organ_dialog = true;">新增组织</el-button>
            </div>
        </div>
        <div class="tableBox">
            <el-table :data="organizations" stripe border style="width: 100%" :header-cell-style="headerCellStyle">
                <el-table-column show-overflow-tooltip prop="name" label="组织名称" min-width="45"></el-table-column>
                <el-table-column show-overflow-tooltip prop="code" label="编码" min-width="45">
                    <template slot-scope="scope">
                        {{ scope.row.code || '-' }} <!-- 如果 org 为空，显示 '-' -->
                    </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip prop="detail" label="描述" min-width="45">
                    <template slot-scope="scope">
                        {{ scope.row.detail || '-' }} <!-- 如果 org 为空，显示 '-' -->
                    </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip prop="area" label="区域" min-width="45"></el-table-column>
                <el-table-column show-overflow-tooltip prop="ctime" label="创建时间" min-width="45"></el-table-column>
                <el-table-column label="是否禁用/使用期限" min-width="45">
                    <template #default="scope">
                        <span v-if="scope.row.isLogin === '1'">启用</span>
                        <span v-else-if="scope.row.isLogin === '2'">禁用</span>
                        <span v-else>{{ scope.row.isLogin }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="220px">
                    <template slot-scope="scope">
                        <div class="operate">
                            <button @click="update(scope.row)">编辑</button>
                            <button @click="enable(scope.row)">
                                {{ scope.row.isLogin === '2' ? '启用' : '禁用' }}
                            </button>
                            <button @click="toPage(scope.row)">批量创建</button>
                            <button @click="permissionSetting(scope.row)"
                                v-show="!unShowJurUser.includes(userid)">权限设置</button>
                            <button @click="delete_organ(scope.row)" style="color:red;">删除</button>

                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页组件 -->
        <el-pagination :current-page="currentPage" :page-size="pageSize" :total="total"
            @current-change="handlePageChange" layout="total,prev, pager, next, jumper">
        </el-pagination>
        <!-- 新增组织弹窗 -->
        <el-dialog title="新增组织" class="table" :visible.sync="add_organ_dialog" :before-close="close_add_organ"
            width="700px">
            <div class="el_dialog_org_content">
                <form class="el-form">
                    <!-- 组织名称 -->
                    <div class="el-form-item" style="margin-top: 15px">
                        <label class="el-form-item__label" style="width: 100px">组织名称</label>
                        <div class="el-form-item__content" style="margin-left: 5px">
                            <span>
                                <div class="add_input el-input el-input--suffix">
                                    <input v-model="orgName" type="text" autocomplete="off" placeholder="组织名称"
                                        class="el-input__inner" />
                                </div>
                            </span>
                        </div>
                    </div>
                    <!-- 地区 -->
                    <div class="el-form-item">
                        <label class="el-form-item__label" style="width: 100px">组织编码</label>
                        <div class="el-form-item__content" style="margin-left: 5px">
                            <span>
                                <div class="add_input el-input el-input--suffix">
                                    <input v-model="randomCode" type="text" autocomplete="off" placeholder="请输入随机码"
                                        class="el-input__inner" />
                                </div>
                            </span>
                        </div>
                    </div>
                    <!-- 描述 -->
                    <div class="el-form-item">
                        <label class="el-form-item__label" style="width: 100px">描述</label>
                        <div class="el-form-item__content" style="margin-left: 5px">
                            <span>
                                <div class="add_input el-input el-input--suffix">
                                    <input v-model="orgDetail" type="text" autocomplete="off" placeholder="请输入描述"
                                        class="el-input__inner" />
                                </div>
                            </span>
                        </div>
                    </div>
                    <!-- 区域 -->
                    <div class="el-form-item">
                        <label class="el-form-item__label" style="width: 100px">区域</label>
                        <div class="el-form-item__content" style="margin-left: 5px">
                            <span>
                                <div class="add_input el-input el-input--suffix">

                                    <el-select v-model="regionC" placeholder="请选择区域" class="custom-select" filterable>
                                        <el-option v-for="(org, index) in regionCList" :key="index" :label="org.name"
                                            :value="org.name">
                                            {{ org.name }}
                                        </el-option>
                                    </el-select>

                                </div>
                            </span>
                        </div>
                    </div>
                </form>
            </div>
            <!-- 按钮区域 -->
            <div slot="footer" class="el-dialog__footer" style="margin-top: 88px;">
                <el-button @click="close_add_organ">取 消</el-button>
                <el-button type="primary" @click="ajax_add_org">确认</el-button>
            </div>
        </el-dialog>
        <!-- 修改组织弹窗 -->
        <el-dialog title="修改组织" class="table" :visible.sync="add_organ_dialog2" :before-close="close_add_organ2"
            width="700px">
            <div class="el_dialog_org_content">
                <form class="el-form">
                    <!-- 组织名称 -->
                    <div class="el-form-item" style="margin-top: 15px">
                        <label class="el-form-item__label" style="width: 100px">组织名称</label>
                        <div class="el-form-item__content" style="margin-left: 5px">
                            <span>
                                <div class="add_input el-input el-input--suffix">
                                    <input v-model="orgName" type="text" autocomplete="off" placeholder="组织名称"
                                        class="el-input__inner" />
                                </div>
                            </span>
                        </div>
                    </div>
                    <!-- 地区 -->
                    <div class="el-form-item">
                        <label class="el-form-item__label" style="width: 100px">组织编码</label>
                        <div class="el-form-item__content" style="margin-left: 5px">
                            <span>
                                <div class="add_input el-input el-input--suffix">
                                    <input v-model="randomCode" type="text" autocomplete="off" placeholder="请输入随机码"
                                        class="el-input__inner" />
                                </div>
                            </span>
                        </div>
                    </div>
                     <!-- 描述 -->
                     <div class="el-form-item">
                        <label class="el-form-item__label" style="width: 100px">描述</label>
                        <div class="el-form-item__content" style="margin-left: 5px">
                            <span>
                                <div class="add_input el-input el-input--suffix">
                                    <input v-model="orgDetail" type="text" autocomplete="off" placeholder="请输入描述"
                                        class="el-input__inner" />
                                </div>
                            </span>
                        </div>
                    </div>
                    <!-- 区域 -->
                    <div class="el-form-item">
                        <label class="el-form-item__label" style="width: 100px">区域</label>
                        <div class="el-form-item__content" style="margin-left: 5px">
                            <span>
                                <div class="add_input el-input el-input--suffix">
                                    <el-select v-model="regionC" placeholder="请选择区域" class="custom-select" filterable>
                                        <el-option v-for="(org, index) in regionCList" :key="index" :label="org.name"
                                            :value="org.name">
                                            {{ org.name }}
                                        </el-option>
                                    </el-select>
                                </div>
                            </span>
                        </div>
                    </div>
                </form>
            </div>
            <!-- 按钮区域 -->
            <div slot="footer" class="el-dialog__footer" style="margin-top: 88px;">
                <el-button @click="close_add_organ2">取 消</el-button>
                <el-button type="primary" @click="updateOrgan">确认</el-button>
            </div>
        </el-dialog>
        <!-- 启用弹窗 -->
        <el-dialog title="启用组织" class="table" :visible.sync="enable_organ_dialog" :before-close="close_enable_organ"
            width="700px">
            <div class="el_dialog_org_content">
                <form class="el-form">
                    <!-- 使用期限 -->
                    <div class="el-form-item">
                        <label class="el-form-item__label">使用期限</label>
                        <div class="el-form-item__content">
                            <el-date-picker v-model="useDate" format="yyyy-MM-dd" type="date" value-format="yyyy-MM-dd"
                                placeholder="请选择使用期限" />
                        </div>
                    </div>
                </form>
            </div>
            <!-- 按钮区域 -->
            <div slot="footer" class="dialog-footer">
                <el-button @click="close_enable_organ">取 消</el-button>
                <el-button type="primary" @click="enable_organ">确认</el-button>
            </div>
        </el-dialog>
        <permissionSettingDialog ref="permissionSettingDialogRef" @getData="getOrgan" />
    </div>
</template>
<script>
import { API_CONFIG } from '@/common/apiConfig';
import { addOp } from "@/api/user";
import { mapGetters } from 'vuex';
import permissionSettingDialog from './dialog/permissionSettingDialog'
export default {
    name: 'onList',
    components: {
        permissionSettingDialog
    },
    data() {
        return {
            organizations: [],
            organList: [],
            checkOrg: "",
            checkArea: "",
            currentPage: 1,
            pageSize: 10,
            total: 0,
            add_organ_dialog: false,
            add_organ_dialog2: false,
            enable_organ_dialog: false,
            useDate: "",
            orgName: "",
            randomCode: "",
            orgDetail: "",
            regionC: 'cn',
            uLogin: "1", // 登录状态 (1 或 2)
            radio: "1",
            regionCList: [
                { id: 1, name: 'hk' },
                { id: 2, name: 'cn' }
            ], //区域列表
            form: {
                organ: ""
            },
            organ: {},
            unShowJurUser: ['0abcb118-9110-11eb-80ad-005056b86db5']
        }
    },
    computed: {
        ...mapGetters(['userid']),
    },
    // created() {
    //     this.formatDate();

    // },
    methods: {
        // 表头的背景色
        headerCellStyle() {
            return { backgroundColor: "#f1f1f1" };
        },
        changeOrg() {
            this.currentPage = 1;
            this.getOrgan();
        },
        changeArea() {
            this.currentPage = 1;
            this.getOrgan();
        },
        getOrgan() {
            let params = [
                {
                    functionName: "getOrgan",
                    org: this.checkOrg,
                    area: this.checkArea,
                    page: this.currentPage,
                    num: this.pageSize,
                }
            ];
            this.$ajax
                .post(API_CONFIG.baseUrl, params)
                .then((res) => {
                    // console.log("返回的数据为：", res.data);  // 检查返回的数据
                    if (res.data && Array.isArray(res.data[0])) {
                        // 使用 map() 提取所有组织名称
                        this.organizations = res.data[0]
                        this.total = res.data[0][0].num

                        console.log(this.organizations);

                    }

                })
                .catch((err) => {
                    this.$message.error("查询失败");
                    console.error("请求失败，错误信息：", err);
                });
        },
        ajax_org() {
            const params = [API_CONFIG.ajax_org]; // 使用配置中的接口参数
            this.$ajax
                .post(API_CONFIG.baseUrl, params)
                .then((res) => {
                    // console.log("返回的数据为：", res.data);  // 检查返回的数据
                    if (res.data && Array.isArray(res.data[0])) {
                        // 使用 map() 提取所有组织名称
                        this.organList = res.data[0].map((item) => ({
                            name: item.name,
                            id: item.id,
                        }));
                    }
                    // console.log("返回的结果为：",this.organizations);
                })
                .catch((err) => {
                    this.$message.error("查询失败");
                    console.error("请求失败，错误信息：", err);
                });
        },
        // 页码扩展按钮
        handlePageChange(page) {
            this.currentPage = page;
            this.getOrgan();
        },
        //新增学校关闭
        close_add_organ() {
            this.regionC = 'cn'
            this.add_organ_dialog = false;
        },
        //修改学校关闭
        close_add_organ2() {
            this.orgName = "";
            this.randomCode = "";
            this.orgDetail = "";
            this.regionC = 'cn'
            this.add_organ_dialog2 = false;
        },
        close_enable_organ() {
            this.enable_organ_dialog = false;
        },
        //新增组织
        ajax_add_org() {
            // 获取弹窗中的输入内容
            let orgName = this.orgName; // 组织名称
            let randomCode = this.randomCode || ""; // 随机码（可为空）
            let uLogin = this.radio; // 获取复选框选中的值（1 或 2）

            // 验证组织名称不能为空
            if (!orgName) {
                this.$message.error("组织名称不能为空");
                return;
            }

            // 构造请求参数
            let params = [
                {
                    functionName: API_CONFIG.ajax_add_org.functionName, // 调用存储过程的名称
                    u_name: orgName, // 组织名称
                    u_create: this.userid, // u_create 固定为0
                    u_code: randomCode, // 随机码（可以为空）
                    u_detail: this.orgDetail, // 描述
                    u_regionC: this.regionC,
                    u_login: uLogin, // 登录状态
                },
            ];

            // 发起请求
            this.$ajax
                .post(API_CONFIG.baseUrl, params)
                .then(async (res) => {
                    console.log(res.data);
                    // 检查返回的结果
                    if (res.data && res.data[0] && res.data[0][0]) {
                        if (res.data[0][0].name === 1) {
                            this.$message({
                                type: "error",
                                message: "该组织已存在，请重新选择!",
                            });
                            return;
                        } else {
                            this.$message({
                                type: "success",
                                message: "添加成功!",
                            });
                            await addOp({
                                uid: this.userid,
                                cid: "",
                                type: "user_op",
                                content: `添加了组织 ${orgName}`,
                            });
                        }
                    } else {
                        this.$message.error("插入失败，未返回有效结果");
                    }
                    // 刷新组织列表
                    this.getOrgan();
                    //关闭弹窗
                    this.add_organ_dialog = false;
                    // 清空输入框、下拉菜单选择和单选框
                    this.orgName = ""; // 清空学校名称
                    this.orgDetail = ""; // 清空学校描述
                    this.regionC = 'cn'
                    this.randomCode = ""; // 清空地区选择
                    this.uLogin = "1"; // 清空学校类型选择
                })
                .catch((err) => {
                    this.$message.error("插入失败");
                    console.error("请求失败，错误信息：", err);
                });
        },

        update(row) {
            this.add_organ_dialog2 = true;
            this.nid = row.id;
            this.orgName = row.name;
            this.randomCode = row.code;
            this.regionC = row.area;
            this.orgDetail = row.detail;
            console.log(row);
        },
        updateOrgan() {
            let params = [
                {
                    functionName: "updateOrgan2",
                    id: this.nid,
                    name: this.orgName,
                    code: this.randomCode,
                    detail: this.orgDetail,
                    area: this.regionC
                }
            ];
            this.$ajax
                .post(API_CONFIG.baseUrl, params)
                .then(async (res) => {
                    console.log("👉", res.data);
                    this.add_organ_dialog2 = false;
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.getOrgan();
                    await addOp({
                        uid: this.userid,
                        cid: "",
                        type: "user_op",
                        content: `修改了组织 ${this.orgName} ${this.nid}`,
                    });
                })
                .catch((err) => {
                    this.$message.error("修改失败");
                    console.log(err);
                });
        },
        formatDate() {
            // 使用示例
            const today = new Date(); // 获取当前日期
            const year = today.getFullYear(); // 获取年份
            const month = String(today.getMonth() + 1).padStart(2, '0'); // 获取月份，注意月份从0开始，所以要加1，并确保是两位数
            const day = String(today.getDate()).padStart(2, '0'); // 获取日期，并确保是两位数

            this.useDate = `${year}-${month}-${day}`; // 返回格式化后的日期字符串
        },
        enable(row) {
            if (row.isLogin === '2') {
                this.enable_organ_dialog = true;
                this.nid = row.id;
            }
            else {
                this.disableOrgan(row);
            }


        },
        enable_organ() {
            let params = [
                {
                    functionName: "enableOrgan",
                    id: this.nid,
                    date: this.useDate
                }
            ];
            this.$ajax
                .post(API_CONFIG.baseUrl, params)
                .then(async (res) => {
                    console.log("👉", res.data);
                    this.enable_organ_dialog = false;
                    this.useDate = "";
                    this.$message({
                        message: '启用成功',
                        type: 'success'
                    });
                    // this.formatDate();
                    this.getOrgan();
                    await addOp({
                        uid: this.userid,
                        cid: "",
                        type: "user_op",
                        content: `启用了组织 ${this.orgName} ${this.nid}`,
                    });
                })
                .catch((err) => {
                    this.$message.error("启用失败");
                    console.log(err);
                });
        },
        disableOrgan(row) {
            this.nid = row.id;
            let params = [
                {
                    functionName: "disableOrgan",
                    id: this.nid
                }
            ];
            this.$confirm("确定禁用此组织记录吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.$ajax
                        .post(API_CONFIG.baseUrl, params)
                        .then(async (res) => {
                            console.log("👉", res.data);
                            this.$message({
                                message: '禁用成功',
                                type: 'success'
                            });
                            this.getOrgan();
                            await addOp({
                                uid: this.userid,
                                cid: "",
                                type: "user_op",
                                content: `禁用了组织 ${row.name} ${row.id}`,
                            });
                        })
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        delete_organ(row) {
            this.nid = row.id;

            let params = [
                {
                    functionName: "deleteOrgan",
                    id: this.nid
                }
            ];
            this.$confirm("确定删除此组织记录吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.$ajax
                        .post(API_CONFIG.baseUrl, params)
                        .then(async (res) => {
                            console.log("👉", res.data);
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getOrgan();
                            await addOp({
                                uid: this.userid,
                                cid: "",
                                type: "user_op",
                                content: `删除了组织 ${row.name} ${row.id}`,
                            });
                        })
                })
                .catch((err) => {
                    this.$message.error("删除失败");
                    console.log(err);
                });
        },
        async getUserId(oid, org) {
            let params = [
                {
                    functionName: "select_Suffix", // 调用存储过程的名称
                    org: org, //组织id
                    oid: oid, //学校id
                },
            ];

            try {
                const res = await this.$ajax.post(API_CONFIG.baseUrl, params);
                console.log('getSuffix', res);
                let data = res.data[0];
                let orgData = res.data[1];
                let ap = data.length > 0 ? data[0].userid : orgData.length > 0 ? orgData[0].userid : "";
                return ap
            } catch (err) {
                console.error("请求失败，错误信息：", err);
            }
        },
        async toPage(row) {
            const oid = "";
            const org = row.id;
            await addOp({
                uid: this.userid,
                cid: "",
                type: "user_op",
                content: `点击了批量添加 ${row.name}${row.id}`,
            });
            let userid = await this.getUserId(oid, org);
            const url = `https://beta.pbl.cocorobo.cn/pbl-teacher-table/dist/?#/teacher?userid=${userid ? userid : this.userid}&oid=${oid}&org=${org}`;
            window.open(url, '_blank');
        },
        permissionSetting(data) {
            this.$refs.permissionSettingDialogRef.open(data, "org");
        }


    },
    mounted() {
        this.getOrgan();
        this.ajax_org();
    }
}
</script>
<style scoped>
.list_container {
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
    overflow: auto;
}

.tableBox {
    margin: 10px 0;
}

.operate {
    display: flex;
    gap: 3px;
}

/* 新增组织的内容容器 */
.el_dialog_org_content {
    color: #606266;
    font-size: 14px;
    height: 120px;
}

.el-form-item {
    margin-bottom: 22px;
    display: flex;
    align-items: center;
    /* border: 1px solid black; */
}

.el-form-item__label {
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    margin-left: 20px;
    width: 70px;
}

.el-form-item__content {
    line-height: 40px;
    position: relative;
    font-size: 14px;
}

.table>>>.el-dialog__header {
    padding: 15px 20px;
    background: #454545;
}

.table>>>.el-dialog__title {
    color: #fff;
}

.operate button {
    background: none;
    border: none;
    cursor: pointer;
    color: #308fff;
}
</style>