<template>
    <div class="app-container">

        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
            <el-form-item label="会员id" prop="fsUserId">
                <el-input
                    v-model="queryParams.fsUserId"
                    @input="queryParams.fsUserId = queryParams.fsUserId.replace(/[^\d]/g, '')"
                    placeholder="请输入会员id"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="会员名称" prop="fsUserName">
                <el-input v-model="queryParams.fsUserName" placeholder="请输入会员名称" clearable size="small"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="进线时间" prop="inComTime">
                <el-date-picker clearable size="small" v-model="queryParams.inComTime" type="date"
                    value-format="yyyy-MM-dd" placeholder="选择进线时间">
                </el-date-picker>
            </el-form-item>

            <el-form-item label="标签" prop="tagIds">
                <div @click="hangleChangeTags()"
                    style="cursor: pointer; border: 1px solid #e6e6e6; background-color: white; overflow: hidden; flex-grow: 1;width: 250px">
                    <div style="min-height: 35px; max-height: 200px; overflow-y: auto;">
                        <el-tag type="success" closable :disable-transitions="false" v-for="list in this.selectTags"
                            :key="list.id" @close="handleCloseTags(list)" style="margin: 3px;">{{ list.name }}
                        </el-tag>
                    </div>
                </div>

            </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" v-if="queryParams.filterMode == 1">
            <el-col :span="1.5">
                <el-tooltip class="item" effect="dark"
                    content="此功能用于给 选中的 营期 内【所有的】客户发送消息" placement="top">
                    <el-button
                        type="warning"
                        icon="el-icon-s-promotion"
                        size="medium"
                        :disabled="multiple"
                        @click="openGroupSendMessagePage"
                    >一键群发
                    </el-button>
                </el-tooltip>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-edit" size="medium" :disabled="multiple"
                    @click="handleUpdate">批量修改客户营期</el-button>
            </el-col>
        </el-row>

        <div style="color: #999;font-size: 14px;display: flex;align-items: center;margin-bottom: 5px">
            <i class="el-icon-info"></i>
            【营期一键群发】：此功能用于给 选中的 营期 内【所有的】客户发送 消息
        </div>
        <div style="color: #999;font-size: 14px;display: flex;align-items: center;margin-bottom: 5px">
            <i class="el-icon-info"></i>
            【批量修改客户营期】：选中 相应的客户 修改到 想进的相应的营期
        </div>
        <el-table border v-loading="loading" :data="sopUserLogsInfoList" @selection-change="handleSelectionChange"
            v-if="queryParams.filterMode == 1">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="编号" align="center" prop="id" min-width="180" />
            <el-table-column label="会员id" align="center" prop="fsUserId" min-width="150"/>
            <el-table-column label="会员名称" align="center" prop="fsUserName" min-width="150"/>
            <el-table-column label="会员标签" align="center" prop="tagsName" min-width="250">
                <template slot-scope="scope">
                    <div v-for="name in (scope.row.tagsName ? scope.row.tagsName.split(',') : [])" style="display: inline;">
                        <el-tag type="success">{{ name }}</el-tag>
                    </div>
                </template>
            </el-table-column>

            <el-table-column label="进线时间" align="center" prop="createTime" min-width="180" />
            <el-table-column label="修改时间" align="center" prop="updateTime" min-width="180" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="120" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除客户营期</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.startIndex"
            :limit.sync="queryParams.pageLimit" @pagination="getList" />

        <!-- 添加或修改sopUserLogsInfo对话框 -->
        <el-dialog title="批量修改客户营期" :visible.sync="updateOpen" width="500px" height="300px" append-to-body>
            <el-form ref="updateLogsInfoFrom" :model="updateLogsInfoFrom" :rules="batchRules" label-width="120px">
                <el-form-item label="选择营期时间" prop="paramTime">
                    <el-date-picker clearable size="small" v-model="updateLogsInfoFrom.pTime" type="date"
                        value-format="yyyy-MM-dd" placeholder="选择营期时间">
                    </el-date-picker>
                </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="changeTagDialog.title" :visible.sync="changeTagDialog.open" width="1000px" custom-class="search-tag-dialog"
            append-to-body>
            <select-tag
                :tagSelected="selectTags"
                @tagSubmit="tagSubmitForm"
                @tagCancel="tagCancel"
                @tagSelection="tagSelection"
            />
        </el-dialog>

        <el-dialog title="一键群发"
            :visible.sync="groupSendMessageForm.visible" width="1000px" append-to-body :close-on-click-modal="false">
        <group-send-message
            :visible="groupSendMessageForm.visible"
            :ids="groupSendMessageForm.ids"
            :sourceType="1"
            @changeGroupSendMessageVisible="changeGroupSendMessageVisible"
        />
        </el-dialog>

    </div>
