<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
            <el-form-item label="选择主体" prop="corpId" required>
                <el-select
                    v-model="queryParams.corpId"
                    placeholder="请选择主体"
                    clearable
                    size="small"
                    style="width: 200px"
                    @change="handleCorpChange"
                >
                    <el-option
                        v-for="item in corpOptions"
                        :key="item.corpId"
                        :label="item.corpName"
                        :value="item.corpId"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="链接名称" prop="linkName">
                <el-input
                    v-model="queryParams.linkName"
                    placeholder="请输入链接名称"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="链接ID" prop="linkId">
                <el-input
                    v-model="queryParams.linkId"
                    placeholder="请输入链接ID"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
                    <el-option label="正常" :value="1" />
                    <el-option label="已失效" :value="2" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-download" size="mini" @click="downloadTemplate">下载导入模板</el-button>
            </el-col>
        </el-row>

        <!-- 数据表格 -->
        <el-table
            v-loading="loading"
            :data="assistantList"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" prop="id" width="80" align="center" />
            <el-table-column label="主体" width="150" align="center">
                <template slot-scope="scope">
                    {{ getCorpName(scope.row.corpId) }}
                </template>
            </el-table-column>
            <el-table-column label="链接ID" prop="linkId" width="200" :show-overflow-tooltip="true" />
            <el-table-column label="链接名称" prop="linkName" width="150" :show-overflow-tooltip="true" />
            <el-table-column label="获客链接" prop="url" width="200" :show-overflow-tooltip="true" />
            <el-table-column label="使用范围" prop="rangeDesc" width="200" :show-overflow-tooltip="true" />
            <el-table-column label="状态" width="80" align="center">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                        {{ scope.row.status === 1 ? '正常' : '已失效' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="企微创建时间" width="160" align="center">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.qwCreateTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="280" fixed="right">
                <template slot-scope="scope">
                    <!-- 第一行：基础操作 -->
                    <div class="action-group">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            @click="handleDetail(scope.row)"
                        >详情</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                        >修改</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                        >删除</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-link"
                            @click="handleExtractLink(scope.row)"
                        >提取电话版链接</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-link"
                            @click="handleExtractLinkNol(scope.row)"
                        >提取获客链接</el-button>
                    </div>
                    <!-- 第二行：扩展操作 -->
                    <div class="action-group">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-message"
                            style="color: #E6A23C;"
                            @click="handleSendSms(scope.row)"
                        >发短信</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-upload2"
                            style="color: #409EFF;"
                            @click="handleUploadPhones(scope.row)"
                        >批量短信</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-mobile-phone"
                            style="color: #909399;"
                            @click="handleIpadBlindAdd(scope.row)"
                        >iPad加好友</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 新增/修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="140px">
                <el-form-item label="链接名称" prop="linkName">
                    <el-input v-model="form.linkName" placeholder="请输入链接名称" maxlength="50" />
                </el-form-item>

                <el-form-item label="是否无需验证" prop="skipVerify">
                    <el-radio-group v-model="form.skipVerify">
                        <el-radio :label="true">无需验证</el-radio>   <!-- true 表示无需验证 -->
                        <el-radio :label="false">需要验证</el-radio>  <!-- false 表示需要验证 -->
                    </el-radio-group>
                    <div class="el-form-item__tips" style="color: #909399; font-size: 12px; margin-top: 5px;">
                        选择"无需验证"时，客户添加好友无需员工确认
                    </div>
                </el-form-item>

                <el-form-item label="优先分配类型" prop="priorityType">
                    <el-radio-group v-model="form.priorityType">
                        <el-radio :label="0">不启用</el-radio>
                        <el-radio :label="1">全企业范围内优先分配给有好友关系的</el-radio>
                        <el-radio :label="2">指定范围内优先分配有好友关系的</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 关联成员选择器（企微用户） -->
                <el-form-item label="关联成员" prop="selectedUserIds">
                    <el-select
                        v-model="form.selectedUserIds"
                        multiple
                        filterable
                        remote
                        reserve-keyword
                        :remote-method="searchQwUsers"
                        :loading="userLoading"
                        :multiple-limit="500"
                        :disabled="!queryParams.corpId"
                        :placeholder="getUserSelectPlaceholder"
                        style="width: 100%"
                        @visible-change="handleSelectVisible"
                        @focus="loadUsersByCorp"
                        @change="handleUserSelectionChange"
                    >
                        <el-option
                            v-for="item in qwUserOptions"
                            :key="item.id"
                            :label="`${item.qwUserName} (${item.qwUserId})`"
                            :value="item.id"
                        >
                            <span style="float: left">{{ item.qwUserName }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.qwUserId }}</span>
                            <div style="clear: both;"></div>
                            <div style="font-size: 12px; color: #999;" v-if="item.department">
                                部门：{{ item.departmentName || item.department }} | 本地ID：{{ item.id }}
                            </div>
                        </el-option>

                        <!-- 加载更多 -->
                        <div style="text-align: center; padding: 10px;" v-if="hasMoreUsers">
                            <el-button type="text" @click="loadMoreUsers" :loading="loadingMore">加载更多</el-button>
                        </div>

                        <!-- 空状态 -->
                        <div slot="empty" style="text-align: center; padding: 20px;">
                            <span v-if="!queryParams.corpId">请先在搜索栏选择主体</span>
                            <span v-else-if="searchKeyword">未找到相关成员</span>
                            <span v-else>暂无成员数据</span>
                        </div>
                    </el-select>

                    <!-- 显示当前选择的主体信息 -->
                    <div v-if="queryParams.corpId" class="el-form-item__tips" style="color: #67C23A; font-size: 12px; margin-top: 5px;">
                        当前主体：{{ getCorpName(queryParams.corpId) }}
                    </div>

                    <!-- 已选信息展示 -->
                    <div v-if="form.selectedUserIds && form.selectedUserIds.length" class="el-form-item__tips" style="color: #909399; font-size: 12px; margin-top: 5px;">
                        <div>已选择 {{ form.selectedUserIds.length }} 名成员</div>
                        <el-button type="text" @click="clearSelectedUsers" size="mini">清空</el-button>
                    </div>
                </el-form-item>

                <el-form-item label="员工添加上限" prop="isUserLimit">
                    <el-table  :data="userLimitJson" style="border: 1px solid #e6e6e6;width: 80%;">
                        <el-table-column label="成员" align="center" prop="userId" >
                            <template slot-scope="scope">
                                <div v-for="(qwUser, index) in qwUserOptions" :key="index">
                                    <span v-if="qwUser.id==scope.row.qwUserId">{{qwUser.qwUserName}}</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="数量" align="center" prop="limitCount" >
                            <template slot-scope="scope">
                                <div>
                                    <el-input-number v-model="scope.row.limitCount"    size="mini" :min="0"   ></el-input-number>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <!--        <el-form-item label="备用员工" prop="spareUserIds" >-->
                <!--          <el-select v-model="spareUserIds" remote multiple placeholder="员工" filterable >-->
                <!--            <el-option-->
                <!--              v-for="dict in this.form.qwUserOptions"-->
                <!--              :key="dict.qwUserId"-->
                <!--              :label="dict.qwUserName"-->
                <!--              :value="dict.qwUserId">-->
                <!--            </el-option>-->
                <!--          </el-select>-->
                <!--        </el-form-item>-->


                <el-form-item label="备用员工" prop="spareUserIds">
                    <el-select
                        v-model="spareUserIds"
                        multiple
                        filterable
                        remote
                        reserve-keyword
                        :remote-method="searchQwUsers"
                        :loading="userLoading"
                        :multiple-limit="500"
                        :disabled="!queryParams.corpId"
                        :placeholder="getUserSelectPlaceholder"
                        style="width: 100%"
                        @visible-change="handleSelectVisible"
                        @focus="loadUsersByCorp"
                    >
                        <el-option
                            v-for="item in qwUserOptions"
                            :key="item.id"
                            :label="`${item.qwUserName} (${item.qwUserId})`"
                            :value="item.id"
                        >
                            <span style="float: left">{{ item.qwUserName }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.qwUserId }}</span>
                            <div style="clear: both;"></div>
                            <div style="font-size: 12px; color: #999;" v-if="item.department">
                                部门：{{ item.departmentName || item.department }} | 本地ID：{{ item.id }}
                            </div>
                        </el-option>

                        <!-- 加载更多 -->
                        <div style="text-align: center; padding: 10px;" v-if="hasMoreUsers">
                            <el-button type="text" @click="loadMoreUsers" :loading="loadingMore">加载更多</el-button>
                        </div>

                        <!-- 空状态 -->
                        <div slot="empty" style="text-align: center; padding: 20px;">
                            <span v-if="!queryParams.corpId">请先在搜索栏选择主体</span>
                            <span v-else-if="searchKeyword">未找到相关成员</span>
                            <span v-else>暂无成员数据</span>
                        </div>
                    </el-select>
                </el-form-item>

                <!-- 部门选择（如果有部门选择组件） -->
                <el-form-item label="关联部门" prop="departmentListParam" v-if="showDepartment">
                    <el-select
                        v-model="form.departmentListParam"
                        multiple
                        filterable
                        placeholder="请选择部门"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in departmentOptions"
                            :key="item.id"
                            :label="item.departmentName"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="200" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog title="获客链接详情" :visible.sync="detailOpen" width="700px" append-to-body>
            <el-form ref="detailForm" :model="detailData" label-width="140px">
                <el-form-item label="链接ID">{{ detailData.linkId }}</el-form-item>
                <el-form-item label="链接名称">{{ detailData.linkName }}</el-form-item>
                <el-form-item label="链接URL">
                    <el-link :href="detailData.url" target="_blank" type="primary">{{ detailData.url }}</el-link>
                </el-form-item>
                <el-form-item label="链接Scheme">{{ detailData.scheme }}</el-form-item>
                <el-form-item label="是否无需验证">
                    <el-tag :type="detailData.skipVerify === true ? 'success' : 'info'">
                        {{ detailData.skipVerify === true ? '无需验证' : '需要验证' }}
                    </el-tag>
                    <span style="margin-left: 8px; color: #909399; font-size: 12px;">
            (skipVerify = {{ detailData.skipVerify }})
          </span>
                </el-form-item>

                <el-form-item label="优先分配类型">
                    <span v-if="detailData.priorityType === 0">不启用</span>
                    <span v-else-if="detailData.priorityType === 1">全企业范围内优先分配给有好友关系的</span>
                    <span v-else-if="detailData.priorityType === 2">指定范围内优先分配有好友关系的</span>
                </el-form-item>
                <el-form-item label="关联成员">
                    <span>{{ formatDetailMembers(detailData.qwUserTableIdList) }}</span>
                </el-form-item>
                <el-form-item label="优先分配成员" v-if="detailData.priorityType === 2">
                    {{ detailData.priorityUserListParam ? detailData.priorityUserListParam.join(', ') : '-' }}
                </el-form-item>
                <el-form-item label="使用范围描述">{{ detailData.rangeDesc || '-' }}</el-form-item>
                <el-form-item label="状态">
                    <el-tag :type="detailData.status === 1 ? 'success' : 'danger'">
                        {{ detailData.status === 1 ? '正常' : '已失效' }}
                    </el-tag>
                </el-form-item>
                <el-form-item label="备用成员">
                    <span>{{ formatDetailMembers(detailData.spareUserIds) }}</span>
                </el-form-item>
                <el-form-item label="企微创建时间">{{ parseTime(detailData.qwCreateTime) }}</el-form-item>
                <el-form-item label="最后同步时间">{{ parseTime(detailData.syncTime) }}</el-form-item>
                <el-form-item label="备注">{{ detailData.remark || '-' }}</el-form-item>
            </el-form>
        </el-dialog>

        <!-- 二维码弹窗 -->
        <el-dialog
            title="获客链接二维码"
            :visible.sync="qrCodeDialog.visible"
            width="500px"
            append-to-body
            @closed="handleQrCodeDialogClosed"
        >
            <div class="qr-code-container" v-loading="qrCodeDialog.generating">
                <div class="qr-code-wrapper" v-if="qrCodeDialog.dataUrl">
                    <img :src="qrCodeDialog.dataUrl" alt="二维码" class="qr-code-image" />
                    <div class="qr-code-info">
                        <p><strong>链接名称：</strong>{{ qrCodeDialog.linkName }}</p>
                        <p><strong>链接ID：</strong>{{ qrCodeDialog.linkId }}</p>
                        <p><strong>pageParam：</strong>{{ qrCodeDialog.pageParam }}</p>
                    </div>
                </div>
                <div v-else-if="!qrCodeDialog.generating" class="qr-code-empty">
                    <el-empty description="暂无二维码" />
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="downloadQRCode" :disabled="!qrCodeDialog.dataUrl">
                    <i class="el-icon-download"></i> 保存二维码
                </el-button>
                <el-button @click="qrCodeDialog.visible = false">关 闭</el-button>
            </div>
        </el-dialog>

        <!-- 发送短信弹窗 -->
        <el-dialog
            title="发送获客链接短信"
            :visible.sync="smsDialog.visible"
            width="400px"
            append-to-body
            @close="handleSmsDialogClose"
        >
            <el-form :model="smsDialog" label-width="100px">
                <el-form-item label="手机号码" required>
                    <el-input
                        v-model="smsDialog.phone"
                        placeholder="请输入手机号码"
                        clearable
                    />
                    <div class="el-form-item__tips" style="color: #909399; font-size: 12px; margin-top: 5px;">
                        请输入11位手机号码
                    </div>
                </el-form-item>
                <el-form-item label="链接名称">
                    <span>{{ smsDialog.linkName }}</span>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="confirmSendSms" :loading="smsDialog.sending">
                    确 定 发 送
                </el-button>
                <el-button @click="smsDialog.visible = false">取 消</el-button>
            </div>
        </el-dialog>

        <!--导入电话号码弹窗 -->
        <el-dialog
            title="导入电话号码文件"
            :visible.sync="uploadPhoneDialog.visible"
            width="500px"
            append-to-body
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :show-close="!uploadPhoneDialog.loading"
            @close="closeUploadPhoneDialog"
        >
            <div v-loading="uploadPhoneDialog.loading" element-loading-text="处理中...">
                <p style="color: #909399; font-size: 14px; margin-bottom: 20px;">
                    请上传 .xls 格式的文件，文件第一行为表头，第二列为电话号码。
                    <br/>
                    <strong>当前操作链接:</strong> {{ uploadPhoneDialog.rowData ? uploadPhoneDialog.rowData.linkName : '' }}
                </p>
                <el-upload
                    ref="upload"
                    class="upload-demo"
                    drag
                    action="#"
                    :http-request="handleHttpRequest"
                    :on-change="handleFileChange"
                    :before-upload="beforeUpload"
                    :show-file-list="true"
                    accept=".xls"
                    :limit="1"
                    :on-exceed="handleExceed"
                >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">
                        仅限 .xls 文件，大小不超过 5MB
                    </div>
                </el-upload>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="uploadPhoneDialog.visible = false" :disabled="uploadPhoneDialog.loading">取 消</el-button>
                <el-button type="primary" @click="startUpload" :loading="uploadPhoneDialog.loading">开始上传</el-button>
            </div>
        </el-dialog>

        <!-- 提取链接弹窗 -->
        <el-dialog
            title="提取链接"
            :visible.sync="extractLinkDialog.visible"
            width="500px"
            append-to-body
            :close-on-click-modal="false"
            @close="closeExtractLinkDialog"
        >
            <div v-loading="extractLinkDialog.loading" element-loading-text="生成中...">
                <el-form :model="extractLinkDialog" label-width="100px">
                    <el-form-item label="手机号码" required>
                        <el-input
                            v-model="extractLinkDialog.phone"
                            placeholder="请输入手机号码"
                            clearable
                            :disabled="extractLinkDialog.resultText !== ''"
                        />
                        <div class="el-form-item__tips" style="color: #909399; font-size: 12px; margin-top: 5px;">
                            请输入11位手机号码
                        </div>
                    </el-form-item>
                    <el-form-item label="链接名称">
                        <span>{{ extractLinkDialog.rowData ? extractLinkDialog.rowData.linkName : '' }}</span>
                    </el-form-item>

                    <!-- 结果显示区域 -->
                    <el-form-item label="生成结果" v-if="extractLinkDialog.resultText">
                        <el-input
                            type="textarea"
                            :rows="4"
                            v-model="extractLinkDialog.resultText"
                            readonly
                            placeholder="生成的文本内容"
                        />
                        <div class="el-form-item__tips" style="color: #67C23A; font-size: 12px; margin-top: 5px;">
                            点击下方按钮复制文本
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <template v-if="!extractLinkDialog.resultText">
                    <el-button type="primary" @click="confirmExtractLink" :loading="extractLinkDialog.loading">
                        确 定 生 成
                    </el-button>
                    <el-button @click="closeExtractLinkDialog">取 消</el-button>
                </template>
                <template v-else>
                    <el-button type="success" @click="copyExtractResult">
                        <i class="el-icon-document-copy"></i> 复制文本
                    </el-button>
                    <el-button @click="closeExtractLinkDialog">关 闭</el-button>
                </template>
            </div>
        </el-dialog>

        <el-dialog
            title="提取链接"
            :visible.sync="extractLinkDialogNol.visible"
            width="500px"
            append-to-body
            :close-on-click-modal="false"
            @close="closeExtractLinkDialog"
        >
            <div v-loading="extractLinkDialogNol.loading" element-loading-text="生成中...">
                <el-form :model="extractLinkDialogNol" label-width="100px">
                    <el-form-item label="生成结果(短链)" v-if="extractLinkDialogNol.shortLink">
                        <el-input
                            type="textarea"
                            :rows="4"
                            v-model="extractLinkDialogNol.shortLink"
                            readonly
                            placeholder="生成的文本内容"
                        />
                        <div class="el-form-item__tips" style="color: #67C23A; font-size: 12px; margin-top: 5px;">
                            点击下方按钮复制文本
                        </div>
                    </el-form-item>

                    <el-form-item label="生成结果(长链接)" v-if="extractLinkDialogNol.linkPlus">
                        <el-input
                            type="textarea"
                            :rows="4"
                            v-model="extractLinkDialogNol.linkPlus"
                            readonly
                            placeholder="生成的文本内容"
                        />
                        <div class="el-form-item__tips" style="color: #67C23A; font-size: 12px; margin-top: 5px;">
                            点击下方按钮复制文本
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="success" @click="copyExtractResultNol">
                    <i class="el-icon-document-copy"></i> 复制文本(短链)
                </el-button>
                <el-button type="success" @click="copyExtractResultNolLong">
                    <i class="el-icon-document-copy"></i> 复制文本(长链链接)
                </el-button>
                <el-button @click="closeExtractLinkDialogNol">关 闭</el-button>
            </div>
        </el-dialog>

        <!-- iPad获客链接加好友弹窗 -->
        <el-dialog
            title="iPad获客链接加好友"
            :visible.sync="ipadBlindAddDialog.visible"
            width="500px"
            append-to-body
            :close-on-click-modal="false"
            @close="closeIpadBlindAddDialog"
        >
            <div v-loading="ipadBlindAddDialog.loading" element-loading-text="处理中...">
                <el-form :model="ipadBlindAddDialog" label-width="100px">
                    <!-- 显示链接信息 -->
                    <el-form-item label="链接名称">
                        <span>{{ ipadBlindAddDialog.rowData ? ipadBlindAddDialog.rowData.linkName : '' }}</span>
                    </el-form-item>
                    <el-form-item label="链接ID">
                        <span>{{ ipadBlindAddDialog.rowData ? ipadBlindAddDialog.rowData.linkId : '' }}</span>
                    </el-form-item>

                    <!-- 成员选择 - 如果只有一个成员则自动选中，多个成员则需要手动选择 -->
                    <el-form-item label="选择成员" required>
                        <el-select
                            v-model="ipadBlindAddDialog.selectedUserId"
                            placeholder="请选择成员"
                            clearable
                            style="width: 100%"
                            :disabled="ipadBlindAddDialog.memberList.length === 1"
                        >
                            <el-option
                                v-for="item in ipadBlindAddDialog.memberList"
                                :key="item.id"
                                :label="`${item.qwUserName} (${item.qwUserId})`"
                                :value="item.id"
                            >
                                <span style="float: left">{{ item.qwUserName }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.qwUserId }}</span>
                                <div style="clear: both;"></div>
                                <div style="font-size: 12px; color: #999;" v-if="item.departmentName">
                                    部门：{{ item.departmentName }}
                                </div>
                            </el-option>
                        </el-select>
                        <div v-if="ipadBlindAddDialog.memberList.length === 1" class="el-form-item__tips" style="color: #67C23A; font-size: 12px; margin-top: 5px;">
                            该链接只有一名成员，已自动选中
                        </div>
                        <div v-else-if="ipadBlindAddDialog.memberList.length > 1" class="el-form-item__tips" style="color: #E6A23C; font-size: 12px; margin-top: 5px;">
                            该链接有 {{ ipadBlindAddDialog.memberList.length }} 名成员，请选择一名
                        </div>
                    </el-form-item>

                    <!-- 手机号码输入 -->
                    <el-form-item label="手机号码" required>
                        <el-input
                            v-model="ipadBlindAddDialog.phone"
                            placeholder="请输入手机号码"
                            clearable
                        />
                        <div class="el-form-item__tips" style="color: #909399; font-size: 12px; margin-top: 5px;">
                            请输入11位手机号码
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="confirmIpadBlindAdd" :loading="ipadBlindAddDialog.loading">
                    确 定 添 加
                </el-button>
                <el-button @click="ipadBlindAddDialog.visible = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listAssistant,
    getDetailByLinkId,
    addAssistant,
    updateAssistant,
    deleteAssistant,
    getQwUserList,
    getQwUserListByIds,
    qwUserCompanyList,
    sendMessageLink,
    batchCreateMessageLink,
    extractLink,
    ipadBlindAdd
} from '@/api/qw/acquisitionAssistant'

