<template>
    <view class="main">
        <view class="mainTop" :style="{
            height: loginType === 'min' ? menu.bottom + 6 + 'px' : menu.top + 50 + 'px',
            paddingTop: loginType === 'min' ? menu.top - 6 + 'px' : menu.top + 'px',
            backgroundSize: `100% 100vh`
        }">
            <view class="mainTopContent" :style="{ height: loginType === 'min' ? menu.height + 12 + 'px' : '' }">
                <image class="backIcon" @click="handleBack"
                    src="https://eshangtech.com/ShopICO/ahyd-BID/commercial/navigation-left.svg" />
                <view class="robotBox">
                    <image class="robotImg" src="https://eshangtech.com/ShopICO/ahyd-BID/robot/robotIcon.png" />
                    <view class="robotDetail">
                        <span class="name">彩云驿</span>
                        <span class="desc">智能客服</span>
                    </view>
                </view>
            </view>
        </view>

        <view class="dialogContentBox"
            :style="{ paddingTop: loginType === 'min' ? menu.bottom + 12 + 'px' : menu.top + 60 + 'px' }">
            <view :class="item.type === 1 ? 'item itemLeft' : 'item rightItem'" v-for="(item, index) in dialogueList"
                :key="index" :style="{ marginTop: index !== 0 ? '30rpx' : '' }">
                <view :id="'printBox' + index" :class="item.type === 1 ? `dialogItem white` : `dialogItem green`">
                    {{ item.text || "" }}
                    <!-- <view class="line" v-if="item.searchType === 'default'"></view> -->
                    <!-- <view class="defaultBox">
                        <view>你可能想问：</view>
                    </view> -->
                    <view class="defaultBox" v-if="item.searchType === 'default'">
                        <view class="defautItem" v-for="(item, index) in defaultQaList" :key="index"
                            @click="handleGetAnwers(item.value)">
                            {{ item.label || "" }}
                        </view>
                    </view>
                </view>
            </view>

            <view class="loadingBox" v-if="isLoading"> 小驿分析中... </view>
        </view>

        <view class="inputBox" :style="{ minHeight: loginType === 'min' ? '180rpx' : '60px' }">
            <!-- <image class="microphone" src="https://eshangtech.com/ShopICO/ahyd-BID/robot/microphone.png" /> -->
            <div class="textBox">
                <textarea class="searchText" auto-height :value="searchText" @input="handleInput" placeholder="有问题尽管问我～"
                    placeholder-class="placeholder-style" maxlength="-1" cursor-spacing="20" :adjust-position="true" />
            </div>

            <view class="searchBtn" @click="handleSubmit"> 发送 </view>
        </view>
    </view>
