<template>
    <div class="app-container loop-send-edit">
        <!-- 顶部返回 + 标题 -->
        <el-page-header @back="onBack" :content="pageTitle" class="page-header" />

        <!-- 表单内容 -->
        <el-card shadow="never" class="card-section">
            <template #header>
                <div class="card-header">任务信息</div>
            </template>
            <el-form
                ref="formRef"
                size="large"
                :model="formData"
                label-width="auto"
                :disabled="isDetail"
                :rules="!isDetail ? rules : {}"
            >
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="任务名称" prop="taskName">
                            <el-input
                                clearable
                                maxlength="50"
                                show-word-limit
                                placeholder="请输入任务名称"
                                v-model.trim="formData.taskName"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="短信类型" prop="msgType">
                            <el-select
                                clearable
                                style="width: 100%"
                                v-model="formData.msgType"
                                placeholder="请选择短信类型"
                            >
                                <el-option label="通知" value="1" />
                                <el-option label="计划" value="2" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="循环方式" prop="cronExpressionMsg">
                            <el-input
                                disabled
                                placeholder="请选择循环方式"
                                v-model="formData.cronExpressionMsg"
                            >
                                <template #append>
                                    <el-button
                                        type="primary"
                                        v-if="!isDetail"
                                        @click="handleShowCron"
                                    >
                                        循环方式配置
                                        <el-icon class="el-icon--right"><Clock /></el-icon>
                                    </el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="执行策略" prop="misfirePolicy">
                            <el-radio-group v-model="formData.misfirePolicy">
                                <el-radio-button value="1">循环执行</el-radio-button>
                                <el-radio-button value="2">执行一次</el-radio-button>
                                <!-- <el-radio-button value="3">放弃执行</el-radio-button> -->
                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                    <!-- <el-col :span="12">
                        <el-form-item label="是否并发" prop="concurrent">
                            <el-radio-group v-model="formData.concurrent">
                                <el-radio-button value="0">允许</el-radio-button>
                                <el-radio-button value="1">禁止</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col> -->
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="发送内容" prop="sendContent">
                            <el-input
                                :rows="5"
                                type="textarea"
                                maxlength="280"
                                show-word-limit
                                placeholder="请输入发送内容"
                                v-model.trim="formData.sendContent"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input
                                :rows="5"
                                maxlength="500"
                                type="textarea"
                                show-word-limit
                                placeholder="请输入备注"
                                v-model.trim="formData.remark"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="是否按照性别进行群发短信">
                            <el-radio-group
                                v-model="isGenderSendGroup"
                                @change="handleGenderSendGroupChange"
                            >
                                <el-radio-button :value="1">是</el-radio-button>
                                <el-radio-button :value="0">否</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24" v-if="isGenderSendGroup === 0">
                    <el-col :span="24">
                        <el-form-item label="接收人员" prop="recipientList">
                            <div class="recipient-select">
                                <el-button
                                    link
                                    icon="Plus"
                                    type="primary"
                                    v-if="!isDetail"
                                    :disabled="isDetail"
                                    @click="onOpenPersonPicker"
                                >
                                    选择
                                </el-button>
                                <span class="selected-names">{{ selectedRecipientNames }}</span>
                            </div>
                            <el-table
                                border
                                style="margin-top: 10px"
                                :data="formData.recipientList"
                                v-if="formData.recipientList && formData.recipientList.length > 0"
                            >
                                <el-table-column
                                    width="80"
                                    type="index"
                                    label="序号"
                                    align="center"
                                />
                                <el-table-column align="center" prop="workerName" label="姓名" />
                                <el-table-column align="center" prop="phone" label="电话" />
                                <el-table-column
                                    width="140"
                                    label="操作"
                                    align="center"
                                    v-if="!isDetail"
                                >
                                    <template #default="{ $index }">
                                        <el-button
                                            link
                                            type="danger"
                                            icon="Delete"
                                            @click="handleRemoveRecipient($index)"
                                        >
                                            删除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24" v-if="isGenderSendGroup === 0">
                    <el-col :span="24">
                        <el-form-item label="已选分组">
                            <div class="recipient-select">
                                <span class="selected-names">
                                    {{
                                        formData.groupList
                                            .map((item) => item.groupName)
                                            .join('、') || '暂未选择分组'
                                    }}
                                </span>
                            </div>
                            <el-table
                                border
                                style="margin-top: 10px"
                                :data="formData.groupList"
                                v-if="formData.groupList && formData.groupList.length > 0"
                            >
                                <el-table-column
                                    width="80"
                                    type="index"
                                    label="序号"
                                    align="center"
                                />
                                <el-table-column align="center" prop="groupName" label="分组名称" />
                                <el-table-column
                                    label="操作"
                                    width="140"
                                    align="center"
                                    v-if="!isDetail"
                                >
                                    <template #default="{ $index }">
                                        <el-button
                                            link
                                            type="danger"
                                            icon="Delete"
                                            @click="handleRemoveGroup($index)"
                                        >
                                            删除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24" v-if="isGenderSendGroup === 1">
                    <el-col :span="24">
                        <el-form-item label="群发短信群体" prop="sex">
                            <el-radio-group v-model="formData.sex">
                                <el-radio-button :value="1">男</el-radio-button>
                                <el-radio-button :value="0">女</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 底部操作按钮 -->
        <div class="page-footer">
            <ComButton plain type="info" @click="onBack">
                {{ isDetail ? '返回' : '取消' }}
            </ComButton>
            <ComButton v-if="!isDetail" type="primary" @click="onSubmit">确认执行</ComButton>
        </div>

        <!-- Cron表达式生成器弹窗 -->
        <ComDialog :dialog-config="cronDialogConfig" @closeDialogOuter="onCloseCronDialog">
            <template #outerContent>
                <crontab
                    ref="crontabRef"
                    @fill="crontabFill"
                    @hide="handleCronHide"
                    :expression="cronExpression"
                />
            </template>
        </ComDialog>

        <!-- 人员选择弹窗 -->
        <ComDialog :dialog-config="managerDialogConfig" @closeDialogOuter="onCloseDialogOuter">
            <template #outerContent>
                <PersonPicker
                    v-model="formData.recipientList"
                    :group-list="formData.groupList"
                    @update:groupList="handleGroupListUpdate"
                    :key="`picker-${managerDialogConfig.outerVisible}`"
                />
                <el-row class="common-btn-row fixed-bottom">
                    <ComButton plain type="info" @click="managerDialogConfig.outerVisible = false">
                        取消
                    </ComButton>
                    <ComButton type="primary" @click="onConfirmRecipients">确定</ComButton>
                </el-row>
            </template>
        </ComDialog>
    </div>