</template>

<script>
import {
    listSopUserLogsInfo,
    delSopUserLogsInfo,
    exportSopUserLogsInfo,
    sendMsgSop, batchUpdateSopUserLogsInfoToTime
} from "@/api/app/userLogsInfo";
import ImageUpload from "@/views/app/sop/info/ImageUpload";
import selectTag from "@/views/app/tagGroup/selectTag.vue";
import groupSendMessage from "@/views/app/sop/userLogsInfo/groupSendMessage.vue";

export default {
    name: "sopUserLogsInfoDetails",
    components: { ImageUpload, selectTag, groupSendMessage, },
    data() {
        return {
            groupSendMessageForm: {
                ids: [],
                visible: false,
            },
            luckyBagList: [],
            luckyBag: null,
            liveList: [],
            //上传语音的遮罩层
            voiceLoading: false,
            uploadUrl: process.env.VUE_APP_BASE_API + "/app/common/uploadOSS2",
            uploadUrlByVoice: process.env.VUE_APP_BASE_API + "/app/common/uploadOSSByHOOKVoice",
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            videoNumOptions: {
                title: '选择视频号',
                open: false,
                content: null,
                contentIndex: null,
            },
            // sopUserLogsInfo表格数据
            sopUserLogsInfoList: [],
            isSalesCallAdded: false,
            isSalesCallCustomerAdded: false,
            selectTags: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            updateOpen: false,
            // 查询参数
            queryParams: {
                startIndex: 1,
                pageLimit: 10,
                tagIds: null,
                remark: null,
                sopId: null,
                userLogsId: null,
                userIdParam: null,
                startTimeParam: null,
                fsUserId: null,
                fsUserName: null,
                inComTime: null,
                createTime: null,
                entryTime: null,
                fsUserIdStatus: null,
            },
            tagTotal: 0,

            //标签
            changeTagDialog: {
                title: "",
                open: false,
            },

            courseList: [],
            videoList: [],

            sendMsgOpen: {
                title: '一键批量群发',
                open: false,
                ids: null,
            },
            // 表单参数
            form: {},
            updateLogsInfoFrom: {},
            setting: [{ contentType: '1', value: '', }],
            msgForm: {
                videoId: null,
                courseId: null,
                courseType: null,
                userIdParam: null,
                setting: null,
                ids: null,
                sopId: null,
                startTime: null,
            },
            // 表单校验
            rules: {},
            batchRules: {
                pTime: [
                    { required: true, message: '选择的时间不能为空', trigger: 'blur' }
                ],
            },
            msgRules: {},
        };
    },
    props: {
        refreshCount: {
            default: 1,
            type: Number,
        },
        params: {
            default: {},
            type: Object,
        }
    },
    watch: {
        refreshCount: {
            handler(o, n) {
                this.getList();
            },
            immediate: true
        },
    },
    methods: {

        hangleChangeTags() {
            this.changeTagDialog.open = true;
        },
        tagSelection(group, tag) {
            if (!tag.isSelected) {
                this.selectTags = this.selectTags.filter(item => tag.id != item.id);
            } else {
                if (!this.selectTags.some(st => st.id == tag.id)) {
                    this.selectTags.push(tag);
                }
            }
            this.queryParams.tagIds = this.selectTags.map(st => st.id);
        },

        //确定选择标签
        tagSubmitForm() {
            this.updateLogsInfoFrom.pTime = null;
            this.changeTagDialog.open = false;
        },
        //取消选择标签
        tagCancel() {
            this.updateLogsInfoFrom.pTime = null;
            this.changeTagDialog.open = false;
        },

        //删除一些选择的标签
        handleCloseTags(tagItem) {
            this.selectTags = this.selectTags.filter(t => t.id != tagItem.id);
            if (this.selectTags != null && this.selectTags.length > 0) {
                // 确保 this.form.tags 是数组
                if (!this.queryParams.tagIds) {
                    this.queryParams.tagIds = []; // 如果未定义，初始化
                } else {
                    this.queryParams.tagIds = []; // 清空已有数据
                }
                // 遍历并添加 tagId
                this.selectTags.forEach(tag => {
                    if (tag.tagId) { // 确保 tagId 存在
                        this.queryParams.tagIds.push(tag.id);
                    }
                });
                this.queryParams.tagIds = this.queryParams.tagIds.join(",");
            } else {
                this.queryParams.tagIds = null;
            }
        },
        /** 查询sopUserLogsInfo列表 */
        getList() {
            this.loading = true;
            this.queryParams.sopId = this.params.sopId;
            this.queryParams.filterMode = this.params.filterMode;
            this.queryParams.userLogsId = this.params.id;
            let qp = {...this.queryParams};
            listSopUserLogsInfo(qp).then(response => {
                this.sopUserLogsInfoList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.updateOpen = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                sopId: null,
                userLogsId: null,
                externalContactId: null,
                qwUserId: null,
                corpId: null,
                externalId: null,
                fsUserId: null,
                externalUserName: null,
                createTime: null,
                crtTime: null,
                updateTime: null
            };
            this.resetForm("form");
        },


        resetSendMsgSop() {
            this.msgForm = {
                corpId: null,
                videoId: null,
                courseId: null,
                courseType: null,
                setting: null,
                ids: null,
            };
            this.resetForm("msgForm");
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.selectTags = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加客户营期";
        },

        /**
         * 一键群发
         */
        handleSendMsg() {
            this.sendMsgOpen.open = true;
            this.sendMsgOpen.ids = this.ids;
        },

        /** 修改按钮操作 */
        handleUpdate() {
            this.updateOpen = true;
        },

        // 修改后的方法：在原有的基础上增加一条消息
        processContentType13(settings) {
            const result = [];

            settings.forEach(item => {
                // 如果 contentType 是 13 且 value 不为空，则额外添加一条 contentType 为 1 的消息
                if (item.contentType == 13 && item.value && item.value.trim() !== '') {
                    // 按换行符分割内容，取第一部分
                    const contentParts = item.value.split('\n')
                        .map(part => part.trim())
                        .filter(part => part !== '');

                    if (contentParts.length > 0) {
                        // 创建一条额外的消息，使用第一部分内容
                        const additionalMessage = {
                            ...item,
                            contentType: 1, // 改为文本类型
                            value: contentParts[0]
                        };
                        result.push(additionalMessage);
                    }
                }
                if (item.contentType == 10) {
                    item.miniprogramAppid = 'wx4d225cc86cc7885d'
                }
                result.push(item);
            });

            return result;
        },

        submitMsgForm() {
            this.$refs["msgForm"].validate(valid => {
                if (valid) {

                    // 处理 contentType 13 的拆分逻辑
                    const processedSetting = this.processContentType13(this.setting);
                    console.log(processedSetting)
                    this.msgForm.setting = JSON.stringify(processedSetting);
                    this.msgForm.ids = this.ids;
                    this.msgForm.sopId = this.queryParams.sopId;
                    this.msgForm.userIdParam = this.queryParams.userIdParam;
                    this.msgForm.startTime = this.queryParams.startTimeParam;
                    this.msgForm.corpId = this.queryParams.corpIdParam;
                    this.msgForm.filterMode = this.queryParams.filterMode;

                    if (processedSetting.length <= 0) {
                        return this.$message.error("请添加规则")
                    }
                    if (this.msgForm.courseId === null || this.msgForm.courseId === '') {
                        return this.$message.error("科普不能为空")
                    }

                    if (this.msgForm.videoId === null || this.msgForm.videoId === '') {
                        return this.$message.error("课节不能为空")
                    }

                    if (this.msgForm.courseType === null || this.msgForm.courseType === '') {
                        return this.$message.error("消息类型不能为空")
                    }

                    for (let i = 0; i < processedSetting.length; i++) {
                        const item = processedSetting[i];
                        if (item.contentType == 1 && (item.value == null || item.value == "")) {
                            return this.$message.error("内容不能为空")
                        }
                        if (item.contentType == 2 && (item.imgUrl == null || item.imgUrl == "")) {
                            return this.$message.error("图片不能为空")
                        }
                        if ((item.contentType == 3 || item.contentType == 9) && (item.linkTitle == null || item.linkTitle == "")) {
                            return this.$message.error("链接标题不能为空")
                        }
                        if ((item.contentType == 3 || item.contentType == 9) && (item.linkDescribe == null || item.linkDescribe == "")) {
                            return this.$message.error("链接描述不能为空")
                        }
                        if ((item.contentType == 3 || item.contentType == 9) && (item.linkImageUrl == null || item.linkImageUrl == "")) {
                            return this.$message.error("链接图片不能为空")
                        }
                        if ((item.contentType == 3 || item.contentType == 9) && item.type == 1 && (item.linkUrl == null || item.linkUrl == "")) {
                            return this.$message.error("链接地址不能为空")
                        }
                        if ((item.contentType == 4 || item.contentType == 15) && (item.miniprogramTitle == null || item.miniprogramTitle == "")) {
                            return this.$message.error("小程序消息标题不能为空")
                        }
                        if ((item.contentType == 4 || item.contentType == 15) && (item.miniprogramPicUrl == null || item.miniprogramPicUrl == "")) {
                            return this.$message.error("小程序封面地址不能为空")
                        }
                        if (item.contentType == 5 && (item.fileUrl == null || item.fileUrl == "")) {
                            return this.$message.error("文件不能为空")
                        }
                        if (item.contentType == 6 && (item.videoUrl == null || item.videoUrl == "")) {
                            return this.$message.error("视频不能为空")
                        }
                        if (item.contentType == 7 && (item.value == null || item.value == "")) {
                            return this.$message.error("语音不能为空")
                        }
                        if (item.contentType == 14 && (item.luckyBagId == null || item.luckyBagId == "")) {
                            return this.$message.error("福袋不能为空")
                        }
                    }

                    this.sendMsgOpen.open = false;

                    const loading = this.$loading({
                        lock: true,
                        text: '正在执行中请稍后~~请不要刷新页面！！',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    sendMsgSop(this.msgForm).then(response => {
                        this.msgSuccess("一键群发成功");
                        loading.close();
                        this.setting = [];
                        this.msgForm = {
                            videoId: null,
                            courseId: null,
                            courseType: null,
                            setting: null,
                        }
                        this.getList();
                    }).finally(() => {
                        loading.close();
                    });

                }
            });
        },
        cancelMsgForm() {
            this.sendMsgOpen.open = false;
            this.resetSendMsgSop();
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["updateLogsInfoFrom"].validate(valid => {
                if (valid) {
                    this.updateLogsInfoFrom.ids = this.ids;
                    this.updateLogsInfoFrom.sopId = this.queryParams.sopId;
                    this.updateLogsInfoFrom.uTime = this.updateLogsInfoFrom.pTime;
                    let loadingRock = this.$loading({
                        lock: true,
                        text: '正在执行中请稍后~~请不要刷新页面！！',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });

                    batchUpdateSopUserLogsInfoToTime(this.updateLogsInfoFrom).then(response => {
                        this.msgSuccess("修改成功");
                        this.open = false;
                        this.updateOpen = false;
                        this.getList();
                        loadingRock.close();
                    }).finally(res => {
                        loadingRock.close();
                    })
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm('是否确认删除sopUserLogsInfo编号为"' + ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delSopUserLogsInfo(ids);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有营期数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.exportLoading = true;
                return exportSopUserLogsInfo(queryParams);
            }).then(response => {
                this.download(response.msg);
                this.exportLoading = false;
            }).catch(() => { });
        },
        //选择视频号
        hanldeSelectVideoNum(content, index) {
            this.videoNumOptions.content = content;
            this.videoNumOptions.contentIndex = index;
            this.videoNumOptions.open = true;
        },

        qwUserVideoResult(val) {

            // 根据选中的内容，将返回的数据更新到相应的表单项
            const content = this.videoNumOptions.content;
            const setList = content[this.videoNumOptions.contentIndex];
            setList.nickname = val.nickname;
            setList.avatar = val.avatar;
            setList.coverUrl = val.coverUrl;
            setList.thumbUrl = val.thumbUrl;
            setList.desc = val.desc;
            setList.url = val.url;
            setList.extras = val.extras;
            setList.videoId = val.id;

            this.videoNumOptions.open = false;

        },
        /**
         * 营期一键群发
         */
        openGroupSendMessagePage() {
            if (this.ids.length === 0) {
                return this.$message.error('请勾选具体群发记录！');
            }
            this.groupSendMessageForm.ids = this.ids;
            this.groupSendMessageForm.visible = true;
        },
        changeGroupSendMessageVisible(visible) {
            this.groupSendMessageForm.visible = visible;
        },
    }
};
</script>

<style lang="scss" scoped>

::v-deep  .search-tag-dialog {
    height: 800px !important;
    overflow: auto !important;
}

/* CSS 样式 */
.tag-container {
    display: flex;
    flex-wrap: wrap;
    /* 超出宽度时自动换行 */
    gap: 8px;
    /* 设置标签之间的间距 */
}

.name-background {
    display: inline-block;
    background-color: #abece6;
    /* 背景颜色 */
    padding: 4px 8px;
    /* 调整内边距，让背景包裹文字 */
    border-radius: 4px;
    /* 可选：设置圆角 */
}

.tag-box {
    padding: 8px 12px;
    border: 1px solid #989797;
    border-radius: 4px;
    cursor: pointer;
    display: inline-block;
}

.tag-selected {
    background-color: #00bc98;
    color: #fff;
    border-color: #00bc98;
}

.el-tag+.el-tag {
    margin-left: 10px;
}


.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>