</template>
<script>
export default {
    data() {
        return {
            searchText: "",
            dialogueList: [], // 对话list  type 1 是居左 2 是居右 searchType default
            printText: "",
            isLoading: false, // 是否加载中
            useInfo: {},
            menu: {},
            qaList: [
                {
                    "request": "服务区功能",
                    "answers": "进入本功能后，系统会自动定位并显示距离您最近的服务区，您可以查看该服务区的详细设施信息，包括餐饮、超市、加油、充电、洗手间、停车位等。同时，您还可以在页面中手动选择其他服务区，查看它们的设施与服务详情，方便您提前规划行程。"
                },
                {
                    "request": "商城功能",
                    "answers": "进入本功能后，您可以浏览精选商城，挑选心仪的商品进行购买。商城内包含食品、饮品、日用品、特产等多种类别，支持多种支付方式，购买后可选择邮寄到家或到指定地点自提，让您旅途中也能轻松购物。"
                },
                {
                    "request": "加油功能",
                    "answers": "进入本功能后，扫描页面提供的二维码，关注官方微信公众号，即可领取加油券大礼包。领取的加油券可在指定加油站使用，享受优惠加油服务，节省您的出行成本。具体使用规则可在领取页面查看。"
                },
                {
                    "request": "充电功能",
                    "answers": "点击本功能后，将跳转至云南交投新能源充电网平台小程序。在该平台，您可以查找附近的充电桩位置、实时充电状态、价格信息，并可直接在线导航至充电站，支持在线支付充电费用。"
                },
                {
                    "request": "ETC功能",
                    "answers": "点击本功能后，会出现两个入口供您选择：1）选择“ETC小程序”，将跳转至云南ETC车生活小程序，可办理ETC业务、充值、查询余额及账单；2）选择“ETC地图”，将显示云南省内的ETC网点分布图，您可以查询最近的ETC办理点或服务点的位置及联系方式。"
                },
                {
                    "request": "点餐功能",
                    "answers": "进入本功能后，将跳转至可预约点餐的服务区列表。您可以选择即将到达或感兴趣的服务区，提前浏览餐饮商家和菜单，并在线预约点餐，减少现场等待时间，方便快捷地享用美食。"
                },
                {
                    "request": "招商功能",
                    "answers": "进入本功能后，您可以查看各服务区的招商信息，包括招商项目类别、合作方式、租赁政策、联系方式等，方便有意向的商户了解并参与服务区的经营合作。"
                },
                {
                    "request": "租车功能",
                    "answers": "点击本功能后，将直接跳转至携程租车小程序。您可以在线选择租车地点、车型、租期，并完成下单支付。平台提供多种车型与价格选择，支持异地还车，满足不同出行需求。"
                },
                {
                    "request": "投诉建议功能",
                    "answers": "点击本功能后，将跳转至云南交投集团经营公司服务监督平台。您可以在线填写投诉或建议表单，上传相关图片或视频，提交后客服人员将及时处理并反馈，保障您的权益。"
                },
                {
                    "request": "保险功能",
                    "answers": "进入本功能后，您可以查看相关保险服务的推广信息，包括车险、意外险、旅行险等。您可根据自身需求在线咨询、投保或了解详细的保障范围和优惠活动。"
                },
                {
                    "request": "金融功能",
                    "answers": "进入本功能后，您可以浏览相关金融服务推广，包括分期付款、贷款、信用卡、理财产品等。可在线申请或咨询，享受便捷的金融支持，满足您在出行或消费中的资金需求。"
                }
            ],
            defaultQaList: [
                { label: "服务区功能说明", value: 0 },
                { label: "商城功能说明", value: 1 },
                { label: "加油功能说明", value: 2 },
                { label: "充电功能说明", value: 3 },
                { label: "ETC功能说明", value: 4 },
                { label: "点餐功能说明", value: 5 },
                { label: "招商功能说明", value: 6 },
                { label: "投诉建议功能说明", value: 7 },
                { label: "保险功能说明", value: 8 },
                { label: "金融功能说明", value: 9 },
            ],
            loginType: ""
        };
    },
    onLoad() {

        let systemInfo = uni.getSystemInfoSync();
        let type = uni.getStorageSync("loginType");
        this.loginType = type
        if (this.loginType === 'min') {
            this.menu = uni.getMenuButtonBoundingClientRect();
        } else {
            this.menu = systemInfo.safeArea;
        }
        console.log("menu", this.menu);
        this.dialogueList.push({
            text: `您好！欢迎咨询在线客服，请详细描述您的问题为您推荐一下常见问题，请点击选择：`,
            type: 1,
            searchType: "default",
        });
        // this.handlePrintText();
        // this.printText = `您好！我是服务区商业智能助理小驿。<br>您想了解服务区哪些方面的信息？`
    },
    methods: {
        handleGetAnwers(index) {
            let list = this.dialogueList;
            let text = this.qaList[index].request
            list.push({ text: text, type: 2 });
            this.searchText = "";
            let _this = this
            _this.isLoading = true
            this.scrollToBottom();
            setTimeout(() => {
                let data = this.qaList[index]
                if (data) {
                    list.push({ text: data.answers, type: 1 });
                    _this.dialogueList = list;
                } else {
                    list.push({ text: '小驿不太明白您的意思。', type: 1 });
                    _this.dialogueList = list;
                }
                _this.isLoading = false
                _this.$forceUpdate();
                _this.scrollToBottom();
            }, 500)
        },
        handleBack() {
            uni.navigateBack({
                delta: 1,
            });
        },
        handleInput(e) {
            console.log('e', e);
            const value = e.detail.value;

            // 检测是否包含回车符
            if (value.includes('\n')) {
                // 移除回车符
                const cleanValue = value.replace(/\n/g, '');
                this.searchText = cleanValue;

                // 如果有内容则发送
                if (cleanValue.trim()) {
                    this.handleSubmit();
                }
            } else {
                this.searchText = value;
            }
        },
        handleSubmit() {
            console.log("this.searchText", this.searchText);
            if (this.searchText) {
                let list = this.dialogueList;
                let text = this.searchText
                list.push({ text: text, type: 2 });
                this.searchText = "";
                let _this = this
                _this.isLoading = true
                this.scrollToBottom();
                setTimeout(() => {
                    const data = _this.findClosestMatch(text)
                    if (data) {
                        list.push({ text: data.answers, type: 1 });
                        _this.dialogueList = list;
                    } else {
                        list.push({ text: '小驿不太明白您的意思。', type: 1 });
                        _this.dialogueList = list;
                    }
                    _this.isLoading = false
                    _this.$forceUpdate();
                    _this.scrollToBottom();
                }, 500)
            }
        },
        // 简单关键词匹配（评分方式）
        findClosestMatch(input) {
            if (!input) return null;
            const keywords = input.split(/[\s，。？！、]/).filter(Boolean);
            let maxScore = 0;
            let bestMatch = null;

            this.qaList.forEach(item => {
                let score = 0;
                keywords.forEach(kw => {
                    if (item.request.includes(kw)) {
                        score += 1;
                    }
                });
                if (score > maxScore) {
                    maxScore = score;
                    bestMatch = item;
                }
            });
            console.log('bestMatch', bestMatch);

            return bestMatch;
        },
        // 自动滚动到底部
        scrollToBottom() {
            this.$nextTick(() => {
                uni.pageScrollTo({
                    scrollTop: 99999,
                    duration: 300
                });
            });
        }
    },
};
</script>

