<template>
    <div class="user-container">
        <el-card class="search">
            <el-select-v2 style="width: 200px;margin-right: 12px;" v-model="query.robot_id" popper-class="costom-select"
                :options="robotCards" placeholder="请选择机器人" :props="v2props" filterable @change="changeRobot" clearable>
                <template #default="{ item }">
                    <div class="costom-select-item">
                        <el-image :src="item.head_url"></el-image>
                        <span>{{ item.name }}</span>
                    </div>
                </template>
                <template #footer v-if="robotTotal > 100">
                    <el-pagination v-model:current-page="queryRobot.page" :page-size="queryRobot.page_size" size="small"
                        background layout="prev, pager, next" :total="robotTotal" class="mt-4"
                        @current-change="currentChange" />
                </template>
            </el-select-v2>
            <el-input v-model="query.title" placeholder="请输入标题" style="width: 200px; margin-right: 12px;"></el-input>
            <el-select v-model="query.sop_type" style="width: 130px; margin-right: 12px;" placeholder="SOP类型"
                @change="search" clearable>
                <el-option label="基础SOP" :value="1"></el-option>
                <el-option label="客户SOP" :value="2"></el-option>
            </el-select>
            <el-select v-model="query.type" style="width: 130px; margin-right: 12px;" placeholder="类型" @change="search"
                clearable>
                <el-option label="定时任务" value="1"></el-option>
                <el-option label="手动任务" value="2"></el-option>
            </el-select>
            <el-select v-model="query.status" style="width: 130px; margin-right: 12px;" placeholder="状态"
                @change="search" clearable>
                <el-option label="禁用" value="1"></el-option>
                <el-option label="启用" value="2"></el-option>
                <el-option label="草稿" value="3"></el-option>
            </el-select>
            <el-button type="primary" icon="Search" @click="search">查询</el-button>
            <el-button type="primary" icon="Plus" @click="handleAdd" style="float: right">新增任务</el-button>
        </el-card>
        <el-card class="table-card">
            <div class="table-card-center">
                <div class="table-box">
                    <el-table :data="userTable" style="width: 100%" max-height="calc(100vh - 285px)"
                        @selection-change="handleSelectionChange">
                        <template #empty>
                            <span v-if="tableLoading">加载中...</span>
                            <span v-if="!tableLoading">暂无数据</span>
                        </template>
                        <!-- <el-table-column type="selection" width="55" /> -->
                        <el-table-column prop="title" label="机器人" min-width="150">
                            <template #default="scoped">
                                <el-image
                                    style="width: 32px; height: 32px;border-radius: 4px;margin-right: 5px;vertical-align: middle;"
                                    :src="getHeadUrl(scoped.row.robot_id)"></el-image>
                                <span style="display: inline-block; transform: translateY(2px);">{{
                                    getRobotName(scoped.row.robot_id) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="title" label="标题" min-width="140"></el-table-column>
                        <el-table-column label="概况" prop="material_type_count" min-width="190"></el-table-column>


                        <!-- <el-table-column prop="type" label="任务类型" min-width="100">
                            <template #default="scoped">
                                <sapn v-if="scoped.row.type == 1">定时任务</sapn>
                                <sapn v-if="scoped.row.type == 2">手动任务</sapn>
                            </template>
                        </el-table-column> -->
                        <!-- <el-table-column prop="robot_id" label="机器人编号">
                        </el-table-column> -->
                        <!-- <el-table-column prop="description" label="描述" /> -->
                        <!-- <el-table-column prop="status" label="状态" min-width="80">
                            <template #default="scoped">
                                <sapn v-if="scoped.row.status == 1">禁用</sapn>
                                <sapn v-if="scoped.row.status == 2">启用</sapn>
                                <sapn v-if="scoped.row.status == 3">草稿</sapn>
                            </template>
                        </el-table-column> -->

                        <!-- <el-table-column label="循环截止时间" min-width="130">
                            <template #default="scoped">
                                <span v-if="scoped.row.type == 1">
                                    {{ JSON.parse(scoped.row.spec_content).is_due == 1 ?
                                        JSON.parse(scoped.row.spec_content).expiration_time : '无' }}
                                </span>
                                <span v-else>/</span>
                            </template>
                        </el-table-column> -->


                        <!-- <el-table-column label="执行状态" align="center" min-width="80">
                            <template #default="scoped">
                                <span v-if="scoped.row.is_running == 0">未执行</span>
                                <span v-if="scoped.row.is_running == 1">执行中</span>
                            </template>
                        </el-table-column> -->
                        <el-table-column label="执行进度" align="center" width="200">
                            <template #default="scoped">
                                <div v-if="scoped.row.is_running == 1">
                                    <div style="overflow: hidden;">
                                        <span style="float: left;font-size: 12px;">已发送：{{ scoped.row.sent_number }}
                                            条</span>
                                        <span style="float: right;font-size: 12px;">总计：{{ scoped.row.total_number }}
                                            条 </span>
                                    </div>
                                    <el-progress :text-inside="true" :stroke-width="14" striped
                                        :percentage="getPercentage(scoped.row.is_running, scoped.row.sent_number, scoped.row.total_number)">
                                    </el-progress>

                                </div>
                                <span v-else> / </span>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column label="发送量总数" prop="total_number" align="center" min-width="110">
                            
                        </el-table-column>
                        <el-table-column label="已发送数量" prop="sent_number" align="center" min-width="110">
                            
                        </el-table-column> -->
                        <el-table-column label="执行详情" prop="estimated_duration" align="center" min-width="180">
                            <template #default="scoped">
                                <p style="text-align: left;font-size: 12px;">{{ scoped.row.estimated_duration }}</p>
                                <p style="text-align: left;font-size: 12px;">{{ scoped.row.estimated_end_time }}</p>
                                <span v-if="!scoped.row.estimated_duration && !scoped.row.estimated_end_time"> / </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="任务描述" min-width="150">

                            <template #default="scoped">
                                <div style="font-size: 12px;">
                                    <p>
                                        任务类型：
                                        <sapn v-if="scoped.row.type == 1">定时任务</sapn>
                                        <sapn v-if="scoped.row.type == 2">手动任务</sapn>
                                    </p>
                                    <p>
                                        SOP类型：
                                        <sapn v-if="scoped.row.sop_type == 1">基础SOP</sapn>
                                        <sapn v-if="scoped.row.sop_type == 2">客户SOP</sapn>
                                    </p>
                                    <p>
                                        任务状态：
                                        <sapn v-if="scoped.row.status == 1">禁用</sapn>
                                        <sapn v-if="scoped.row.status == 2">启用</sapn>
                                        <sapn v-if="scoped.row.status == 3">草稿</sapn>

                                    </p>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="执行时间状态" prop="next_exec_time" min-width="215">
                            <template #default="scoped">
                                <div style="font-size: 12px;">
                                    <P>
                                        执行状态：
                                        <span v-if="scoped.row.is_running == 0">未执行</span>
                                        <span v-if="scoped.row.is_running == 1">执行中</span>
                                    </P>
                                    <p>
                                        下次执行时间：
                                        <span v-if="scoped.row.type == 1">{{ scoped.row.next_exec_time ?
                                            scoped.row.next_exec_time : '无' }}</span>
                                        <span v-if="scoped.row.type == 2">/</span>
                                    </p>
                                    <P>
                                        循环截止时间：
                                        <span v-if="scoped.row.type == 1">
                                            {{ JSON.parse(scoped.row.spec_content).is_due == 1 ?
                                                JSON.parse(scoped.row.spec_content).expiration_time : '无' }}
                                        </span>
                                        <span v-else>/</span>
                                    </P>
                                </div>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column label="预计结束时间" prop="estimated_end_time" align="center" min-width="150">

                        </el-table-column> -->
                        <!-- <el-table-column prop="status" label="日志">
                            <template #default="scoped">
                                <el-link type="primary" @click="readyLog(scoped.row)">查看</el-link>

                            </template>
                        </el-table-column> -->
                        <el-table-column label="创建时间" prop="created_at" align="center"
                            min-width="130"></el-table-column>
                        <el-table-column prop="" label="操作" width="170" fixed="right" align="center">
                            <template #default="scoped">
                                <div class="mht-operations" style="font-size: 14px;text-align: right;">
                                    <el-tooltip class="box-item" effect="dark" content="执行" placement="bottom">

                                        <el-icon @click="execNew(scoped.row)"
                                            v-if="scoped.row.status == 2 && scoped.row.is_running == 0">
                                            <svg class="icon" aria-hidden="true">
                                                <use xlink:href="#icon-zhihang1"></use>
                                            </svg>
                                        </el-icon>
                                    </el-tooltip>
                                    <el-tooltip v-if="scoped.row.status == 2 && scoped.row.is_running == 1"
                                        class="box-item" effect="dark" content="停止任务" placement="bottom">

                                        <el-icon class="el-icon-danger" @click="handeleStop(scoped.row)"
                                            v-if="scoped.row.status == 2">
                                            <svg class="icon" aria-hidden="true">
                                                <use xlink:href="#icon-a-zhongzhicuowu"></use>
                                            </svg>
                                        </el-icon>
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" content="预览" placement="bottom">
                                        <el-icon @click="readyView(scoped.row)">
                                            <View />
                                        </el-icon>
                                    </el-tooltip>
                                    <el-tooltip v-if="scoped.row.sop_type == 2" class="box-item" effect="dark"
                                        content="复制" placement="bottom">
                                        <el-icon @click="handleCopy(scoped.row)">
                                            <DocumentCopy />
                                        </el-icon>
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" content="查看日志" placement="bottom">
                                        <el-icon @click="readyLog(scoped.row)">
                                            <ChatLineSquare />
                                        </el-icon>
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" content="编辑" placement="bottom">
                                        <el-icon @click="handleEdit(scoped.row)">
                                            <Edit />
                                        </el-icon>
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" content="删除" placement="bottom">
                                        <el-icon class="el-icon-danger" @click="handeleDelete(scoped.row)">
                                            <Delete />
                                        </el-icon>
                                    </el-tooltip>
                                </div>

                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="pagination-box">
                    <el-pagination v-model:current-page="query.page" v-model:page-size="query.page_size"
                        :page-sizes="[20, 30, 40, 50]" :size="query.page_size" background
                        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
        </el-card>

        <el-dialog v-model="dialogLog" title="查看日志" width="800px" align-center destroy-on-close>
            <el-table :data="logList" style="width: 100%">
                <template #empty>
                    <span v-if="tableLoading2">加载中...</span>
                    <span v-if="!tableLoading2">暂无数据</span>
                </template>
                <el-table-column prop="created_at" label="时间"></el-table-column>
                <el-table-column prop="status_text" label="状态"></el-table-column>
                <el-table-column type="expand">
                    <template #default="props">
                        <div style="padding: 20px 30px;line-height: 22px;" v-html="props.row.content"></div>
                    </template>
                </el-table-column>

            </el-table>
            <div class="pagination-box">
                <el-pagination v-model:current-page="logQuery.page" v-model:page-size="logQuery.page_size"
                    :page-sizes="[10, 20, 30, 40, 50]" :size="logQuery.page_size" background
                    layout="total, sizes, prev, pager, next, jumper" :total="logTotal"
                    @size-change="handleSizeChangeLog" @current-change="handleCurrentChangeLog" />
            </div>
        </el-dialog>
        <el-dialog v-model="dialogView" title="预览" width="950px" align-center destroy-on-close>
            <div style="padding: 0 20px;">

                <div class="materia-box">
                    <div class="user-list">
                        <el-skeleton :rows="3" animated v-if="isSkeleton" />
                        <el-scrollbar v-if="taskInfo.sop_type == 1 && !isSkeleton">
                            <span> 群聊 </span>
                            <ul class="infinite-list" style="overflow: auto; margin-bottom: 15px;">
                                <li v-for="item in groupListEd" :key="item.id" class="infinite-list-item">
                                    <span>{{ item.group_name }}</span>
                                </li>
                            </ul>
                            <span> 好友 </span>
                            <ul class="infinite-list" style="overflow: auto">
                                <li v-for="item in friendList" :key="item.user_id" class="infinite-list-item">
                                    <!-- <el-image :src="item."></el-image> -->
                                    <span>{{ item.friend_name }}</span>

                                </li>
                            </ul>
                        </el-scrollbar>
                        <div v-if="taskInfo.sop_type == 2 && !isSkeleton" style="">
                            <label v-if="sopData.rule_type == 1"
                                style="display: block;margin-bottom: 15px;color: var(--el-color-primary);">新增的用户生效</label>
                            <label v-if="sopData.rule_type == 2"
                                style="display: block;margin-bottom: 15px;color: var(--el-color-primary);">手术完毕的用户生效</label>
                            <label v-if="sopData.rule_type == 3"
                                style="display: block;margin-bottom: 15px;color: var(--el-color-primary);">
                                <span v-if="sopData.tag_type == 1">标签下所有用户生效</span>
                                <span v-if="sopData.tag_type == 2">基于打标签时间生效</span>
                            </label>
                            <div v-if="sopData.tag_type != 1" style="font-size: 12px;">
                                <span v-if="sopData.time_type == 0">当天</span>
                                <span
                                    v-if="sopData.time_type > 0 && sopData.time_type < 8">过去的第{{ sopData.time_type }}天</span>
                                <span v-if="sopData.time_type == 8">{{ sopData.start_time }} 至 {{ sopData.end_time
                                    }}</span>
                                <span v-if="sopData.time_type == 9">过去的第{{ sopData.day }}天</span>
                                &nbsp;&nbsp;
                                <span v-if="sopData.time_type != 0 && sopData.time_type != 8"> {{ time_day }} </span>
                            </div>
                            <div v-if="sopData.rule_type == 3" class="tags-box">
                                {{ sopData.tag_name }}
                                <el-tag type="primary" v-for="(item, index) in tags">
                                    <span>{{ item }} </span>
                                </el-tag>
                            </div>
                        </div>
                    </div>
                    <div class="meaasge">
                        <el-skeleton :rows="5" animated v-if="isSkeleton2" />
                        <Scripts v-if="!isSkeleton2" :disabled="true" :materiaList="materiaList"
                            :robotInfo="readyRobot">
                        </Scripts>

                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer" v-if="taskInfo.status == 2">
                    <el-button type="primary" @click="execNewView" :class="{ 'no-click': mhtLoading }"
                        style="margin-right: 20px;">
                        <el-icon v-if="mhtLoading" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon>
                        <el-icon v-else style="margin-right: 4px;">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-zhihang1"></use>
                            </svg></el-icon>

                        执 行
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogCopyTask" title="复制任务" width="550px" align-center destroy-on-close>
            <div class="dialog-box">
                <!-- <label style="display: block;margin-bottom: 15px;">将任务复制给下面的机器人</label> -->
                <el-form ref="ruleFormRef" :model="copyTask" :rules="rules">
                    <el-form-item label="将任务复制给下面的机器人" prop="robot_id">
                        <el-select-v2 style="" v-model="copyTask.robot_id" popper-class="costom-select"
                            :options="robotCardsCopy" placeholder="请选择机器人" :props="v2props" filterable
                            @change="changeRobotCopy" clearable>
                            <template #default="{ item }">
                                <div class="costom-select-item">
                                    <el-image :src="item.head_url"></el-image>
                                    <span>{{ item.name }}</span>
                                </div>
                            </template>
                            <!-- <template #footer v-if="robotTotal > 100">
                    <el-pagination v-model:current-page="queryRobot.page" :page-size="queryRobot.page_size" size="small"
                        background layout="prev, pager, next" :total="robotTotal" class="mt-4"
                        @current-change="currentChange" />
                </template> -->
                        </el-select-v2>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogCopyTask = false">取 消</el-button>
                    <el-button type="primary" @click="saveCopy" :class="{ 'no-click': mhtLoading }"
                        style="margin-right: 20px;">
                        <el-icon v-if="mhtLoading" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon>
                        <el-icon v-else style="margin-right: 4px;">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-baocun"></use>
                            </svg></el-icon>

                        保 存
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { taskList, addTask, upTask, deleteTask, execTask, taskLogs, taskGroups, taskFriends, taskMaterials, taskFriendAdd, taskMaterialsAdd, stopTask } from '@/api/task'
import { robotList } from '@/api/robot'
import { uploadFile } from '@/api/upload'
import { tagSelected } from '@/api/tags'
import robotStore from '@/store/modules/robotStore'
import { useRouter } from 'vue-router';
import detailStore from '@/store/modules/detailStore'
import addess from '@/assets/images/addess.png'
import robotDefiut from '@/assets/images/robot_1.png'
import { ElNotification } from 'element-plus'
import Scripts from '@/components/Scripts/index.vue'
const addess_png = addess
const detailInfo = detailStore()
const userRobotStore = robotStore()
const router = useRouter()
const robot_id = ref('')
const robotCards = ref([])
const query = reactive({
    title: '',
    page: 1,
    page_size: 20,
    type: '',
    status: '',
    spec: '',
    sop_type: '',
    robot_id: ''
})
const userTable = ref([])
const total = ref(0)
const ruleFormRef = ref()

const rules = ref({
    robot_id: [
        {
            required: true,
            message: '选择机器人',
            trigger: 'change',
        }
    ]
})

const tableLoading = ref(false)

let timer = null
const getTable = async () => {
    // if (!userRobotStore.robotInfo.id) {
    //     ElNotification({
    //         type: 'warning',
    //         message: '请在机器人页面选择机器人！'
    //     })
    //     return
    // }
    if (timer != null) {
        clearTimeout(timer)
        timer = null
    }
    tableLoading.value = true
    const res = await taskList(query)
    tableLoading.value = false
    userTable.value = res.list
    total.value = res.total
    if (userTable.value.some(item => item.is_running == 1)) {
        timer = setTimeout(() => {
            nextTick(() => {
                getTable()
            })
        }, 4000)
    }

}

const search = () => {
    query.page = 1
    getTable()
}

const handleSizeChange = (e) => {
    query.page = 1
    query.page_size = e
    getTable()
}
const handleCurrentChange = (e) => {
    query.page = e
    getTable()
}

const allUserlist = ref('')
const handleSend = (row) => {
    allUserlist.value = ''
    ruleForm.value = row

}

let allUser_ids = []


// 多选
const handleSelectionChange = (e) => {

    allUser_ids = e.map((el) => {
        return el.user_id
    })
}
const hideMessage = (e) => {
}
const toDetail = (e) => {
    detailInfo.taskDetails = e
    router.push('/taskDetails')
}
const dialogView = ref(false)

// 执行任务
const mhtLoading = ref(false)
const execNew = async (row) => {
    ElMessageBox.confirm(
        '确认任务执行该任务吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            mhtLoading.value = true
            if (timer != null) {
                clearTimeout(timer)
                timer = null
            }
            timer = setTimeout(() => {
                getTable()
            }, 4000)
            row.is_running = 1
            row.sent_number = 0
            try {
                ElNotification({
                    type: 'warning',
                    message: '任务执行中请稍等'
                })

                await execTask(row.id)
                mhtLoading.value = false
                dialogView.value = false
                // ElNotification({
                //     type: 'success',
                //     message: '任务执行完毕'
                // })
            } catch {
                mhtLoading.value = false
                clearTimeout(timer)
                timer = null
                row.is_running = 0
            }
        })
        .catch(() => {

        })


}



const handeleDelete = async (row) => {

    ElMessageBox.confirm(
        '确认删除该任务吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await deleteTask(row.id)
            ElNotification({
                type: 'success',
                message: '操作成功'
            })
            query.page = 1
            getTable()
        })
        .catch(() => {

        })
}