</template>

<script setup name="LoopSendEdit">
import { ref, reactive, computed, getCurrentInstance, nextTick, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Clock } from '@element-plus/icons-vue'
import Crontab from './Crontab/index.vue'
import {
    addLoopSendAPI,
    updateLoopSendAPI,
    getLoopSendDetailAPI,
    getLoopSendRecordsAPI,
    getLoopSendRecordDetailsAPI,
} from '@/api/sMsSendManage/loopSend.js'
import ComButton from '@/components/ComButton/index.vue'
import ComDialog from '@/components/ComDialog/index.vue'
import PersonPicker from '@/components/PersonPicker/index.vue'
import { bus, BUS_EVENTS } from '@/utils/bus'

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const mode = computed(() => route.query.mode || 'add')
const isDetail = computed(() => mode.value === 'detail')

const pageTitle = computed(() => {
    if (mode.value === 'edit') return '编辑循环发送任务'
    if (mode.value === 'detail') return '循环发送任务详情'
    return '新增循环发送任务'
})

const formRef = ref(null)
const taskStatus = ref('')
const crontabRef = ref(null)
const cronExpression = ref('')
const personTableRef = ref(null)
const isGenderSendGroup = ref(0)

// Cron表达式生成器弹窗配置
const cronDialogConfig = reactive({
    maxHeight: '80vh',
    minHeight: '500px',
    outerWidth: '70%',
    outerVisible: false,
    outerTitle: '循环方式配置',
})

// 定义初始表单数据
const getInitFormData = () => ({
    id: null,
    taskName: '', // 任务名称
    msgType: '', // 短信类型：1-通知，2-计划
    cronExpression: '', // cron表达式
    cronExpressionMsg: '', // 循环方式
    misfirePolicy: '1', // 执行策略：1-立即执行，2-执行一次，3-放弃执行
    concurrent: '1', // 是否并发：0-允许，1-禁止
    sendContent: '', // 发送内容
    sex: '', // 群发短信群体：0-男，1-女
    recipientList: [], // 接收人员列表
    groupList: [], // 接收分组列表
})

