<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: '添加企业微信客服'
            },
            // 企业微信配置
            corpId: {
                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
             */
            async initWxWork() {
                try {
                    // 获取企业微信配置
                    const res = await this.$api.sendRequest({
                        url: '/api/wxwork/config',
                        data: {
                            corp_id: this.corpId
                        }
                    });
                    
                    if (res.code === 0 && res.data) {
                        this.wxWorkSDK = new WxWork();
                        const initResult = this.wxWorkSDK.init({
                            corpId: res.data.corp_id,
                            agentId: res.data.agent_id,
                            timestamp: res.data.timestamp,
                            nonceStr: res.data.nonceStr,
                            signature: res.data.signature,
                            jsApiList: ['openUserProfile', 'openEnterpriseChat']
                        });
                        
                        if (!initResult) {
                            console.error('企业微信SDK初始化失败');
                        }
                    }
                } catch (error) {
                    console.error('获取企业微信配置失败:', error);
                }
            },
            
            /**
             * 点击添加企业微信客服
             */
            addWxWorkContact() {
                if (this.showConfirm) {
                    this.$refs.confirmPopup.open();
                } else {
                    this.confirmAdd();
                }
            },
            
            /**
             * 确认添加
             */
            confirmAdd() {
                this.closePopup();
                
                // #ifdef MP-WEIXIN
                if (this.contactUrl) {
                    // 方案1：直接跳转到企业微信活码
                    this.jumpToWxWorkContact();
                } else if (this.contactId) {
                    // 方案2：使用SDK打开用户资料
                    this.openUserProfile();
                } else {
                    this.showError('未配置企业微信客服信息');
                }
                // #endif
                
                // #ifdef H5
                if (this.contactUrl) {
                    // H5环境直接跳转
                    window.location.href = this.contactUrl;
                } else {
                    this.showError('未配置企业微信客服信息');
                }
                // #endif
            },
            
            /**
             * 跳转到企业微信客服
             */
            jumpToWxWorkContact() {
                uni.navigateToMiniProgram({
                    appId: 'wxeb490c6f9b154ef9', // 企业微信小程序AppID
                    path: `pages/contacts/externalContactDetail?url=${encodeURIComponent(this.contactUrl)}`,
                    success: () => {
                        console.log('跳转企业微信成功');
                        this.$util.showToast({
                            title: '跳转成功',
                            icon: 'success'
                        });
                    },
                    fail: (err) => {
                        console.error('跳转企业微信失败:', err);
                        this.showError('跳转失败，请检查企业微信配置');
                    }
                });
            },
            
            /**
             * 打开用户资料
             */
            openUserProfile() {
                if (!this.wxWorkSDK) {
                    this.showError('企业微信SDK未初始化');
                    return;
                }
                
                this.wxWorkSDK.addContact({
                    userId: this.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>