const handeleStop = (row) => {
    ElMessageBox.confirm(
        '确认停止该任务吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await stopTask(row.id)

            if (timer != null) {
                clearTimeout(timer)
                timer = null
            }
            getTable()
            ElNotification({
                type: 'success',
                message: '任务已停止'
            })
        })
}
// 新增
const isEdit = ref(false)
const handleAdd = () => {

    detailInfo.taskDetails = {}
    router.push('/taskDetails')
}
const onChangeCron = () => {

}
let task_id = ''


const handleEdit = (row) => {

    detailInfo.taskDetails = row
    router.push('/taskDetails')
}

// 查看日志
const dialogLog = ref(false)
const logList = ref([])
let logData = {}
const logQuery = reactive({
    page: 1,
    page_size: 10
})
const readyLog = (row) => {
    logData = row
    dialogLog.value = true
    logQuery.page = 1
    logList.value = []
    getLogs()
}

const logTotal = ref(0)

const tableLoading2 = ref(false)
const getLogs = async () => {
    tableLoading2.value = true

    const res = await taskLogs({
        task_id: logData.id,
        ...logQuery
    })
    tableLoading2.value = false

    logList.value = res.list.map((el) => {
        el.content = el.content.replace(/; /g, '<br /><br />')
        return el
    })
    logTotal.value = res.total
}
const handleSizeChangeLog = (e) => {
    logQuery.page = 1;
    logQuery.page_size = e
    getLogs()
}
const handleCurrentChangeLog = (e) => {
    logQuery.page = e;
    getLogs()
}