<style scoped lang="scss">
.main {
    width: 100%;
    min-height: 100vh;
    // background: #f0f0f0;
    background-image: url("https://eshangtech.com/minTestImg/pageBg.png");
    background-repeat: no-repeat;

    .mainTop {
        width: 100%;
        box-sizing: border-box;
        position: fixed;
        top: 0;
        left: 0;
        background-image: url("https://eshangtech.com/minTestImg/pageBg.png");
        background-repeat: no-repeat;

        .mainTopContent {
            width: 100%;
            box-sizing: border-box;
            padding-left: 32rpx;
            display: flex;
            align-items: center;

            .backIcon {
                width: 52rpx;
                height: 52rpx;
                margin-right: 16rpx;
            }

            .robotBox {
                display: flex;
                align-items: center;

                .robotImg {
                    width: 68rpx;
                    height: 68rpx;
                    margin-right: 16rpx;
                }

                .robotDetail {
                    display: flex;
                    flex-direction: column;

                    .name {
                        font-family: PingFangSC, PingFang SC;
                        font-weight: 600;
                        font-size: 28rpx;
                        color: #090c1a;
                        line-height: 40rpx;
                        text-align: left;
                        font-style: normal;
                    }

                    .desc {
                        font-family: PingFangSC, PingFang SC;
                        font-weight: 400;
                        font-size: 24rpx;
                        color: #787879;
                        line-height: 36rpx;
                        text-align: justify;
                        font-style: normal;
                    }
                }
            }
        }
    }

    .dialogContentBox {
        width: 100%;
        // height: calc(100vh - 90px);
        min-height: calc(100vh - var(--nav-height) - 180rpx - env(safe-area-inset-bottom));
        overflow-y: scroll;
        box-sizing: border-box;
        padding: 32rpx;
        padding-bottom: calc(180rpx + env(safe-area-inset-bottom));
        /* 增加底部内边距 */
        /* 新增平滑滚动 */
        scroll-behavior: smooth;

        .item {
            display: flex;
            align-items: center;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 30rpx;
            color: #090c1a;
            line-height: 44rpx;
            text-align: left;
            font-style: normal;

            .dialogItem {
                max-width: calc(100vw - 64rpx);
                display: block;
                box-sizing: border-box;
                // padding: 24rpx 32rpx;
                padding: 16rpx 30rpx;
                border-radius: 4px;
                background: #ffffff;
                border-radius: 0rpx 24rpx 24rpx 24rpx;

                .line {
                    width: 100%;
                    height: 2rpx;
                    background: #f2f2f2;
                    border-radius: 16rpx;
                    margin: 24rpx 0;
                }

                .defaultBox {
                    .clickItem {
                        font-family: PingFangSC, PingFang SC;
                        font-weight: 400;
                        font-size: 30rpx;
                        color: #2363ff;
                        line-height: 44rpx;
                        text-align: left;
                        font-style: normal;
                    }

                    .defautItem {
                        color: #28B360;
                        padding: 8rpx 0;
                        text-decoration: underline;
                    }
                }


            }

            .white {
                background: #fff;
                color: #000;
                border-radius: 20rpx 20rpx 20rpx 5rpx;
            }

            .green {
                background: #28B360;
                color: #fff;
                border-radius: 20rpx 20rpx 5rpx 20rpx;
            }
        }

        .itemLeft {
            justify-content: flex-start;
        }

        .rightItem {
            justify-content: flex-end;
        }

        .loadingBox {
            font-size: 12px;
            color: #ccc;
            width: 100%;
            display: flex;
            justify-content: center;
        }
    }

    .inputBox {
        width: 100%;
        min-height: 180rpx;
        background: #fff;
        position: fixed;
        left: 0;
        bottom: 0;
        box-sizing: border-box;
        padding: 16rpx 32rpx;
        padding-bottom: env(safe-area-inset-bottom);
        display: flex;
        align-items: flex-end;
        /* 修改为底部对齐 */
        border-top: 1rpx solid #f2f2f2;

        .microphone {
            width: 48rpx;
            height: 48rpx;
            margin-right: 16rpx;
        }

        .textBox {
            width: calc(100% - 140rpx);
            min-height: 88rpx;
            max-height: 300rpx;
            /* 设置最大高度 */
            background: #f2f3f7;
            border-radius: 44rpx;
            padding: 16rpx 32rpx;
            box-sizing: border-box;
            display: flex;
            align-items: center;
        }

        .searchText {
            width: 100%;
            font-size: 28rpx;
            line-height: 1.5;
            max-height: 268rpx;
            /* textBox高度减去padding */
            overflow-y: auto;
            /* 内容过多时可滚动 */
        }

        .placeholder-style {
            color: #999;
            font-size: 28rpx;
            display: flex;
            align-items: center;
        }

        .searchBtn {
            width: 128rpx;
            height: 88rpx;
            box-sizing: border-box;
            color: #fff;
            background: #28B360;
            border-radius: 44rpx;
            margin-left: 16rpx;
            font-family: "Microsoft YaHei";
            font-weight: 400;
            font-size: 28rpx;
            color: #FFFFFF;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
}
</style>