const formData = ref(getInitFormData())

// 表单验证规则
const rules = {
    taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
    msgType: [{ required: true, message: '请选择短信类型', trigger: 'change' }],
    cronExpressionMsg: [{ required: true, message: '请选择循环方式', trigger: 'change' }],
    sendContent: [{ required: true, message: '请输入发送内容', trigger: 'blur' }],
    recipientList: [
        {
            required: true,
            message: '请至少选择一个接收人员或分组',
            trigger: 'change',
            validator: (rule, value, callback) => {
                // 如果选择了分组，则不需要验证人员列表
                if (formData.value.groupList && formData.value.groupList.length > 0) {
                    callback()
                    return
                }
                // 如果没有选择分组，则必须选择人员
                if (!value || value.length === 0) {
                    callback(new Error('请至少选择一个接收人员或分组'))
                } else {
                    callback()
                }
            },
        },
    ],
    sex: [{ required: true, message: '请选择群发短信群体', trigger: 'change' }],
}

// 人员选择弹窗相关
const managerDialogConfig = reactive({
    outerVisible: false,
    outerTitle: '选择接收人员',
    outerWidth: '80%',
    minHeight: '60vh',
    maxHeight: '80vh',
})

// 已选接收人员名称显示
const selectedRecipientNames = computed(() => {
    if (!formData.value.recipientList || formData.value.recipientList.length === 0) {
        return '暂未选择人员'
    }
    return formData.value.recipientList.map((item) => item.workerName).join('、')
})

// 处理分组列表更新
const handleGroupListUpdate = (groupList) => {
    formData.value.groupList = groupList || []
}

// 打开人员选择弹窗
const onOpenPersonPicker = () => {
    managerDialogConfig.outerVisible = true
}

// 确认选择接收人员
const onConfirmRecipients = () => {
    managerDialogConfig.outerVisible = false
}

// 移除接收人员
const handleRemoveRecipient = (index) => {
    formData.value.recipientList.splice(index, 1)
}

// 移除分组
const handleRemoveGroup = (index) => {
    formData.value.groupList.splice(index, 1)
}
// 关闭人员选择弹窗
const onCloseDialogOuter = (visible) => {
    managerDialogConfig.outerVisible = visible
}

// Cron表达式生成器
const handleShowCron = () => {
    cronExpression.value = formData.value.cronExpression || ''
    cronDialogConfig.outerVisible = true
}

// 获取星期名称
// 注意：Crontab组件使用的映射是：1=周日，2=周一，3=周二，4=周三，5=周四，6=周五，7=周六
// 这与标准Cron表达式不同（标准：0/7=周日，1=周一，2=周二...6=周六）
const getWeekName = (week) => {
    const weekMap = {
        0: '日', // 标准Cron：0或7表示周日
        1: '日', // Crontab组件：1表示周日
        2: '一', // Crontab组件：2表示周一
        3: '二', // Crontab组件：3表示周二
        4: '三', // Crontab组件：4表示周三
        5: '四', // Crontab组件：5表示周四
        6: '五', // Crontab组件：6表示周五
        7: '六', // Crontab组件：7表示周六，标准Cron：7也表示周日
    }
    // 转换为字符串以确保正确匹配
    const weekStr = String(week)
    return weekMap[weekStr] !== undefined ? weekMap[weekStr] : week
}