// 预览
const groupListEd = ref([])
const friendList = ref([])
const materiaList = ref([])
const taskInfo = ref({})
const time_type = ref(0)
const rule_type = ref('')
const start_time = ref('')
const end_time = ref('')
const isSkeleton = ref(true)
const isSkeleton2 = ref(true)

const readyRobot = ref({})
const sopData = ref({})
const tags = ref([])
const time_day = ref('')
const readyView = async (row) => {

    groupListEd.value = []
    friendList.value = []
    materiaList.value = []
    taskInfo.value = row
    dialogView.value = true
    isSkeleton.value = true
    isSkeleton2.value = true
    if (row.sop_type == 1) {

        taskGroups({
            task_id: row.id,
            page: 1,
            page_size: 100
        }).then((res) => {
            groupListEd.value = res.list
        })
    }
    taskFriends({
        task_id: row.id,
        page: 1,
        page_size: 100
    }).then((res) => {
        isSkeleton.value = false
        friendList.value = res.list
        if (row.sop_type == 2) {
            // time_type.value = JSON.parse(res.list[0].friend_rule).time_type
            // start_time.value = JSON.parse(res.list[0].friend_rule).start_time
            // end_time.value = JSON.parse(res.list[0].friend_rule).end_time
            if (res.list.length > 0) {
                sopData.value = JSON.parse(res.list[0].friend_rule)
                time_day.value = res.list[0].historical_day
                // console.log(sopData.value)
                if (sopData.value.rule_type == 3) {
                    tags.value = res.list[0].tag_name?.split(',')
                } else {
                    isSkeleton.value = false
                }
            } 

        } else {
            isSkeleton.value = false

        }
    })

    taskMaterials({
        task_id: row.id,
        page: 1,
        page_size: 100
    }).then((res) => {
        materiaList.value = res.list.map(el => {
            el.content = JSON.parse(el.content)
            return el
        })
        isSkeleton2.value = false
    })
    // getRobotList(row.robot_id)
    readyRobot.value = robotCards.value.find(el => el.id == row.robot_id)


}
const execNewView = async () => {
    execNew(taskInfo.value)

}