import QRCode from 'qrcodejs2'
import {extractLinkNol} from "../../../api/qw/acquisitionAssistant";

export default {
    name: 'AcquisitionAssistant',
    data() {
        return {
            // 提取链接弹窗数据
            extractLinkDialog: {
                visible: false,
                loading: false,
                phone: '',
                rowData: null,
                resultText: ''
            },
            extractLinkDialogNol:{
                visible: false,
                loading: false,
                rowData: null,
                linkPlus: '',
                shortLink: ''
            },
            // 导入电话号码弹窗数据
            uploadPhoneDialog: {
                visible: false,
                loading: false,
                rowData: null,
            },
            // 遮罩层
            loading: true,
            userLoading: false,
            loadingMore: false,
            // 添加部门选择器显示控制
            showDepartment: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 表格数据
            assistantList: [],
            // 详情数据
            detailData: {},
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            detailOpen: false,
            // 二维码弹窗数据
            qrCodeDialog: {
                visible: false,
                generating: false,
                dataUrl: null,
                fullUrl: '',
                linkName: '',
                linkId: '',
                pageParam: '',
                rowData: null
            },
            // 短信发送弹窗数据
            smsDialog: {
                visible: false,
                sending: false,
                phone: '',
                linkId: '',
                linkName: '',
                fullUrl: '',
                rowData: null
            },
            // iPad获客链接加好友弹窗数据
            ipadBlindAddDialog: {
                visible: false,
                loading: false,
                phone: '',
                selectedUserId: null,
                memberList: [],
                rowData: null
            },
            // 查询参数 - corpId作为全局筛选条件
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                linkName: '',
                linkId: '',
                status: '',
                corpId: '' // 全局主体ID，所有需要corpId的接口都会用到
            },
            // 表单参数
            form: {
                // 基础信息
                linkName: '',
                skipVerify: true,
                priorityType: 0,
                remark: '',
                corpId: '',
                id: null,

                // 关联成员相关（三套数据，各有用处）
                userListParam: [],           // 企微用户ID数组 (用于前端显示和回显)
                departmentListParam: [],     // 部门ID数组
                qwUserTableIdList: [],       // 本地数据库ID数组 (需要传给后端保存)
                userList: '',                // 完整的JSON字符串 (包含userList)

                // 优先分配相关
                priorityUserListParam: [],   // 优先分配的企微用户ID数组
                priorityDepartmentListParam: [], // 优先分配的部门ID数组
                priorityUserList: '',        // 优先分配的JSON字符串

                // 选中的ID（用于el-select绑定）
                selectedUserIds: []          // 与qwUserTableIdList同步，用于前端选择框显示
            },
            spareUserIds:[],
            userLimitJson:[],
            // 表单校验
            rules: {
                linkName: [
                    { required: true, message: '链接名称不能为空', trigger: 'blur' }
                ]
            },
            // 企业主体相关
            corpOptions: [],
            corpMap: new Map(),
            // 企微用户相关
            qwUserOptions: [],
            searchKeyword: '',
            userPage: 1,
            userPageSize: 20,
            userTotal: 0,
            hasMoreUsers: true,
            initialLoaded: false,
            // 基础域名
            baseDomain: 'https://c.ysyd.top'
        }
    },
    computed: {
        getUserSelectPlaceholder() {
            if (!this.queryParams.corpId) {
                return '请先在搜索栏选择主体'
            }
            return '请输入成员姓名进行搜索，或直接下拉选择'
        }
    },
    created() {
        this.getCorpList().then(() => {
            // 默认选中第一个主体
            if (this.corpOptions && this.corpOptions.length > 0) {
                this.queryParams.corpId = this.corpOptions[0].corpId
                this.getList() // 获取列表数据
            } else {
                this.msgWarning('请先配置企业主体')
            }
        })
    },
    methods: {


        /**
         * 下载获客链接创建模板
         */
        downloadTemplate() {
            // 指向 public 目录下的模板文件
            const templateUrl = '/template/acquisition_link_template.xls';

            // 创建一个隐藏的 a 标签用于下载
            const link = document.createElement('a');
            link.style.display = 'none';
            link.href = templateUrl;

            // 设置下载的文件名
            link.download = '手机号生成短链模板.xls';

            // 将链接添加到DOM中，触发点击，然后移除
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },
        /** 提取链接按钮操作 */
        handleExtractLink(row) {
            // 重置表单数据
            this.extractLinkDialog = {
                visible: true,
                loading: false,
                phone: '',
                rowData: row,
                resultText: ''
            }
        },

        handleExtractLinkNol(row){
            extractLinkNol({
                id: row.id,
                url: row.url
            }).then(response => {
                if (response.code === 200) {
                    // 修改这里：使用 response.msg 而不是 response.data
                    this.extractLinkDialogNol.visible = true
                    this.extractLinkDialogNol.shortLink = response.shortLink
                    this.extractLinkDialogNol.linkPlus = response.linkPlus
                    this.$message.success('短链接生成成功')
                } else {
                    this.$message.error(response.msg || '生成失败')
                }
            }).catch(error => {
                const errorMsg = error.response?.data?.msg || error.message || '生成失败'
                this.$message.error(errorMsg)
            }).finally(() => {
                this.extractLinkDialogNol.loading = false
            })
        },

        /** 确认提取链接 */
        confirmExtractLink() {
            // 验证手机号码
            const phone = this.extractLinkDialog.phone.trim()
            if (!phone) {
                this.$message.warning('请输入手机号码')
                return
            }

            // 验证手机号码格式
            const phoneRegex = /^1[3-9]\d{9}$/
            if (!phoneRegex.test(phone)) {
                this.$message.warning('请输入正确的11位手机号码')
                return
            }

            // 发送请求
            this.extractLinkDialog.loading = true

            extractLink({
                id: this.extractLinkDialog.rowData.id,
                phone: phone,
                url: this.extractLinkDialog.rowData.url
            }).then(response => {
                if (response.code === 200) {
                    // 修改这里：使用 response.msg 而不是 response.data
                    this.extractLinkDialog.resultText = response.msg
                    this.$message.success('短链接生成成功')
                } else {
                    this.$message.error(response.msg || '生成失败')
                }
            }).catch(error => {
                const errorMsg = error.response?.data?.msg || error.message || '生成失败'
                this.$message.error(errorMsg)
            }).finally(() => {
                this.extractLinkDialog.loading = false
            })
        },

        /** 复制提取的链接文本 */
        copyExtractResult() {
            if (!this.extractLinkDialog.resultText) return

            this.copyToClipboard(this.extractLinkDialog.resultText, '文本已复制到剪贴板')
        },

        /** 复制提取的链接文本 */
        copyExtractResultNol() {
            if (!this.extractLinkDialogNol.shortLink) return

            this.copyToClipboard(this.extractLinkDialogNol.shortLink, '文本已复制到剪贴板')
        },

        copyExtractResultNolLong() {
            if (!this.extractLinkDialogNol.linkPlus) return

            this.copyToClipboard(this.extractLinkDialogNol.linkPlus, '文本已复制到剪贴板')
        },

        /** 关闭提取链接弹窗 */
        closeExtractLinkDialog() {
            this.extractLinkDialog.visible = false
            this.extractLinkDialog.phone = ''
            this.extractLinkDialog.resultText = ''
        },

        closeExtractLinkDialogNol() {
            this.extractLinkDialogNol.visible = false
            this.extractLinkDialogNol.linkPlus = ''
            this.extractLinkDialogNol.shortLink = ''
        },
        /** 获取完整链接 */
        getFullUrl(row) {
            if (!row || !row.pageParam) return `${this.baseDomain}`
            return `${this.baseDomain}/${row.pageParam}`
        },
        /** 复制到剪贴板的通用方法 */
        copyToClipboard(text, successMessage) {
            // 创建临时输入框
            const textarea = document.createElement('textarea')
            textarea.value = text
            textarea.style.position = 'fixed'
            textarea.style.opacity = '0'
            document.body.appendChild(textarea)
            textarea.select()

            try {
                const successful = document.execCommand('copy')
                if (successful) {
                    this.$message({
                        message: successMessage || '复制成功',
                        type: 'success',
                        duration: 2000
                    })
                } else {
                    this.$message.error('复制失败，请手动复制')
                }
            } catch (err) {
                this.$message.error('复制失败，请手动复制')
            } finally {
                document.body.removeChild(textarea)
            }
        },

        /** 生成二维码 - 使用项目自带的QRCode库 */
        handleGenerateQRCode(row) {
            if (!row || !row.pageParam) {
                this.$message.warning('该链接没有pageParam参数，无法生成二维码')
                return
            }

            const fullUrl = this.getFullUrl(row)

            // 显示二维码弹窗，并显示加载中
            this.qrCodeDialog.visible = true
            this.qrCodeDialog.generating = true
            this.qrCodeDialog.dataUrl = null
            this.qrCodeDialog.fullUrl = fullUrl
            this.qrCodeDialog.linkName = row.linkName || '-'
            this.qrCodeDialog.linkId = row.linkId || '-'
            this.qrCodeDialog.pageParam = row.pageParam || '-'
            this.qrCodeDialog.rowData = row

            try {
                // 使用 setTimeout 让UI能够更新加载状态
                setTimeout(() => {
                    // 创建一个临时容器来生成二维码
                    const tempDiv = document.createElement('div')
                    tempDiv.style.position = 'absolute'
                    tempDiv.style.left = '-9999px'
                    tempDiv.style.top = '-9999px'
                    document.body.appendChild(tempDiv)

                    try {
                        // 使用项目自带的 QRCode 库生成二维码
                        const qrcode = new QRCode(tempDiv, {
                            text: fullUrl,
                            width: 300,
                            height: 300,
                            colorDark: '#000000',
                            colorLight: '#ffffff',
                            correctLevel: QRCode.CorrectLevel.H // 使用高容错率
                        })

                        // 等待二维码生成
                        setTimeout(() => {
                            try {
                                // 从临时容器中获取生成的 canvas 或 img 元素
                                const canvas = tempDiv.querySelector('canvas')
                                if (canvas) {
                                    // 转换为 data URL
                                    this.qrCodeDialog.dataUrl = canvas.toDataURL('image/png')
                                } else {
                                    this.$message.warning('二维码生成方式不支持保存为图片，请更新浏览器')
                                }
                            } catch (err) {
                                this.$message.error('生成二维码失败')
                            } finally {
                                // 清理临时容器
                                document.body.removeChild(tempDiv)
                                this.qrCodeDialog.generating = false
                            }
                        }, 100)
                    } catch (err) {
                        this.$message.error('生成二维码失败')
                        document.body.removeChild(tempDiv)
                        this.qrCodeDialog.generating = false
                    }
                }, 50)
            } catch (error) {
                this.$message.error('生成二维码失败')
                this.qrCodeDialog.generating = false
            }
        },

        /** 下载二维码 */
        downloadQRCode() {
            if (!this.qrCodeDialog.dataUrl) return

            // 创建下载链接
            const link = document.createElement('a')
            link.href = this.qrCodeDialog.dataUrl
            link.download = `qrcode_${this.qrCodeDialog.linkId || 'link'}_${Date.now()}.png`
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)

            this.$message.success('二维码已开始下载')
        },

        /** 二维码弹窗关闭后的处理 */
        handleQrCodeDialogClosed() {
        },

        /** 发送短信按钮操作 */
        handleSendSms(row) {
            // 重置表单数据
            this.smsDialog = {
                visible: true,
                sending: false,
                phone: '',
                linkId: row.id,
                linkName: row.linkName,
                fullUrl: this.getFullUrl(row),
                rowData: row
            }
        },

        /** 确认发送短信 */
        confirmSendSms() {
            // 验证手机号码
            const phone = this.smsDialog.phone.trim()
            if (!phone) {
                this.$message.warning('请输入手机号码')
                return
            }

            // 验证手机号码格式
            const phoneRegex = /^1[3-9]\d{9}$/
            if (!phoneRegex.test(phone)) {
                this.$message.warning('请输入正确的11位手机号码')
                return
            }

            // 发送请求
            this.smsDialog.sending = true

            sendMessageLink(this.smsDialog.linkId, phone)
                .then(response => {
                    this.$message.success('短信发送成功')
                    this.smsDialog.visible = false
                })
                .catch(error => {
                    const errorMsg = error.response?.data?.msg || error.message || '发送失败'
                    this.$message.error(errorMsg)
                })
                .finally(() => {
                    this.smsDialog.sending = false
                })
        },

        /** 短信弹窗关闭后的处理 */
        handleSmsDialogClose() {
            this.smsDialog.phone = ''
            this.smsDialog.sending = false
        },

        /** 格式化时间 */
        parseTime(time, pattern) {
            if (arguments.length === 0 || !time) {
                return '-'
            }
            const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
            let date
            if (typeof time === 'object') {
                date = time
            } else {
                if ((typeof time === 'string')) {
                    if ((/^[0-9]+$/.test(time))) {
                        // 如果是纯数字字符串，转为数字
                        time = parseInt(time)
                    } else {
                        // 处理 "2026-03-19T14:05:41.000+0800" 格式
                        time = time.replace(/-/g, '/') // 将 ISO 格式转换为兼容格式
                    }
                }
                if ((typeof time === 'number') && (time.toString().length === 10)) {
                    time = time * 1000
                }
                date = new Date(time)
            }

            // 如果日期无效
            if (isNaN(date.getTime())) {
                return '-'
            }

            const formatObj = {
                y: date.getFullYear(),
                m: date.getMonth() + 1,
                d: date.getDate(),
                h: date.getHours(),
                i: date.getMinutes(),
                s: date.getSeconds(),
                a: date.getDay()
            }
            const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
                const value = formatObj[key]
                // 补零
                if (key === 'y') {
                    return value.toString()
                }
                return ('00' + value).substr(-2)
            })
            return timeStr
        },
        /** 处理用户选择变化 - 同步更新所有相关字段 */
        handleUserSelectionChange(selectedIds) {

            // 1. 更新 qwUserTableIdList（需要传给后端的本地ID）
            this.form.qwUserTableIdList = [...selectedIds]

            // 2. 根据选中的本地ID，找到对应的企微用户ID，更新 userListParam
            const qwUserIds = []
            selectedIds.forEach(id => {
                const user = this.qwUserOptions.find(u => u.id === id)
                if (user) {
                    qwUserIds.push(user.qwUserId)
                }
            })
            this.form.userListParam = qwUserIds

            // 3. 构建完整的 userList JSON（包含用户ID和部门ID）
            const userListData = {
                userList: qwUserIds,                    // 企微用户ID列表
                departmentList: this.form.departmentListParam || [], // 部门ID列表
                userIds: selectedIds,                    // 本地数据库ID列表
                updateTime: new Date().getTime()
            }
            this.form.userList = JSON.stringify(userListData)

            // 4. 更新 userLimitJson，确保与当前选择的用户同步
            // 先移除不在当前选择中的用户限制
            this.userLimitJson = this.userLimitJson.filter(limitItem =>
                this.form.qwUserTableIdList.includes(limitItem.qwUserId)
            )

            // 再添加新选择用户的默认限制（如果不存在）
            this.form.qwUserTableIdList.forEach((localId) => {
                if (!this.userLimitJson.find(item => item.qwUserId === localId)) {
                    // 从 qwUserOptions 中找到对应的用户，获取企微用户ID
                    const user = this.qwUserOptions.find(u => u.id === localId)
                    this.userLimitJson.push({
                        qwUserId: localId,                          // 本地数据库ID
                        userId: user ? user.qwUserId : '',    // 企微用户ID
                        limitCount: 100
                    })
                }
            })

            // console.log("userLimitJson",this.userLimitJson)
            // console.log("this.qwUserOptions",this.qwUserOptions)
            // console.log(" this.form.selectedUserIds", this.form.selectedUserIds)
            // console.log('更新后的数据:', {
            //   qwUserTableIdList: this.form.qwUserTableIdList,
            //   userListParam: this.form.userListParam,
            //   departmentListParam: this.form.departmentListParam,
            //   userList: this.form.userList
            // })
        },
        /** 检查是否已选择主体 */
        checkCorpId() {
            if (!this.queryParams.corpId) {
                this.msgError('请先在搜索栏选择主体')
                return false
            }
            return true
        },

        /** 查询列表 */
        getList() {
            if (!this.checkCorpId()) {
                this.loading = false
                return
            }

            this.loading = true
            const params = { ...this.queryParams }
            listAssistant(params).then(response => {
                this.assistantList = response.rows
                this.total = response.total
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        },

        /** 获取企业主体列表 */
        getCorpList() {
            return qwUserCompanyList({ status: 1 }).then(response => {
                this.corpOptions = response.data || []
                // 创建Map方便根据corpId获取corpName
                this.corpMap.clear()
                this.corpOptions.forEach(item => {
                    this.corpMap.set(item.corpId, item.corpName)
                })
            })
        },

        /** 根据corpId获取企业名称 */
        getCorpName(corpId) {
            return this.corpMap.get(corpId) || corpId
        },

        /** 切换主体时的处理 */
        handleCorpChange(corpId) {

            // 重置用户相关数据
            this.qwUserOptions = []
            this.initialLoaded = false
            this.userPage = 1
            this.hasMoreUsers = true
            this.searchKeyword = ''

            // 如果有关联成员选择框打开，清空已选成员
            if (this.form.userListParam) {
                this.form.userListParam = []
            }

            if (corpId) {
                // 重新查询列表
                this.queryParams.pageNum = 1
                this.getList()
                // 预加载用户数据
                this.loadUsersByCorp()
            } else {
                // 如果没有选择主体，清空列表
                this.assistantList = []
                this.total = 0
            }
        },

        /** 根据当前选择的主体加载用户 */
        loadUsersByCorp() {
            if (!this.checkCorpId()) return

            const corpId = this.queryParams.corpId

            // 重置分页和数据
            this.userPage = 1
            this.qwUserOptions = []
            this.initialLoaded = false
            this.searchKeyword = ''

            // 调用搜索方法，传入空字符串加载所有用户
            this.searchQwUsers('')
        },

        /** 搜索企微用户 - POST请求 */
        searchQwUsers(query) {
            if (!this.checkCorpId()) {
                this.userLoading = false
                return
            }

            if (query !== undefined) {
                this.searchKeyword = query
                this.userPage = 1
            }

            if (!this.searchKeyword && this.initialLoaded) {
                return
            }

            this.userLoading = true

            const params = {
                qwUserName: this.searchKeyword || '',
                pageNum: this.userPage,
                pageSize: this.userPageSize,
                corpId: this.queryParams.corpId
            }

            getQwUserList(params).then(response => {

                let newUsers = []
                if (response.data && Array.isArray(response.data)) {
                    newUsers = response.data
                } else if (response.rows && Array.isArray(response.rows)) {
                    newUsers = response.rows
                } else if (Array.isArray(response)) {
                    newUsers = response
                }

                // 处理返回的用户数据，确保包含id字段
                newUsers = newUsers.map(user => ({
                    ...user,
                    // 确保有唯一标识
                    uniqueKey: `${user.qwUserId}_${user.corpId}`,
                    // 确保有id字段（本地数据库ID）
                    id: user.id || user.userId || null
                }))

                if (this.userPage === 1) {
                    this.qwUserOptions = newUsers
                } else {
                    const existingKeys = new Set(
                        this.qwUserOptions.map(u => `${u.qwUserId}_${u.corpId}`)
                    )
                    const uniqueNewUsers = newUsers.filter(u =>
                        !existingKeys.has(`${u.qwUserId}_${u.corpId}`)
                    )
                    this.qwUserOptions = [...this.qwUserOptions, ...uniqueNewUsers]
                }

                if (response.total !== undefined) {
                    this.userTotal = response.total
                } else if (response.data && response.data.total) {
                    this.userTotal = response.data.total
                } else {
                    this.userTotal = this.qwUserOptions.length
                }

                this.hasMoreUsers = this.qwUserOptions.length < this.userTotal

                if (this.userPage === 1) {
                    this.initialLoaded = true
                }

                this.userLoading = false
                this.loadingMore = false
            }).catch(error => {
                this.userLoading = false
                this.loadingMore = false
            })
        },

        /** 处理选择器显隐变化 */
        handleSelectVisible(visible) {
            if (visible && this.queryParams.corpId) {
                if (!this.initialLoaded || this.qwUserOptions.length === 0) {
                    this.loadUsersByCorp()
                }
            }
        },

        /** 加载更多用户 */
        loadMoreUsers() {
            if (this.loadingMore || !this.hasMoreUsers) return

            this.loadingMore = true
            this.userPage++
            this.searchQwUsers(this.searchKeyword)
        },

        /** 清空已选用户 */
        clearSelectedUsers() {
            this.form.selectedUserIds = []
            this.form.qwUserTableIdList = []
            this.form.userListParam = []
            //部门列表可能不需要清空，根据业务需求决定
            // this.form.departmentListParam = []
            this.form.userList = JSON.stringify({
                userList: [],
                departmentList: this.form.departmentListParam || [],
                userIds: [],
                updateTime: new Date().getTime()
            })
        },

        /** 加载已选中用户的详细信息 */
        loadSelectedUsers(userIds) {
            if (!userIds || userIds.length === 0) return

            getQwUserListByIds(userIds).then(response => {
                const selectedUsers = response.data || []

                selectedUsers.forEach(user => {
                    const exists = this.qwUserOptions.some(opt =>
                        opt.qwUserId === user.qwUserId && opt.corpId === user.corpId
                    )
                    if (!exists) {
                        this.qwUserOptions.push(user)
                    }
                })
            })
        },
        /** 格式化详情页面的成员显示（不显示部门） */
        formatDetailMembers(localIds) {

            if (!localIds || !localIds.length) return '-'

            const memberNames = []
            localIds.forEach(id => {
                // 通过本地数据库ID查找用户
                const user = this.qwUserOptions.find(u => u.id === id)
                if (user) {
                    // 显示用户名和企微ID，不显示部门
                    memberNames.push(`${user.qwUserName}[${user.qwUserId}]`)
                } else {
                    // 如果找不到，显示原始ID
                    memberNames.push(`ID:${id}`)
                }
            })

            return memberNames.join(', ')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            if (!this.checkCorpId()) return
            this.queryParams.pageNum = 1
            this.getList()
        },

        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            // 重置时保留主体选择
            const currentCorpId = this.queryParams.corpId
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                linkName: '',
                linkId: '',
                status: '',
                corpId: currentCorpId
            }
            this.handleQuery()
        },

        /** 多选框选中数据 */
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        /** 新增按钮操作 */
        handleAdd() {
            if (!this.checkCorpId()) return

            this.reset()
            this.open = true
            this.title = '添加获客链接'

            // 新增时添加关联成员必填校验
            this.rules.selectedUserIds = [
                { required: true, message: '请选择关联成员', trigger: 'change' }
            ]

            // 如果表单已渲染，需要重新设置校验规则
            this.$nextTick(() => {
                if (this.$refs.form) {
                    this.$refs.form.clearValidate()
                }
            })

            // 预加载用户数据
            this.loadUsersByCorp()
        },

        /** 修改按钮操作 */
        handleUpdate(row) {
            if (!this.checkCorpId()) return

            this.reset()

            // 先查询详情
            getDetailByLinkId(row.linkId).then(response => {
                const data = response.data

                // 基础信息赋值
                this.form.id = data.id
                this.form.linkId = data.linkId
                this.form.linkName = data.linkName
                //将字符串的"true"/"false"转换为布尔值
                this.form.skipVerify = data.skipVerify === true || data.skipVerify === 'true'
                this.form.priorityType = data.priorityType
                this.form.remark = data.remark
                this.form.corpId = data.corpId

                // ========== 关联成员相关字段回显 ==========

                if(data.userLimitJson!=null){
                    this.userLimitJson=JSON.parse(data.userLimitJson)
                }else{ this.userLimitJson=[]}

                if(data.spareUserIds!=null){
                    this.spareUserIds=JSON.parse(data.spareUserIds)
                }else{ this.spareUserIds=[]}

                // 1. 处理 qwUserTableIdList（本地数据库ID）
                if (data.qwUserTableIdList) {
                    if (typeof data.qwUserTableIdList === 'string') {
                        try {
                            // 处理类似 "[28462]" 的字符串
                            const parsed = JSON.parse(data.qwUserTableIdList)
                            this.form.qwUserTableIdList = Array.isArray(parsed) ? parsed : [parsed]
                        } catch (e) {
                            // 如果不是标准JSON格式，尝试按逗号分割
                            this.form.qwUserTableIdList = data.qwUserTableIdList
                                .replace(/[\[\]"]/g, '')  // 去除方括号和引号
                                .split(',')
                                .filter(id => id.trim())
                                .map(id => parseInt(id.trim()))
                        }
                    } else if (Array.isArray(data.qwUserTableIdList)) {
                        this.form.qwUserTableIdList = data.qwUserTableIdList
                    }
                }

                // 2. 处理 userListParam（企微用户ID）- 从 userList 字段获取
                if (data.userList) {
                    if (typeof data.userList === 'string') {
                        try {
                            const parsed = JSON.parse(data.userList)
                            // 检查 parsed 是否包含 userList 字段
                            if (parsed && parsed.userList && Array.isArray(parsed.userList)) {
                                this.form.userListParam = parsed.userList
                            } else if (Array.isArray(parsed)) {
                                this.form.userListParam = parsed
                            } else {
                                this.form.userListParam = []
                            }
                        } catch (e) {
                            this.form.userListParam = []
                        }
                    } else if (Array.isArray(data.userList)) {
                        this.form.userListParam = data.userList
                    } else if (data.userList && data.userList.userList) {
                        // 处理已经是对象的情况
                        this.form.userListParam = data.userList.userList
                    }
                }

                // 3. 处理 departmentListParam（部门ID）
                if (data.departmentList) {
                    if (typeof data.departmentList === 'string') {
                        try {
                            const parsed = JSON.parse(data.departmentList)
                            this.form.departmentListParam = Array.isArray(parsed) ? parsed : []
                        } catch (e) {
                            this.form.departmentListParam = []
                        }
                    } else if (Array.isArray(data.departmentList)) {
                        this.form.departmentListParam = data.departmentList
                    }
                }

                // ========== 优先分配相关字段回显 ==========

                // 4. 处理 priorityUserListParam（优先分配的企微用户ID）
                if (data.priorityUserList) {
                    if (typeof data.priorityUserList === 'string') {
                        try {
                            const parsed = JSON.parse(data.priorityUserList)
                            this.form.priorityUserListParam = Array.isArray(parsed) ? parsed : []
                        } catch (e) {
                            this.form.priorityUserListParam = []
                        }
                    } else if (Array.isArray(data.priorityUserList)) {
                        this.form.priorityUserListParam = data.priorityUserList
                    }
                }

                // 5. 设置 selectedUserIds 用于前端显示（与 qwUserTableIdList 同步）
                this.form.selectedUserIds = [...(this.form.qwUserTableIdList || [])]


                // 加载该主体的用户
                this.loadUsersByCorp()

                // 如果有已选用户，加载他们的详细信息用于显示
                if (this.form.selectedUserIds && this.form.selectedUserIds.length > 0) {
                    this.loadSelectedUsers(this.form.selectedUserIds)
                }

                this.open = true
                this.title = '修改获客链接'
            }).catch(error => {
                this.msgError('获取详情失败')
            })
        },

        /** 详情按钮操作 */
        handleDetail(row) {
            getDetailByLinkId(row.linkId).then(response => {
                const data = response.data
                this.detailData = { ...data }

                if(data.spareUserIds!=null){
                    this.detailData.spareUserIds=JSON.parse(data.spareUserIds)
                }else{ this.detailData.spareUserIds=[]
                }

                // 解析qwUserTableIdList
                if (data.qwUserTableIdList) {
                    if (typeof data.qwUserTableIdList === 'string') {
                        try {
                            this.detailData.qwUserTableIdList = JSON.parse(data.qwUserTableIdList)
                        } catch (e) {
                            this.detailData.qwUserTableIdList = []
                        }
                    } else {
                        this.detailData.qwUserTableIdList = data.qwUserTableIdList || []
                    }
                }

                // 解析userList
                if (data.userList) {
                    try {
                        this.detailData.userListObj = JSON.parse(data.userList)
                    } catch (e) {
                        this.detailData.userListObj = {}
                    }
                }

                // 解析priorityUserList
                if (data.priorityUserList) {
                    try {
                        this.detailData.priorityUserListParam = JSON.parse(data.priorityUserList)
                    } catch (e) {
                        this.detailData.priorityUserListParam = []
                    }
                }

                this.detailOpen = true
            })
        },

        /** 提交按钮 */
        submitForm() {
            if (!this.checkCorpId()) return
            this.$refs['form'].validate(valid => {
                if (valid) {
                    // 验证关联成员是否超过500
                    if (this.form.selectedUserIds && this.form.selectedUserIds.length > 500) {
                        this.msgError('关联成员最多只能选择500人')
                        return
                    }

                    // 构建提交的数据
                    const submitData = {
                        // 基础信息
                        id: this.form.id,
                        linkId: this.form.linkId,
                        linkName: this.form.linkName,
                        skipVerify: this.form.skipVerify, // 布尔值，提交时保持布尔类型
                        priorityType: this.form.priorityType,
                        remark: this.form.remark,
                        corpId: this.queryParams.corpId,

                        // ========== 关联成员相关 ==========
                        // 本地数据库ID列表 - 转换为JSON字符串
                        qwUserTableIdList: JSON.stringify(this.form.selectedUserIds || []),

                        // 企微用户ID列表 - 转换为JSON字符串，与后端期望的格式一致
                        userList: JSON.stringify(this.form.userListParam || []),

                        // 部门ID列表
                        departmentList: JSON.stringify(this.form.departmentListParam || []),

                        // ========== 优先分配相关 ==========
                        priorityUserList: JSON.stringify(this.form.priorityUserListParam || []),

                        userListParam: this.form.userListParam || [],
                        departmentListParam: this.form.departmentListParam || [],
                        priorityUserListParam: this.form.priorityUserListParam || [],
                        userLimitJson:JSON.stringify(this.userLimitJson || []),
                        spareUserIds:JSON.stringify(this.spareUserIds || [])
                    }

                    if (this.form.id) {
                        updateAssistant(submitData).then(response => {
                            this.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        }).catch(error => {
                            console.error('修改失败:', error)
                        })
                    } else {
                        addAssistant(submitData).then(response => {
                            this.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        }).catch(error => {
                            console.error('新增失败:', error)
                        })
                    }
                }
            })
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            if (!this.checkCorpId()) return

            const ids = row.id || this.ids.join(',')
            this.$confirm('是否确认删除获客链接编号为"' + ids + '"的数据项？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                return deleteAssistant(ids)
            }).then(() => {
                this.getList()
                this.msgSuccess('删除成功')
            })
        },

        /** 取消按钮 */
        cancel() {
            this.open = false
            this.reset()
        },

        /** 表单重置 */
        reset() {
            this.form = {
                // 基础信息
                linkId: '',
                linkName: '',
                skipVerify: true,
                priorityType: 0,
                remark: '',
                corpId: this.queryParams.corpId,
                id: null,

                // 关联成员相关
                userListParam: [],           // 企微用户ID
                departmentListParam: [],     // 部门ID
                qwUserTableIdList: [],       // 本地数据库ID
                userList: '{"userList":[],"departmentList":[],"userIds":[]}', // 完整JSON
                userLimitJson: null,
                spareUserIds: null,
                // 优先分配相关
                priorityUserListParam: [],   // 优先分配的企微用户ID
                priorityDepartmentListParam: [], // 优先分配的部门ID
                priorityUserList: '[]',      // 优先分配JSON

                // 选中的ID（用于el-select绑定）
                selectedUserIds: []

            }
            this.spareUserIds=[];
            this.userLimitJson=[];
            this.searchKeyword = ''
            this.userPage = 1
            this.hasMoreUsers = true
            this.resetForm('form')
        },
        /**
         * 处理导入电话号码按钮点击事件
         */
        /**
         * 处理导入电话号码按钮点击事件
         */
        handleUploadPhones(row) {
            // 先重置上传组件的文件列表
            this.$nextTick(() => {
                if (this.$refs.upload) {
                    // 清空上传组件的文件列表
                    this.$refs.upload.clearFiles()
                    // 重置上传组件的内部状态
                    this.$refs.upload.uploadFiles = []
                }
            })

            this.uploadPhoneDialog.rowData = row
            this.uploadPhoneDialog.visible = true
            // 重置加载状态，防止上次上传的loading状态残留
            this.uploadPhoneDialog.loading = false
        },
        /**
         * 关闭导入电话号码弹窗
         */
        closeUploadPhoneDialog() {
            // 清空上传组件的文件列表
            if (this.$refs.upload) {
                this.$refs.upload.clearFiles()
                this.$refs.upload.uploadFiles = []
            }
            this.uploadPhoneDialog.visible = false
            this.uploadPhoneDialog.loading = false
            this.uploadPhoneDialog.rowData = null
        },

        /**
         * 自定义上传方法，供 el-upload 调用
         */
        handleHttpRequest(options) {
            this.uploadFile(options);
        },

        /**
         * 上传文件到后端
         */
        async uploadFile(file) {
            // 1. 构建FormData对象
            const formData = new FormData();
            formData.append('file', file.file);
            formData.append('qwAcquisitionAssistantId', this.uploadPhoneDialog.rowData.id);
            formData.append('qwAcquisitionAssistantUrl', this.uploadPhoneDialog.rowData.url);

            this.uploadPhoneDialog.loading = true;

            try {
                const response = await batchCreateMessageLink(formData);
                if (response.code === 200) {
                    this.$message.success(response.msg || '生成短链成功！');
                    // 上传成功后关闭弹窗并清理
                    this.closeUploadPhoneDialog();
                } else {
                    this.$message.error(response.msg || '操作失败');
                    // 上传失败不清空文件，但关闭加载状态
                    this.uploadPhoneDialog.loading = false;
                }
            } catch (error) {
                console.error('上传文件请求失败:', error);
                this.$message.error(error.message || '上传失败，请稍后重试');
                this.uploadPhoneDialog.loading = false;
            }
        },

        /**
         * 上传文件前的钩子函数，可以做校验
         */
        beforeUpload(file) {
            const isXLS = file.type === 'application/vnd.ms-excel';
            const isXLSAlt = file.name.toLowerCase().endsWith('.xls'); // 有些浏览器可能检测不到MIME类型

            if (!isXLS && !isXLSAlt) {
                this.$message.error('上传文件只能是 .xls 格式!');
                return false;
            }
            return true; // 返回true才继续上传
        },

        /**
         * 上传成功后的回调
         */
        handleUploadSuccess(response, file, fileList) {
        },

        /**
         * 上传失败后的回调
         */
        handleUploadError(error, file, fileList) {
            console.error('文件上传失败:', error);
        },
        /**
         * 文件状态改变时的钩子，添加文件、上传成功和失败都会被调用
         * @param {Object} file - 文件对象
         * @param {Array} fileList - 文件列表
         */
        handleFileChange(file, fileList) {
        },

        /**
         * 文件超出个数限制时的钩子
         */
        handleExceed(files, fileList) {
            this.$message.warning(`最多只能上传 1 个文件！`);
            console.warn('文件数量超出限制，当前文件:', files, '文件列表:', fileList);
        },
        /** 开始上传按钮点击事件 */
        startUpload() {
            // 获取 el-upload 组件实例
            const uploadComponent = this.$refs.upload;
            if (uploadComponent) {
                // 如果有文件队列，开始上传
                if (uploadComponent.uploadFiles && uploadComponent.uploadFiles.length > 0) {
                    uploadComponent.submit();
                } else {
                    this.$message.warning('请先选择要上传的文件');
                }
            } else {
                this.$message.warning('请先选择要上传的文件');
            }
        },
        /** iPad获客链接加好友按钮操作 */
        handleIpadBlindAdd(row) {
            // 重置弹窗数据
            this.ipadBlindAddDialog = {
                visible: true,
                loading: false,
                phone: '',
                selectedUserId: null,
                memberList: [],
                rowData: row
            }

            // 获取该链接关联的成员列表
            this.loadLinkMembers(row)
        },

        /** 加载链接关联的成员列表 */
        loadLinkMembers(row) {
            // 解析成员ID列表
            let memberIds = []

            if (row.qwUserTableIdList) {
                if (typeof row.qwUserTableIdList === 'string') {
                    try {
                        // 处理类似 "[28462]" 的字符串
                        const parsed = JSON.parse(row.qwUserTableIdList)
                        memberIds = Array.isArray(parsed) ? parsed : [parsed]
                    } catch (e) {
                        // 如果不是标准JSON格式，尝试按逗号分割
                        memberIds = row.qwUserTableIdList
                            .replace(/[\[\]"]/g, '')
                            .split(',')
                            .filter(id => id.trim())
                            .map(id => parseInt(id.trim()))
                    }
                } else if (Array.isArray(row.qwUserTableIdList)) {
                    memberIds = row.qwUserTableIdList
                }
            }
            if (memberIds.length === 0) {
                this.$message.warning('该链接没有关联任何成员')
                this.ipadBlindAddDialog.visible = false
                return
            }

            // 从已加载的用户选项中查找成员信息
            const memberList = []
            memberIds.forEach(id => {
                const user = this.qwUserOptions.find(u => u.id === id)
                if (user) {
                    memberList.push(user)
                }
            })

            this.ipadBlindAddDialog.memberList = memberList

            // 如果只有一个成员，自动选中
            if (memberList.length === 1) {
                this.ipadBlindAddDialog.selectedUserId = memberList[0].id
            }

            // 如果本地没有用户数据，需要从接口获取
            if (memberList.length === 0 && memberIds.length > 0) {
                this.loadMembersFromApi(memberIds)
            }
        },

        /** 从接口加载成员信息 */
        loadMembersFromApi(memberIds) {
            this.ipadBlindAddDialog.loading = true

            getQwUserListByIds(memberIds).then(response => {
                const members = response.data || []
                this.ipadBlindAddDialog.memberList = members

                // 将加载的用户添加到全局用户选项中，方便后续使用
                members.forEach(user => {
                    const exists = this.qwUserOptions.some(opt => opt.id === user.id)
                    if (!exists) {
                        this.qwUserOptions.push(user)
                    }
                })

                // 如果只有一个成员，自动选中
                if (members.length === 1) {
                    this.ipadBlindAddDialog.selectedUserId = members[0].id
                }

                this.ipadBlindAddDialog.loading = false
            }).catch(error => {
                console.error('加载成员信息失败:', error)
                this.$message.error('加载成员信息失败')
                this.ipadBlindAddDialog.loading = false
            })
        },

        /** 确认iPad获客链接加好友 */
        confirmIpadBlindAdd() {
            // 验证手机号码
            const phone = this.ipadBlindAddDialog.phone.trim()
            if (!phone) {
                this.$message.warning('请输入手机号码')
                return
            }

            // 验证手机号码格式
            const phoneRegex = /^1[3-9]\d{9}$/
            if (!phoneRegex.test(phone)) {
                this.$message.warning('请输入正确的11位手机号码')
                return
            }

            // 验证是否选择了成员
            if (!this.ipadBlindAddDialog.selectedUserId) {
                this.$message.warning('请选择成员')
                return
            }
            // 验证是否选择了主体
            if (!this.queryParams.corpId) {
                this.$message.warning('请先在搜索栏选择主体')
                return
            }

            // 发送请求
            this.ipadBlindAddDialog.loading = true

            // 构建请求参数
            const params = {
                linkId: this.ipadBlindAddDialog.rowData.linkId,
                userId: this.ipadBlindAddDialog.selectedUserId,
                phone: phone,
                qwAcquisitionAssistantId: this.ipadBlindAddDialog.rowData.id,
                corpId: this.queryParams.corpId  //当前选中的主体ID
            }

            // 调用接口
            ipadBlindAdd(params).then(response => {
                if (response.code === 200) {
                    this.$message.success(response.msg || '添加成功')
                    this.ipadBlindAddDialog.visible = false
                } else {
                    this.$message.error(response.msg || '添加失败')
                }
            }).catch(error => {
                const errorMsg = error.response?.data?.msg || error.message || '添加失败'
                this.$message.error(errorMsg)
            }).finally(() => {
                this.ipadBlindAddDialog.loading = false
            })
        },

        /** 关闭iPad获客链接加好友弹窗 */
        closeIpadBlindAddDialog() {
            this.ipadBlindAddDialog.visible = false
            this.ipadBlindAddDialog.phone = ''
            this.ipadBlindAddDialog.selectedUserId = null
            this.ipadBlindAddDialog.memberList = []
            this.ipadBlindAddDialog.rowData = null
        },
    }
}
</script>

<style scoped>
.mb8 {
    margin-bottom: 8px;
}

.el-form-item__tips {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
}

/* 优化下拉选项的显示 */
.el-select-dropdown__item {
    height: auto;
    padding: 8px 20px;
}

.el-select-dropdown__item span {
    line-height: 1.5;
}

/* 二维码弹窗样式 */
.qr-code-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 350px;
    padding: 20px 0;
}

.qr-code-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
}

.qr-code-image {
    width: 250px;
    height: 250px;
    border: 1px solid #eee;
    padding: 10px;
    background: white;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
}

.qr-code-info {
    width: 100%;
    padding: 15px;
    background-color: #f9f9f9;
    border-radius: 4px;
    font-size: 14px;
}

.qr-code-info p {
    margin: 8px 0;
    word-break: break-all;
}

.qr-code-empty {
    width: 100%;
    display: flex;
    justify-content: center;
}

/* 导入弹窗样式 */
.upload-demo {
    text-align: center;
}
</style>