// 将Cron表达式解析为中文说明
const parseCronToChinese = (cronExpression) => {
    if (!cronExpression) return ''

    const parts = cronExpression.trim().split(/\s+/)
    if (parts.length < 5) return ''

    // 判断是5位格式（分钟 小时 日 月 星期）还是6/7位格式（秒 分钟 小时 日 月 星期 [年]）
    let second, minute, hour, day, month, week, year
    if (parts.length === 5) {
        // 5位格式：分钟 小时 日 月 星期，秒默认为0
        second = '0'
        minute = parts[0]
        hour = parts[1]
        day = parts[2]
        month = parts[3]
        week = parts[4]
        year = ''
    } else {
        // 6位或7位格式：秒 分钟 小时 日 月 星期 [年]
        second = parts[0]
        minute = parts[1]
        hour = parts[2]
        day = parts[3]
        month = parts[4]
        week = parts[5]
        year = parts[6] || ''
    }

    // 格式化时间（时分秒）
    const formatTime = (h, m, s) => {
        // 如果值是*，替换为0
        const hVal = h === '*' || h === '**' ? '0' : h
        const mVal = m === '*' || m === '**' ? '0' : m
        const sVal = s === '*' || s === '**' ? '0' : s
        const hStr = String(hVal).replace(/\*/g, '0').padStart(2, '0')
        const mStr = String(mVal).replace(/\*/g, '0').padStart(2, '0')
        const sStr = String(sVal).replace(/\*/g, '0').padStart(2, '0')
        return `${hStr}：${mStr}：${sStr}`
    }

    // 获取单个值（如果是列表，取第一个）
    const getSingleValue = (value) => {
        if (value.includes(',')) {
            return value.split(',')[0]
        }
        return value
    }

    // 解析星期
    const parseWeek = (weekValue) => {
        if (!weekValue || weekValue === '?' || weekValue === '*') return ''
        if (weekValue.includes(',')) {
            const weeks = weekValue.split(',').map(getWeekName)
            return `每周${weeks.join('、')}`
        }
        if (weekValue.includes('-')) {
            const [start, end] = weekValue.split('-')
            return `每周${getWeekName(start)}到周${getWeekName(end)}`
        }
        return `每周${getWeekName(weekValue)}`
    }

    // 解析日期
    const parseDay = (dayValue, isYearly = false) => {
        if (!dayValue || dayValue === '?' || dayValue === '*') return ''
        if (dayValue.includes(',')) {
            const days = dayValue.split(',')
            return isYearly ? `${days.join('、')}日` : `每月${days.join('、')}日`
        }
        if (dayValue.includes('-')) {
            const [start, end] = dayValue.split('-')
            return isYearly ? `${start}到${end}日` : `每月${start}到${end}日`
        }
        return isYearly ? `${dayValue}日` : `每月${dayValue}日`
    }

    // 解析月份
    const parseMonth = (monthValue) => {
        if (!monthValue || monthValue === '*') return ''
        if (monthValue.includes(',')) {
            const months = monthValue.split(',')
            return `${months.join('、')}月`
        }
        if (monthValue.includes('-')) {
            const [start, end] = monthValue.split('-')
            return `${start}月到${end}月`
        }
        return `${monthValue}月`
    }

    // 解析年份
    const parseYear = (yearValue) => {
        if (!yearValue || yearValue === '*') return ''
        if (yearValue.includes(',')) {
            const years = yearValue.split(',')
            return `${years.join('、')}年`
        }
        if (yearValue.includes('-')) {
            const [start, end] = yearValue.split('-')
            return `${start}年到${end}年`
        }
        return `${yearValue}年`
    }

    // 处理步长表达式
    const hasStep = (value) => {
        return value.includes('/') && value.split('/')[0] === '*'
    }

    // 特殊情况1：每天固定时间执行（最常用）
    if (
        minute !== '?' &&
        hour !== '?' &&
        day === '*' &&
        month === '*' &&
        week === '?' &&
        (!year || year === '*')
    ) {
        const s = second === '?' ? '0' : getSingleValue(second)
        const m = getSingleValue(minute)
        const h = getSingleValue(hour)

        if (!hasStep(minute) && !hasStep(hour)) {
            let result = `每天${formatTime(h, m, s)}执行`
            // 清理所有可能的*符号
            result = result.replace(/(\d)\*/g, '$10').replace(/\*/g, '0')
            return result
        }
    }

    // 特殊情况2：每周固定时间执行
    if (
        minute !== '?' &&
        hour !== '?' &&
        day === '?' &&
        month === '*' &&
        week !== '?' &&
        week !== '*' &&
        (!year || year === '*')
    ) {
        const s = second === '?' ? '0' : getSingleValue(second)
        const m = getSingleValue(minute)
        const h = getSingleValue(hour)
        const weekDesc = parseWeek(week)

        if (!hasStep(minute) && !hasStep(hour)) {
            let result = `${weekDesc}，${formatTime(h, m, s)}执行`
            // 清理所有可能的*符号
            result = result.replace(/(\d)\*/g, '$10').replace(/\*/g, '0')
            return result
        }
    }

    // 特殊情况3：每月固定日期执行
    if (
        minute !== '?' &&
        hour !== '?' &&
        day !== '*' &&
        day !== '?' &&
        month === '*' &&
        week === '?' &&
        (!year || year === '*')
    ) {
        const s = second === '?' ? '0' : getSingleValue(second)
        const m = getSingleValue(minute)
        const h = getSingleValue(hour)
        const dayDesc = parseDay(day)

        if (!hasStep(minute) && !hasStep(hour)) {
            let result = `${dayDesc}，${formatTime(h, m, s)}执行`
            // 清理所有可能的*符号
            result = result.replace(/(\d)\*/g, '$10').replace(/\*/g, '0')
            return result
        }
    }

    // 特殊情况4：每年固定日期时间执行
    if (
        minute !== '?' &&
        hour !== '?' &&
        day !== '*' &&
        day !== '?' &&
        month !== '*' &&
        week === '?' &&
        (!year || year === '*' || year === '')
    ) {
        const s = second === '?' ? '0' : getSingleValue(second)
        const m = getSingleValue(minute)
        const h = getSingleValue(hour)
        const dayDesc = parseDay(day, true) // 每年模式，不显示"每月"
        const monthDesc = parseMonth(month)

        if (!hasStep(minute) && !hasStep(hour)) {
            let result = `每年${monthDesc}${dayDesc}，${formatTime(h, m, s)}执行`
            // 清理所有可能的*符号
            result = result.replace(/(\d)\*/g, '$10').replace(/\*/g, '0')
            return result
        }
    }

    // 通用情况：按年月日时分秒顺序构建
    const partsDesc = []

    // 判断是否是每年模式（月份和日期都有值，但年份为空或*）
    const isYearlyMode = month !== '*' && day !== '*' && day !== '?' && (!year || year === '*')

    // 年份
    if (year && year !== '*' && year !== '') {
        const yearDesc = parseYear(year)
        if (yearDesc) partsDesc.push(yearDesc)
    } else if (isYearlyMode) {
        // 如果是每年模式，添加"每年"前缀
        partsDesc.push('每年')
    }

    // 月份
    if (month !== '*') {
        const monthDesc = parseMonth(month)
        if (monthDesc) partsDesc.push(monthDesc)
    }

    // 日期或星期
    if (day !== '?' && day !== '*') {
        // 如果是每年模式，不显示"每月"
        const dayDesc = parseDay(day, isYearlyMode)
        if (dayDesc) partsDesc.push(dayDesc)
    } else if (week !== '?' && week !== '*') {
        const weekDesc = parseWeek(week)
        if (weekDesc) partsDesc.push(weekDesc)
    }

    // 时间（时分秒）
    const timeParts = []
    if (hour !== '*' && !hasStep(hour)) {
        const h = getSingleValue(hour)
        timeParts.push(h.padStart(2, '0'))
    } else {
        timeParts.push('**')
    }

    if (minute !== '*' && !hasStep(minute)) {
        const m = getSingleValue(minute)
        timeParts.push(m.padStart(2, '0'))
    } else {
        timeParts.push('**')
    }

    // 秒字段：如果是5位格式或秒为?，默认为00
    if (second && second !== '*' && second !== '?' && !hasStep(second)) {
        const s = getSingleValue(second)
        timeParts.push(s.padStart(2, '0'))
    } else {
        timeParts.push('00') // 默认秒为00
    }

    // 如果时间部分有具体值，添加到描述中
    if (timeParts.some((t) => t !== '**')) {
        // 将**替换为00，确保没有*符号
        const timeStr = timeParts.map((t) => (t === '**' ? '00' : t)).join('：')
        if (timeStr !== '00：00：00' || (hour === '*' && minute === '*' && second === '*')) {
            partsDesc.push(timeStr)
        }
    }

    // 处理步长表达式
    if (hour.includes('/') && hour.split('/')[0] === '*') {
        const step = hour.split('/')[1]
        partsDesc.push(`每${step}小时`)
    }
    if (minute.includes('/') && minute.split('/')[0] === '*') {
        const step = minute.split('/')[1]
        partsDesc.push(`每${step}分钟`)
    }
    // 秒的步长表达式只在6/7位格式中处理
    if (second && second.includes('/') && second.split('/')[0] === '*') {
        const step = second.split('/')[1]
        partsDesc.push(`每${step}秒`)
    }

    // 构建最终描述
    if (partsDesc.length === 0) {
        if (minute === '*' && hour === '*' && day === '*' && month === '*' && week === '?') {
            return '每分钟执行'
        }
        return `Cron表达式：${cronExpression}`
    }

    let result = `${partsDesc.join('，')}执行`

    // 清理所有可能的*符号，将0*替换为00
    result = result.replace(/(\d)\*/g, '$10')
    result = result.replace(/\*/g, '0')

    return result
}

