import { listBroadcast, getAddBroadcast, updateBroadcast, DeleteBroadcast, getBroadcast, dataInfo } from '../../api/broadcast'
import { isValidPath, getPathSuggestions } from '../../utils/routeUtils'

export default {
    data() {
        return {
            tableData: [
                // {
                //     id: 1,
                //     createTime: "2025-06-24 10:00:00",
                //     content: "内isjisjfidjfjfjffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff容",
                //     createUser: "创建人",
                //     updateTime: "2025-06-24 10:00:00",
                //     updateUser: "修改人",
                // },
                // {
                //     id: 2,
                //     createTime: "2025-06-24 10:00:00",
                //     content: "内容",
                //     createUser: "创建人",
                //     updateTime: "2025-06-24 10:00:00",
                //     updateUser: "修改人",
                // },
            ],
            listParams: {
                pageNum: 1,
                pageSize: 50
            },
            addParams: {
                content: "",
                buttonContent: "",
                buttonPath: "",
            },
            editParams: {
                content: "",
                id: "",
                buttonContent: "",
                buttonPath: "",
            },
            dialogVisible: false,
            bthLoading: false,
            broadcastLoading: false,
            editDialogVisible: false,
            editLoading: false,
            byteCount: "",
            isOverLimit: false,
            total: 0,
            pageSizes: [50, 100, 300],
            currentPage: 1,

        }
    },
    mounted() {


        let token
        try {
            token = JSON.parse(localStorage.getItem('token'))
        } catch (e) {
            console.log(e);
        }
        if (token) {
            this.fetchList(this.listParams);
        }

    },
    methods: {
        async fetchList(params) {

            this.setLoading('broadcastLoading', true);
            const res = await listBroadcast(params)
            if (res.code === 200) {
                this.tableData = res.rows
                this.total = res.total
            }
            this.setLoading('broadcastLoading', false);
        },
        async addBroadcast(params) {
            this.setLoading('bthLoading', true);

            // 发送请求前打印参数，用于调试
            console.log('发送广播请求的参数:', params);

            const res = await getAddBroadcast(params)
            if (res.code === 200) {
                this.$message.success(this.$t("backendSystem.addSuccess"))
                this.dialogVisible = false;
                // 清空表单参数
                this.addParams.content = ""
                this.addParams.buttonContent = ""
                this.addParams.buttonPath = ""
                this.fetchList(this.listParams);
            }
            this.setLoading('bthLoading', false);
        },
        async getBroadcast(params) {
            this.setLoading('editLoading', true);
            const res = await dataInfo(params)
            if (res.code === 200) {
                this.editParams = {
                    ...res.data,
                    // 确保按钮路径是字符串格式（如果是数组则转换为逗号分隔的字符串）
                    buttonPath: Array.isArray(res.data.buttonPath)
                        ? res.data.buttonPath.join(',')
                        : (res.data.buttonPath || '')
                };
                this.editDialogVisible = true;
            }
            this.setLoading('editLoading', false);
        },
        async editBroadcast(params) {
            this.setLoading('editLoading', true);

            // 发送请求前打印参数，用于调试
            console.log('发送编辑广播请求的参数:', params);

            const res = await updateBroadcast(params)
            if (res.code === 200) {
                this.$message.success(this.$t("backendSystem.editSuccess"))
                this.editDialogVisible = false;

                this.fetchList(this.listParams);
            }
            this.setLoading('editLoading', false);
        },
        async deleteBroadcast(params) {
            const res = await DeleteBroadcast(params)
            if (res.code === 200) {
                this.$message.success(this.$t("backendSystem.deleteSuccess"))
                this.fetchList(this.listParams);
            }
        },
        handelAddBroadcast() {
            this.dialogVisible = true;
        },
        handleClose() {
            this.dialogVisible = false;
            this.addParams.content = ""
            this.addParams.buttonContent = ""
            this.addParams.buttonPath = ""
            this.setLoading('bthLoading', false);
        },
        sureAddBroadcast() {

            this.addParams.content = this.addParams.content.trim()
            this.addParams.content = this.addParams.content.replace(/[\r\n]/g, '');
            this.addParams.buttonPath = this.addParams.buttonPath.trim()
            this.addParams.buttonPath = this.addParams.buttonPath.replace(/[\r\n]/g, '');
            if (!this.addParams.content) {
                this.$message.warning(this.$t("backendSystem.pleaseInputContent"))
                return
            }

            if ((this.addParams.buttonContent && this.addParams.buttonPath) || (!this.addParams.buttonContent && !this.addParams.buttonPath)) {

                if (this.addParams.buttonPath) {
                    // 兼容中英文逗号分割
                    let pathArray = this.addParams.buttonPath.split(/[,，]/).map(e => e.trim()).filter(e => e);
                    if (pathArray.length > 5) {
                        this.$message.warning(this.$t("backendSystem.max5"))
                        return
                    } else if (pathArray.length === 0) {
                        this.$message.warning(this.$t("backendSystem.pleaseInputButtonContentAndPath"))
                        return
                    }

                    // 验证每个路径是否以/开头
                    const invalidPaths = pathArray.filter(path => !path.startsWith('/'));
                    if (invalidPaths.length > 0) {
                        this.$message.error(`路径必须以 / 开头: ${invalidPaths.join(', ')}`);
                        return
                    }

                    if (this.addParams.buttonContent) {
                        // 兼容中英文逗号分割
                        let pathArray2 = this.addParams.buttonContent.split(/[,，]/).map(e => e.trim()).filter(e => e);
                        if (pathArray2.length > 5) {
                            this.$message.warning(this.$t("backendSystem.max5"))
                            return
                        } else if (pathArray2.length === 0) {
                            this.$message.warning(this.$t("backendSystem.pleaseInputButtonContentAndPath"))
                            return
                        }


                        if (this.addParams.buttonContent && this.addParams.buttonPath) {
                            if (pathArray.length !== pathArray2.length) {
                                this.$message.warning(this.$t("backendSystem.pathNumberNotMatch"))
                                return
                            }
                        }


                    }

                    // 验证通过，保持字符串格式传给后端（不转换为数组）
                    // this.addParams.buttonPath 保持原始字符串格式
                }


                this.addBroadcast(this.addParams);
            } else {
                this.$message.warning(this.$t("backendSystem.pleaseInputButtonContentAndPath"))
            }





        },
        sureEditBroadcast() {
            this.editParams.content = this.editParams.content.trim()
            this.editParams.content = this.editParams.content.replace(/[\r\n]/g, '');
            let buttonContentArray
            let pathArray 
            if (!this.editParams.content) {
                this.$message.warning(this.$t("backendSystem.pleaseInputContent"))
                return
            }
            if (this.editParams.buttonContent) {
                this.editParams.buttonContent = this.editParams.buttonContent.trim().replace(/[\r\n]/g, '');

                // 验证按钮内容和路径是否匹配
                if ((this.editParams.buttonContent && this.editParams.buttonPath) || (!this.editParams.buttonContent && !this.editParams.buttonPath)) {
                    if (this.editParams.buttonContent) {
                        // 兼容中英文逗号分割
                         buttonContentArray = this.editParams.buttonContent.split(/[,，]/).map(e => e.trim()).filter(e => e);
                        if (buttonContentArray.length > 5) {
                            this.$message.warning(this.$t("backendSystem.max5"))
                            return
                        } else if (buttonContentArray.length === 0) {
                            this.$message.warning(this.$t("backendSystem.pleaseInputButtonContentAndPath"))
                            return
                        }

                    }

                    // 如果有按钮路径，进行验证
                    if (this.editParams.buttonPath) {
                        this.editParams.buttonPath = this.editParams.buttonPath.trim().replace(/[\r\n]/g, '');

                        // 验证按钮内容和路径是否匹配
                        if ((this.editParams.buttonContent && this.editParams.buttonPath) || (!this.editParams.buttonContent && !this.editParams.buttonPath)) {
                            if (this.editParams.buttonPath) {
                                // 兼容中英文逗号分割
                                pathArray = this.editParams.buttonPath.split(/[,，]/).map(e => e.trim()).filter(e => e);
                                if (pathArray.length > 5) {
                                    this.$message.warning(this.$t("backendSystem.max5"))
                                    return
                                } else if (pathArray.length === 0) {
                                    this.$message.warning(this.$t("backendSystem.pleaseInputButtonContentAndPath"))
                                    return
                                }

                                // 验证每个路径是否以/开头
                                const invalidPaths = pathArray.filter(path => !path.startsWith('/'));
                                if (invalidPaths.length > 0) {
                                    this.$message.error(`路径必须以 / 开头: ${invalidPaths.join(', ')}`);
                                    return
                                }
                            }
                        } else {
                            this.$message.warning(this.$t("backendSystem.pleaseInputButtonContentAndPath"))
                            return
                        }
                    }

                    if (this.editParams.buttonContent && this.editParams.buttonPath) {
                        if (buttonContentArray.length !== pathArray.length) {
                            this.$message.warning(this.$t("backendSystem.pathNumberNotMatch"))
                            return
                        }
                    }

                } else {
                    this.$message.warning(this.$t("backendSystem.pleaseInputButtonContentAndPath"))
                    return
                }
            }


            this.editBroadcast(this.editParams);
        },
        handleEdit(row) {

            this.getBroadcast({ id: row.id });
        },
        handleEditClose() {
            this.editDialogVisible = false;
            this.editParams.content = ""
            this.editParams.buttonContent = ""
            this.editParams.buttonPath = ""
            this.setLoading('editLoading', false);
        },
        handelDelete(row) {
            this.deleteBroadcast({ id: row.id });
        },
        getUtf8Bytes(str) {
            let bytes = 0;
            for (let i = 0; i < str.length; i++) {
                const code = str.charCodeAt(i);
                if (code <= 0x7f) bytes += 1;
                else if (code <= 0x7ff) bytes += 2;
                else if (code <= 0xffff) bytes += 3;
                else bytes += 4;
            }
            return bytes;
        },

        handleInput(val, type = 'add') {
            let bytes = this.getUtf8Bytes(val);
            if (bytes > 100) {
                this.isOverLimit = true;
                // 截断到100字节
                let newVal = '';
                let total = 0;
                for (let ch of val) {
                    let chBytes = this.getUtf8Bytes(ch);
                    if (total + chBytes > 100) break;
                    newVal += ch;
                    total += chBytes;
                }
                if (type === 'add') {
                    this.addParams.content = newVal;
                } else {
                    this.editParams.content = newVal;
                }
                bytes = total;
            } else {
                this.isOverLimit = false;
                if (type === 'add') {
                    this.addParams.content = val;
                } else {
                    this.editParams.content = val;
                }
            }
            this.byteCount = bytes;
        },

        handelTime(time) {
            return `${time.split("T")[0]} ${time.split("T")[1]}`
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.listParams.pageSize = val
            this.listParams.pageNum = 1
            this.currentPage = 1
            this.fetchList(this.listParams);

        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.listParams.pageNum = val
            this.fetchList(this.listParams);
        },

        /**
         * 获取有效路径建议信息
         * @returns {Array} 路径建议列表
         */
        getValidPathSuggestions() {
            // 移除路径建议，返回空数组
            return [];
        },

        /**
         * 显示路径使用帮助
         */
        showPathHelp() {
            const helpMessage = `
                路径规则：
                • 多个路径用逗号分隔
                • 路径格式自由，不做严格验证
                • 支持任意路径格式
            `;

            this.$alert(helpMessage, '路径格式说明', {
                confirmButtonText: '知道了',
                type: 'info',
                customClass: 'path-help-dialog'
            });
        },

        /**
         * 格式化按钮内容显示
         * @param {string} buttonContent - 逗号分隔的按钮内容字符串
         * @returns {Array} 按钮内容数组
         */
        formatButtonContent(buttonContent) {
            if (!buttonContent || typeof buttonContent !== 'string') {
                return [];
            }
            return buttonContent
                .split(/[,，]/)
                .map(btn => btn.trim())
                .filter(btn => btn);
        },

        /**
         * 格式化按钮路径显示
         * @param {string} buttonPath - 逗号分隔的路径字符串
         * @returns {Array} 路径数组
         */
        formatButtonPath(buttonPath) {
            if (!buttonPath || typeof buttonPath !== 'string') {
                return [];
            }
            return buttonPath
                .split(/[,，]/)
                .map(path => path.trim())
                .filter(path => path);
        },





    },

}