const v2props = ref({
    value: 'id',
    label: 'name'
})
const queryRobot = ref({
    page: 1,
    page_size: 100
})
const robotTotal = ref(0)
const robotInfo = ref({})
const getRobotList = async (id) => {
    const res = await robotList(queryRobot.value)
    robotCards.value = res.list
    robotTotal.value = res.total


}
const changeRobot = () => {
    query.page = 1
    getTable()
}
const currentChange = (e) => {
    queryRobot.value.page = e
    getRobotList()
}


const getHeadUrl = (id) => {
    return robotCards.value.find(el => el.id == id)?.head_url

}
const getRobotName = (id) => {
    return robotCards.value.find(el => el.id == id)?.name
}
// 复制任务
const copyTask = ref({})
const robotCardsCopy = ref([])
const dialogCopyTask = ref(false)
let friend_rule = {}
let copyMateriaList = []
const handleCopy = (row) => {
    copyTask.value = JSON.parse(JSON.stringify(row))
    copyTask.value.id = ''
    copyTask.value.title = copyTask.value.title + '-copy'
    copyTask.value.robot_id = ''
    robotCardsCopy.value = robotCards.value.filter(el => el.id != row.robot_id)
    dialogCopyTask.value = true
    taskFriends({
        task_id: row.id,
        page: 1,
        page_size: 100
    }).then((res) => {
        friend_rule = res.list[0].friend_rule

    })

    taskMaterials({
        task_id: row.id,
        page: 1,
        page_size: 100
    }).then((res) => {
        copyMateriaList = res.list.map(el => {
            el.content = JSON.parse(el.content)
            return el
        })



    })
}