// Cron表达式回填
const crontabFill = (value) => {
    formData.value.cronExpression = value

    // 生成中文说明并赋值给备注
    const chineseDesc = parseCronToChinese(value)
    if (chineseDesc) {
        // 清空之前的备注，直接赋值新的中文说明
        formData.value.remark = chineseDesc
        formData.value.cronExpressionMsg = chineseDesc
    }

    cronDialogConfig.outerVisible = false
}

// Cron组件hide事件处理
const handleCronHide = () => {
    cronDialogConfig.outerVisible = false
}

// 关闭Cron表达式弹窗
const onCloseCronDialog = (visible) => {
    cronDialogConfig.outerVisible = visible
}

// 返回
const onBack = () => {
    // router.back()
    proxy.$tab.closeOpenPage({
        path: '/sMsSendManage/loopSend',
    })
}

// 提交表单
const onSubmit = async () => {
    try {
        await formRef.value.validate()
        const API = mode.value === 'edit' ? updateLoopSendAPI : addLoopSendAPI

        // 组装提交参数
        const params = {
            remark: formData.value.remark,
            taskName: formData.value.taskName,
            msgType: formData.value.msgType,
            cronExpression: formData.value.cronExpression,
            misfirePolicy: formData.value.misfirePolicy,
            concurrent: formData.value.concurrent,
            sendContent: formData.value.sendContent,
            sex: formData.value.sex,
        }

        // 根据是否有分组列表来决定传递workerList还是groupList
        if (formData.value.groupList && formData.value.groupList.length > 0) {
            // 如果选择了分组，传递分组ID列表
            params.groupList = formData.value.groupList.map((item) => {
                return {
                    id: item.id,
                }
            })
        }

        if (formData.value.recipientList && formData.value.recipientList.length > 0) {
            // 如果选择了分组，传递分组ID列表
            params.workerList = formData.value.recipientList.map((item) => {
                return {
                    id: item.id,
                }
            })
        }

        // 编辑时需要传递id
        if (mode.value === 'edit' && route.query.id) {
            params.id = Number(route.query.id)
            params.jobId = Number(route.query.jobId)
            params.taskStatus = taskStatus.value
        }

        const result = await API(params)
        if (result.code === 200) {
            proxy.$modal.msgSuccess(mode.value === 'edit' ? '编辑成功' : '新增成功')
            // 通知父页面刷新列表
            bus.emit(BUS_EVENTS.REFRESH_LOOP_SEND_LIST)
            onBack()
        }
    } catch (error) {
        return Promise.reject(error)
    }
}

