<template>
    <view class="wxwork-contact-wrap">
        <slot></slot>
        <button
            type="default"
            hover-class="none"
            class="contact-button"
            @click="addWxWorkContact">
            <text class="btn-text">{{ btnText }}</text>
        </button>
        
        <!-- 确认弹窗 -->
        <uni-popup ref="confirmPopup" type="center">
            <view class="confirm-popup">
                <view class="popup-header">
                    <text>添加企业微信客服</text>
                </view>
                <view class="popup-body">
                    <text>点击确定后将跳转至企业微信，添加专业客服为您服务</text>
                </view>
                <view class="popup-footer">
                    <button class="cancel-btn" @click="closePopup">取消</button>
                    <button class="confirm-btn" @click="confirmAdd">确定</button>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
    import { WxWork } from '@/common/js/wxwork-jssdk.js';
    
    export default {
        name: 'wxwork-contact',
        props: {
            // 按钮文字
            btnText: {
                type: String,
                default: '添加企业微信客服'
            },
            // 企业ID（必需）
            corpId: {
                type: String,
                required: true
            },
            // 应用ID
            agentId: {
                type: String,
                default: ''
            },
            // 时间戳
            timestamp: {
                type: String,
                default: ''
            },
            // 随机字符串
            nonceStr: {
                type: String,
                default: ''
            },
            // 签名
            signature: {
                type: String,
                default: ''
            },
            // 客服ID或活码配置ID
            contactId: {
                type: String,
                default: ''
            },
            // 活码链接
            contactUrl: {
                type: String,
                default: ''
            },
            // 是否显示确认弹窗
            showConfirm: {
                type: Boolean,
                default: true
            }
        },
        data() {
            return {
                wxWorkSDK: null
            };
        },
        mounted() {
            this.initWxWork();
        },
        methods: {
            /**
             * 初始化企业微信SDK
             */
            initWxWork() {
                try {
                    if (this.corpId) {
                        this.wxWorkSDK = new WxWork();
                        const initResult = this.wxWorkSDK.init({
                            corpId: this.corpId,
                            agentId: this.agentId,
                            timestamp: this.timestamp,
                            nonceStr: this.nonceStr,
                            signature: this.signature,
                            jsApiList: ['openUserProfile', 'openEnterpriseChat']
                        });
                        
                        if (!initResult) {
                            console.error('企业微信SDK初始化失败');
                        }
                    }
                } catch (error) {
                    console.error('初始化企业微信SDK失败:', error);
                }
            },
            
            /**
             * 点击添加企业微信客服
             */
            addWxWorkContact() {
                if (this.showConfirm) {
                    this.$refs.confirmPopup.open();
                } else {
                    this.confirmAdd();
                }
            },
            
            /**
             * 确认添加
             */
            confirmAdd() {
                this.closePopup();
                
                // 直接使用props传递的配置
                const contactUrl = this.contactUrl;
                const contactId = this.contactId;
                
                // #ifdef MP-WEIXIN
                if (contactUrl) {
                    // 方案1：直接跳转到企业微信活码
                    this.jumpToWxWorkContact(contactUrl);
                } else if (contactId) {
                    // 方案2：使用SDK打开用户资料
                    this.openUserProfile(contactId);
                } else {
                    this.showError('未配置企业微信客服信息');
                }
                // #endif
                
                // #ifdef H5
                if (contactUrl) {
                    // H5环境直接跳转
                    window.location.href = contactUrl;
                } else {
                    this.showError('未配置企业微信客服信息');
                }
                // #endif
            },
            
            /**
             * 跳转到企业微信客服
             */
            jumpToWxWorkContact(contactUrl) {
                uni.navigateToMiniProgram({
                    appId: 'wxeb490c6f9b154ef9', // 企业微信小程序AppID
                    path: `pages/contacts/externalContactDetail?url=${encodeURIComponent(contactUrl)}`,
                    success: () => {
                        console.log('跳转企业微信成功');
                        this.$util.showToast({
                            title: '跳转成功',
                            icon: 'success'
                        });
                    },
                    fail: (err) => {
                        console.error('跳转企业微信失败:', err);
                        this.showError('跳转失败，请检查企业微信配置');
                    }
                });
            },
            
            /**
             * 打开用户资料
             */
            openUserProfile(contactId) {
                if (!this.wxWorkSDK) {
                    this.showError('企业微信SDK未初始化');
                    return;
                }
                
                this.wxWorkSDK.addContact({
                    userId: contactId
                }, (res) => {
                    console.log('打开用户资料成功:', res);
                }, (err) => {
                    console.error('打开用户资料失败:', err);
                    this.showError('打开用户资料失败');
                });
            },
            
            /**
             * 显示错误提示
             */
            showError(message) {
                uni.showModal({
                    title: '提示',
                    content: message,
                    showCancel: false
                });
            },
            
            /**
             * 关闭弹窗
             */
            closePopup() {
                this.$refs.confirmPopup.close();
            }
        }
    };
</script>

<style lang="scss" scoped>
    .wxwork-contact-wrap {
        width: 100%;
        height: 100%;
        position: relative;
        
        .contact-button {
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, #1e7dd8 0%, #1482e0 100%);
            color: #fff;
            border: none;
            border-radius: 8rpx;
            font-size: 28rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .btn-text {
                font-weight: 500;
            }
            
            &:active {
                opacity: 0.8;
            }
        }
    }
    
    .confirm-popup {
        width: 600rpx;
        background: #fff;
        border-radius: 16rpx;
        overflow: hidden;
        
        .popup-header {
            padding: 40rpx 30rpx 20rpx;
            text-align: center;
            font-size: 32rpx;
            font-weight: 600;
            color: #333;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .popup-body {
            padding: 30rpx;
            text-align: center;
            font-size: 28rpx;
            color: #666;
            line-height: 1.6;
        }
        
        .popup-footer {
            display: flex;
            border-top: 1px solid #f0f0f0;
            
            button {
                flex: 1;
                height: 88rpx;
                line-height: 88rpx;
                text-align: center;
                font-size: 30rpx;
                border: none;
                border-radius: 0;
                
                &.cancel-btn {
                    background: #fff;
                    color: #999;
                    border-right: 1px solid #f0f0f0;
                }
                
                &.confirm-btn {
                    background: #1e7dd8;
                    color: #fff;
                }
                
                &:active {
                    opacity: 0.8;
                }
            }
        }
    }
</style>