const convertImageUrlToFile = async (url, fileName) => {
    try {
        // 1. 获取图片数据
        console.log(url)
        const response = await fetch(url);
        if (!response.ok) throw new Error('图片下载失败');

        // 2. 将响应转换为 Blob
        const blob = await response.blob();
        // 创建 FormData 对象
        const formData = new FormData();
        // 生成文件名
        formData.append('file', blob, fileName);
        // // 3. 将 Blob 转换为 File 对象（模拟用户上传的文件）
        // const file = new File([blob], fileName, { type: blob.type });

        return formData;
    } catch (error) {
        console.error('转换失败:', error);
        throw error;
    }

}

// async function convertToBase64(url) {
//   const response = await fetch(url);
//   const blob = await response.blob();
//   return new Promise((resolve) => {
//     const reader = new FileReader();
//     reader.onloadend = () => resolve(reader.result);
//     reader.readAsDataURL(blob);
//   });
// }

// // 使用示例
// convertToBase64(imageUrl)
//   .then(base64 => {
//     // 发送 base64 字符串到服务器
//     fetch(serverUrl, {
//       method: 'POST',
//       body: JSON.stringify({ image: base64 }),
//       headers: { 'Content-Type': 'application/json' }
//     });
//   });
let uploadAction = ''
const changeRobotCopy = (e) => {
    robotCardsCopy.value.forEach((el) => {
        if (e == el.id) {
            copyTask.value.robot_id = el.id
            uploadAction = el.server_ip
        }
    })
}
const saveCopy = async () => {
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            mhtLoading.value = true
            const promises = copyMateriaList.map(async (el, i) => {
                let url = ''
                let fileName = ''
                if (el.type == 2 || el.type == 4) {
                    url = el.content.img_url
                    fileName = el.content.file_name
                    const file = await convertImageUrlToFile(url, fileName)
                    let fordata = new FormData();
                    fordata.append('file', file)
                    const data = await uploadFile(file, uploadAction)
                    copyMateriaList[i].content.img_url = uploadAction + '/' + data.file_url
                    copyMateriaList[i].content.file_path = data.file_path
                    return true
                } else if (el.type == 8 || el.type == 10) {
                    url = el.content.file_url
                    fileName = el.content.file_name
                    const file = await convertImageUrlToFile(url, fileName)
                    let fordata = new FormData();
                    fordata.append('file', file)
                    const data = await uploadFile(file, uploadAction)
                    copyMateriaList[i].content.file_url = uploadAction + '/' + data.file_url
                    copyMateriaList[i].content.file_path = data.file_path
                    return true
                }

            })
            Promise.all(promises)
                .then(async (results) => {
                    console.log('所有图片都已完成', results);
                    try {
                        const obj = JSON.parse(JSON.stringify(copyTask.value))
                        obj.robot_id = String(copyTask.value.robot_id)
                        const res = await addTask(obj)
                        const copyTask_id = res.id
                        await taskFriendAdd({
                            "friend_list": [],
                            type: 2,
                            friend_rule: friend_rule
                        }, copyTask_id)
                        await taskMaterialsAdd({
                            'material_list': copyMateriaList.map((el) => {
                                return {
                                    content: JSON.stringify(el.content),
                                    type: el.type,
                                    interval_seconds: el.interval_seconds
                                }
                            })

                        }, copyTask_id)
                        mhtLoading.value = false
                        dialogCopyTask.value = false
                        ElNotification({
                            type: 'success',
                            message: '复制成功'
                        })
                        query.page = 1
                        getTable()
                    } catch (err) {
                        mhtLoading.value = false
                    }

                })
                .catch((error) => {
                    mhtLoading.value = false
                    console.error('有图片失败了', error);
                });
        }
    })

}

