<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"
                :model="formData"
                :rules="!isDetail ? rules : {}"
                size="large"
                label-width="120px"
                :disabled="isDetail"
            >
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="任务名称" prop="taskName">
                            <el-input
                                v-model.trim="formData.taskName"
                                placeholder="请输入任务名称"
                                maxlength="50"
                                show-word-limit
                                clearable
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="短信类型" prop="msgType">
                            <el-select
                                v-model="formData.msgType"
                                placeholder="请选择短信类型"
                                clearable
                                style="width: 100%"
                            >
                                <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="cron表达式" prop="cronExpression">
                            <el-input
                                v-model="formData.cronExpression"
                                placeholder="请输入cron执行表达式"
                            >
                                <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
                                v-model.trim="formData.sendContent"
                                type="textarea"
                                :rows="5"
                                placeholder="请输入发送内容"
                                maxlength="500"
                                show-word-limit
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

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

                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="接收人员" prop="recipientList">
                            <div class="recipient-select">
                                <el-button
                                    type="primary"
                                    link
                                    icon="Plus"
                                    @click="onOpenPersonPicker"
                                    :disabled="isDetail"
                                    v-if="!isDetail"
                                >
                                    选择
                                </el-button>
                                <span class="selected-names">{{ selectedRecipientNames }}</span>
                            </div>
                            <el-table
                                v-if="formData.recipientList && formData.recipientList.length > 0"
                                :data="formData.recipientList"
                                border
                                style="margin-top: 10px"
                                max-height="200"
                            >
                                <el-table-column align="center" prop="workerName" label="姓名" />
                                <el-table-column align="center" prop="phone" label="电话" />
                                <el-table-column v-if="!isDetail" label="操作" align="center">
                                    <template #default="{ $index }">
                                        <el-button
                                            type="danger"
                                            link
                                            icon="Delete"
                                            @click="handleRemoveRecipient($index)"
                                        >
                                            删除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </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"
                    @hide="handleCronHide"
                    @fill="crontabFill"
                    :expression="cronExpression"
                />
            </template>
        </ComDialog>

        <!-- 人员选择弹窗 -->
        <ComDialog :dialog-config="managerDialogConfig" @closeDialogOuter="onCloseDialogOuter">
            <template #outerContent>
                <PersonPicker v-model="formData.recipientList" />
                <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 '@/components/Crontab'
import {
    addLoopSendAPI,
    updateLoopSendAPI,
    getLoopSendDetailAPI,
} 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'

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 crontabRef = ref(null)
const personTableRef = ref(null)
const cronExpression = ref('')

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

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

const formData = ref(getInitFormData())

// 表单验证规则
const rules = {
    taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
    msgType: [{ required: true, message: '请选择短信类型', trigger: 'change' }],
    cronExpression: [{ required: true, message: '请输入cron表达式', trigger: 'change' }],
    sendContent: [{ required: true, message: '请输入发送内容', trigger: 'blur' }],
    recipientList: [
        {
            required: true,
            message: '请至少选择一个接收人员',
            trigger: 'change',
            validator: (rule, value, callback) => {
                if (!value || value.length === 0) {
                    callback(new Error('请至少选择一个接收人员'))
                } else {
                    callback()
                }
            },
        },
    ],
}

// 人员选择弹窗相关
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 onOpenPersonPicker = () => {
    managerDialogConfig.outerVisible = true
}

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

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

// 关闭人员选择弹窗
const onCloseDialogOuter = (visible) => {
    managerDialogConfig.outerVisible = visible
}

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

// Cron表达式回填
const crontabFill = (value) => {
    formData.value.cronExpression = value
    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,
            workerList: formData.value.recipientList.map((item) => {
                return {
                    id: item.id,
                }
            }),
        }

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

        const result = await API(params)
        if (result.code === 200) {
            proxy.$modal.msgSuccess(mode.value === 'edit' ? '编辑成功' : '新增成功')
            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
            formData.value = {
                id: data.id,
                taskName: data.taskName || '',
                msgType: String(data.msgType || ''),
                cronExpression: data.cronExpression || '',
                misfirePolicy: String(data.misfirePolicy || '1'),
                concurrent: String(data.concurrent || '1'),
                sendContent: data.sendContent || '',
                recipientList: data.workerList || [],
                remark: data.remark || '',
            }
            cronExpression.value = data.cronExpression || ''
        }
    } catch (error) {
        console.error('获取详情失败:', error)
    }
}

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;
        }
    }

    .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 {
        margin-top: 12px;
        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>