// 获取详情数据
const getDetail = async () => {
    if (!route.query.id) return
    try {
        const result = await getLoopSendDetailAPI(route.query.id)
        if (result.code === 200 && result.data) {
            const data = result.data

            // 处理分组列表：将后端返回的 workerName 字段转换为 groupName
            const groupList = (data.groupList || []).map((group) => ({
                id: group.id,
                groupName: group.workerName || group.groupName || '',
            }))

            formData.value = {
                id: data.id,
                taskName: data.taskName || '',
                msgType: String(data.msgType || ''),
                cronExpression: data.cronExpression || '',
                cronExpressionMsg: parseCronToChinese(data.cronExpression) || '',
                misfirePolicy: String(data.misfirePolicy || '1'),
                concurrent: String(data.concurrent || '1'),
                sendContent: data.sendContent || '',
                recipientList: data.workerList || [],
                groupList: groupList,
                remark: data.remark || '',
                sex: data.sex,
            }

            if (data.sex === 1 || data.sex === 0) {
                isGenderSendGroup.value = 1
            }
            taskStatus.value = data.taskStatus || ''
            cronExpression.value = data.cronExpression || ''
        }
    } catch (error) {
        console.error('获取详情失败:', error)
    }
}

// 查看详情
const onHandleDetail = async (row) => {
    const result = await getLoopSendRecordDetailsAPI({ loopId: row.loopId })

    if (result.code === 200 && result.data?.workerList) {
        recordsDetailList.value = result.data.workerList
    }
    console.log(result, 'result')
}