// 进度条
const getPercentage = (type, a, b) => {
    if (type == 0) {
        return 0
    } else {
        if (b == 0) {
            return 0
        } else {
            let num = a / b * 100
            return num.toFixed(2)

        }
    }

}

// watch(userRobotStore, (val) => {
//     query.page = 1
//     getTable()
// })
onMounted(() => {
    // if (userRobotStore.robotInfo.id) {
    getTable()
    // }
    getRobotList()
})
</script>
<style lang="scss" scoped>
.user-container {
    padding: var(--el-main-padding);

    // height: 100%;
    .el-card {
        background-color: var(--el-bg-color);
    }

    .table-card {
        margin-top: 20px;

        .table-card-center {
            height: calc(100vh - 232px);
        }

        .table-box {
            height: calc(100% - 60px);
        }
    }

    .pagination-box {
        overflow: hidden;
        margin-top: 25px;
        text-align: right;

        .el-pagination {
            float: right;
        }
    }

    .operations {
        font-size: 14px;
        // color: var(--el-color-primary);
        cursor: pointer;

        .el-icon {
            position: relative;
            top: 2px;
        }

        &:hover {
            color: var(--el-color-primary);
        }
    }

    .user-phone {
        color: var(--el-color-primary);
        cursor: pointer;

    }

    .materia-box {
        min-height: 460px;
        max-height: calc(100vh - 160px);
        margin-top: 10px;
        // margin-left: 20px;
        border: 1px solid var(--el-border-color);
        // padding: 25px;
        display: flex;
        position: relative;
        background-color: var(--el-color-primary-light-9);

        .meaasge {
            padding: 25px;
            flex: 2.5;
            position: relative;

            &::after {
                position: absolute;
                content: '';
                width: 1px;
                height: 100%;
                top: 0;
                left: 0;
                background-color: var(--el-border-color);
            }
        }

        .user-list {
            padding: 25px;
            flex: 1;
            background-color: #fff;

            .infinite-list {
                margin-top: 10px;
            }

            .infinite-list-item {
                height: 32px;
                line-height: 32px;
                margin: 0;
                padding-left: 15px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        }
    }

    .materia-item {
        overflow: hidden;
        margin-bottom: 20px;

        .tobot-image {
            float: left;
            width: 36px;
            height: 36px;
            margin-right: 15px;
            border-radius: 4px;
        }

        .materia-info {
            width: 300px;
            float: left;

            .remove {
                color: var(--el-color-danger);
                margin-left: 6px;
                transform: translateY(3px);
                cursor: pointer;
                font-size: 16px;
            }

            .robot-name {
                display: block;
                font-size: 12px;
                color: var(--el-text-color-secondary);
                margin-bottom: 6px;
            }

            .text {
                display: inline-block;
                line-height: 22px;
                background-color: #fff;
                border-radius: 8px;
                padding: 6px 12px;
                font-size: 14px;
                position: relative;

                pre {
                    white-space: break-spaces;
                }

                &::before {
                    position: absolute;
                    width: 0;
                    height: 0;
                    border-top: 8px solid transparent;
                    border-bottom: 8px solid transparent;
                    border-right: 10px solid #fff;
                    content: '';
                    top: 10px;
                    left: -8px;
                }
            }

            .image {
                .el-image {
                    width: 120px;
                    height: auto;
                    border-radius: 6px;
                }
            }

            .gif {
                .el-image {
                    width: 120px;
                    height: auto;
                }
            }

            .audio {
                width: 100px;

                .el-icon {
                    font-size: 20px;
                    transform: translateY(5px);
                }
            }

            .video {
                video {
                    width: 180px;
                    height: auto;
                }
            }

            .mini {
                height: 95px;
                width: 220px;
                background-color: #fff;
                padding: 0;

                .card-user {
                    overflow: hidden;
                    padding: 10px;
                }

                .el-image {
                    height: 50px;
                    width: 50px;
                    border-radius: 4px;
                    vertical-align: middle;
                    float: left;
                }

                .name {
                    font-size: 15px;
                    margin-left: 5px;
                    transform: translateY(7px);
                    display: inline-block;
                    float: left;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                p {
                    height: 20px;
                    line-height: 22px;
                    border-top: 1px solid var(--el-border-color);
                    font-size: 12px;
                    color: var(--el-text-color-secondary);
                    padding-left: 10px;
                }
            }

            .chengxu {
                height: 103px;

                .el-image {
                    height: 30px;
                    width: 30px;
                    margin-right: 5px;
                }

                .name {
                    transform: translateY(0px);
                    color: var(--el-text-color-secondary);
                    font-size: 12px;
                    line-height: 30px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                .cg-text {
                    display: block;
                    padding-left: 10px;
                    padding-right: 10px;
                    line-height: 20px;
                    margin-bottom: 6px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                p {
                    line-height: 25px;
                }
            }

            .address {
                padding: 0;
                // overflow: hidden;
                width: 220px;

                h4 {
                    line-height: 28px;
                    font-size: 14px;
                    margin-bottom: 5px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    position: relative;
                    z-index: 0;
                    font-weight: normal;
                    padding: 0 10px;
                }

                p {
                    font-size: 12px;
                    color: var(--el-text-color-secondary);
                    line-height: 24px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    position: relative;
                    z-index: 0;
                    padding: 0 10px;
                }

                .el-image {
                    height: 86px;
                    width: 100%;
                    position: relative;
                    z-index: 0;
                    border-bottom-left-radius: 8px;
                    border-bottom-right-radius: 8px;
                }
            }

            .link {
                width: 220px;
                height: 100px;

                .el-image {
                    height: 46px;
                    width: 46px;
                    float: right;
                    // transform: translateY(-17px);
                    margin-right: 0;
                }

                div {
                    // margin-top: 13px;
                    height: 50px;

                    h4 {
                        font-size: 14px;
                        line-height: 22px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }

                    p {
                        color: var(--el-text-color-secondary);
                        height: 48px;
                        font-size: 12px;
                        float: left;
                        width: calc(100% - 55px);
                        line-height: normal;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: normal;
                        /* 防止文本换行 */
                        display: -webkit-box;
                        -webkit-line-clamp: 3; //显示两行文本
                        -webkit-box-orient: vertical;
                    }
                }
            }

            .file {
                width: 220px;
                height: 75px;

                .file-box {
                    float: left;
                    width: calc(100% - 50px);

                }

                .el-image {
                    width: 46px;
                    height: 46px;
                    float: right;
                    margin-right: 0;
                    transform: translateY(10px);
                }

                .el-icon {
                    float: right;
                    font-size: 40px;
                    color: var(--el-color-primary);
                    transform: translateY(12px);
                }

                label {
                    display: block;
                    line-height: 30px;
                    transform: translateY(2px);
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    margin-bottom: 6px;
                }

                span {
                    display: inline-block;
                    font-size: 12px;
                    color: var(--el-text-color-secondary);
                    line-height: normal;
                    transform: translateY(-8px);
                }
            }

            .interval-seconds {
                font-size: 12px;
                color: var(--el-text-color-secondary);
                margin-top: 10px;
                // transform: scale(0.8);
            }
        }
    }
}

:deep(.el-table td.el-table__cell div) {
    font-size: 13px;

    .el-progress-bar__innerText {
        font-size: 12px;
        transform: translateY(-1px);
    }
}

.tags-box {
    margin-top: 10px;

    .el-tag {
        margin-right: 10px;
    }
}
</style>