// 群发短信群体变化
const handleGenderSendGroupChange = (value) => {
    if (value === 0) {
        // 重置人员和分组列表
        formData.value.recipientList = []
        formData.value.groupList = []
    } else {
        formData.value.sex = ''
    }
}

onMounted(() => {
    if (mode.value === 'edit' || mode.value === 'detail') {
        getDetail()
    }
})
</script>

<style lang="scss" scoped>
.loop-send-edit {
    padding: 20px;

    .page-header {
        margin-bottom: 20px;
        padding: 16px 20px;
        background: linear-gradient(135deg, #f5f7fa 0%, #ffffff 100%);
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);

        :deep(.el-page-header__left) {
            .el-page-header__back {
                padding: 8px;
                border-radius: 6px;
                transition: all 0.3s ease;
                background-color: transparent;

                &:hover {
                    background-color: #f0f2f5;
                    color: #1677ff;
                    transform: translateX(-2px);
                }

                &::before {
                    font-size: 16px;
                    font-weight: 600;
                }
            }
        }

        :deep(.el-page-header__content) {
            font-size: 18px;
            font-weight: 600;
            color: #1f2937;
            margin-left: 12px;
        }
    }

    .card-section {
        margin-bottom: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        overflow: hidden;
        transition: box-shadow 0.3s ease;

        &:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        :deep(.el-card__header) {
            padding: 16px 20px;
            background-color: #fafbfc;
            border-bottom: 1px solid #f0f2f5;
        }

        :deep(.el-card__body) {
            padding: 24px 20px;
        }
    }

    .recipient-select {
        display: flex;
        align-items: center;
        gap: 10px;

        .selected-names {
            color: #606266;
            font-size: 14px;
            flex: 1;
        }
    }

    .no-group-tip {
        color: #909399;
        font-size: 14px;
        padding: 10px 0;
    }

    .person-search-bar {
        margin-bottom: 8px;
    }

    .selected-persons {
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        padding: 12px;
        height: 100%;
        display: flex;
        flex-direction: column;
        background: #fff;

        .selected-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 15px;
            border-bottom: 1px solid #e5e7eb;
            font-weight: 500;
            margin-bottom: 8px;
        }

        .selected-list {
            flex: 1;
            padding: 10px;
            overflow-y: auto;
            max-height: 400px;
            display: flex;
            flex-direction: column;
            gap: 8px;

            .selected-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 8px 12px;
                background: #f0f9ff;
                border: 1px solid #b3d8ff;
                border-radius: 6px;
                transition: all 0.3s ease;

                &:hover {
                    background: #e1f3ff;
                    border-color: #409eff;
                }

                .remove-icon {
                    color: #909399;
                    cursor: pointer;
                    font-size: 16px;
                    transition: color 0.3s ease;

                    &:hover {
                        color: #f56c6c;
                    }
                }
            }

            .empty-tip {
                text-align: center;
                color: #9ca3af;
                padding: 20px;
            }
        }
    }

    .page-footer {
        position: sticky;
        bottom: 10px;
        background: #fff;
        z-index: 10;
        border-top: 1px solid #e4e7ed;
        padding-top: 15px;
        display: flex;
        justify-content: flex-end;
        gap: 12px;
    }
}

.common-btn-row {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
    padding: 0 20px 20px;

    &.fixed-bottom {
        position: sticky;
        bottom: 0;
        background: #fff;
        z-index: 10;
        border-top: 1px solid #e4e7ed;
        padding-top: 15px;
    }
}

.card-header {
    font-weight: 600;
    font-size: 15px;
    color: #1f2937;
    position: relative;
    padding-left: 12px;
    display: flex;
    align-items: center;

    &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background: linear-gradient(180deg, #1677ff 0%, #4096ff 100%);
        border-radius: 2px;
    }
}
</style>

