<template>
    <PagingTable url="/task" :where="where" ref="table" @row-click="rowClick" :stripe="false">
        <template #filter>
            <ElButton :icon="Refresh" @click="table.refresh()"></ElButton>
            <ElButton :icon="Plus" @click="onEdit({ checkConnection: true }), getPhoneList()"> 添加</ElButton>
        </template>
        <ElTableColumn type="expand">
            <template #default="{ row }">
                <div class="px-4 py-2">
                    <div class="bg-neutral-100 dark:bg-neutral-800 rounded-md p-4">
                        <div class="flex flex-wrap">
                            <ExpandItem class="w-full">
                                <template #title>发送内容</template>
                                <template #content>{{ row.message }}</template>
                            </ExpandItem>

                            <ExpandItem class="w-full" v-if="row.dynamicMessage && row.dynamicMessage.length">
                                <template #title>动态内容</template>
                                <template #content>
                                    <div v-for="(dm, i) in row.dynamicMessage" :key="i">
                                        <div>
                                            <span>{{ dm.key }}: </span>
                                            <span>{{ dm.values.join(', ') }}</span>
                                        </div>
                                    </div>
                                </template>
                            </ExpandItem>

                            <ExpandItem v-if="isAdmin">
                                <template #title>RCS等待时间</template>
                                <template #content>{{ row.rcsWait }}</template>
                            </ExpandItem>

                            <ExpandItem class="expand-item" v-if="isAdmin">
                                <template #title>RCS发送间隔</template>
                                <template #content>{{ row.rcsInterval }}</template>
                            </ExpandItem>

                            <ExpandItem class="expand-item" v-if="isAdmin">
                                <template #title>清理数量</template>
                                <template #content>{{ row.cleanCount }}</template>
                            </ExpandItem>

                            <ExpandItem class="expand-item" v-if="isAdmin">
                                <template #title>请求号码间隔</template>
                                <template #content>{{ row.requestNumberInterval }}</template>
                            </ExpandItem>

                            <ExpandItem class="expand-item" v-if="isAdmin">
                                <template #title>检查连接</template>
                                <template #content>{{ row.checkConnection ? '是' : '否' }}</template>
                            </ExpandItem>
                        </div>

                        <div>
                            <div>
                                <ElButton
                                    type="primary"
                                    size="small"
                                    @click="getToBeSentNum(row)"
                                    v-if="row.status === 'queued'"
                                >
                                    排队状态
                                </ElButton>
                                <ElButton type="primary" size="small" @click="detail(row)">详情</ElButton>
                                <ElButton type="primary" size="small" @click="onEdit(row)" v-if="isAdmin">
                                    编辑
                                </ElButton>
                                <ElButton
                                    type="primary"
                                    size="small"
                                    @click="start(row)"
                                    v-if="row.status === 'idle' || row.status === 'pause'"
                                >
                                    开始
                                </ElButton>
                                <ElButton
                                    type="primary"
                                    size="small"
                                    @click="pause(row)"
                                    v-if="isAdminOrApi && row.status === 'pending'"
                                >
                                    暂停
                                </ElButton>
                                <ElButton
                                    type="primary"
                                    size="small"
                                    @click="receipt(row)"
                                    v-if="row.status === 'completed' || row.status === 'pause'"
                                >
                                    回执
                                </ElButton>
                                <ElButton type="danger" size="small" @click="del(row)" v-if="row.status === 'idle'">
                                    删除
                                </ElButton>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </ElTableColumn>
        <ElTableColumn prop="id" label="#" width="80" />
        <ElTableColumn prop="name" label="名称" show-overflow-tooltip />
        <ElTableColumn prop="remark" label="备注" show-overflow-tooltip />
        <ElTableColumn prop="listId" label="发送列表" :formatter="phoneListFormatter" />
        <ElTableColumn prop="userName" label="任务创建人" align="center" />
        <ElTableColumn prop="status" label="状态" align="center">
            <template #default="{ row }">
                <ElTag v-if="row.status === 'idle'" type="info">未发送</ElTag>
                <ElTag v-else-if="row.status === 'pending'">发送中</ElTag>
                <ElTag v-else-if="row.status === 'pause'" type="warning">暂停</ElTag>
                <ElTag v-else-if="row.status === 'completed'" type="success">已完成</ElTag>
                <ElTag v-else-if="row.status === 'queued'" type="warning">排队中</ElTag>
                <ElTag v-else-if="row.status === 'error'" type="danger">错误</ElTag>
                <ElTag v-else>未知</ElTag>
            </template>
        </ElTableColumn>
        <ElTableColumn prop="sent" label="已发送" align="center">
            <template #default="{ row }"> {{ row.sent || 0 }} / {{ row.total || 0 }}</template>
        </ElTableColumn>
        <ElTableColumn prop="successRate" label="发送成功率" align="center" />
        <ElTableColumn prop="createdAt" label="创建时间" :formatter="timeFormatter" width="150" />
        <ElTableColumn prop="startedAt" label="开始时间" :formatter="startedTimeFormatter" width="150" />
        <ElTableColumn prop="updatedAt" label="结束时间" :formatter="updatedTimeFormatter" width="150" />
    </PagingTable>
    <EditDialog
        class="task-edit-dialog"
        v-model="showEditDialog"
        :model="model"
        :rules="rules"
        :on-submit="submit"
        @success="table.refresh()"
        label-width="120px"
        :title="`${model.id ? '编辑' : '新建'}任务`"
        inline
    >
        <ElFormItem prop="name" label="名称">
            <ElInput v-model="model.name" placeholder="请输入名称" />
        </ElFormItem>
        <ElFormItem prop="remark" label="备注">
            <ElInput v-model="model.remark" placeholder="请输入备注" />
        </ElFormItem>
        <ElFormItem prop="listId" label="发送列表">
            <ElSelect v-model="model.listId" placeholder="请选择发送列表" :disabled="!!model.id">
                <ElOption v-for="item in phoneList" :key="item.id" :label="item.name" :value="item.id" />
            </ElSelect>
        </ElFormItem>
        <ElFormItem v-if="isAdmin" prop="country" label="国家列表">
            <ElSelect
                v-model="model.country"
                multiple
                placeholder="请选择国家列表"
                :collapse-tags="true"
                :collapse-tags-tooltip="true"
            >
                <ElOption v-for="item in countryList" :key="item" :value="item" />
            </ElSelect>
        </ElFormItem>
        <ElFormItem prop="message" label="内容" v-if="!model.id" class="!w-full">
            <ElInput v-model="model.message" placeholder="请输入内容" type="textarea" />
        </ElFormItem>
        <ElFormItem prop="dynamicMessage" label="动态内容" v-if="!model.id" class="!w-full">
            <div
                v-for="(dm, i) in model.dynamicMessage"
                :key="i"
                class="bg-neutral-100 dark:bg-neutral-900 p-3 rounded-md mb-4 w-full"
            >
                <div></div>
                <div>
                    <ElInput v-model="dm.key" placeholder="请先输入关键字" class="mb-2">
                        <template #append>
                            <ElButton :icon="Trash" @click="model.dynamicMessage.splice(i, 1)" />
                        </template>
                    </ElInput>
                </div>
                <ElInput v-model="dm.values" :disabled="!dm.key" placeholder="替换内容" type="textarea" />
            </div>
            <ElButton
                @click="
                    ;(model.dynamicMessage = model.dynamicMessage || []),
                        model.dynamicMessage.push({
                            key: '',
                            values: ''
                        })
                "
                :icon="Plus"
            />
        </ElFormItem>
        <ElFormItem v-if="isAdmin" prop="rcsWait" label="RCS等待时间">
            <ElInputNumber :controls="false" v-model="model.rcsWait" placeholder="请输入RCS等待时间" />
        </ElFormItem>
        <ElFormItem v-if="isAdmin" prop="rcsInterval" label="RCS发送间隔">
            <ElInputNumber :controls="false" v-model="model.rcsInterval" placeholder="请输入RCS发送间隔" />
        </ElFormItem>
        <ElFormItem v-if="isAdmin" prop="cleanCount" label="清理数量">
            <ElInputNumber :controls="false" v-model="model.cleanCount" placeholder="请输入清理数量" />
        </ElFormItem>
        <ElFormItem v-if="isAdmin" prop="requestNumberInterval" label="请求号码间隔">
            <ElInputNumber :controls="false" v-model="model.requestNumberInterval" placeholder="请输入请求号码间隔" />
        </ElFormItem>
        <ElFormItem v-if="isAdmin" prop="matchDevice" label="筛选设备">
            <ElInput v-model="model.matchDevice" placeholder="设备名称" />
        </ElFormItem>
        <ElFormItem v-if="isAdmin" prop="checkConnection" label="检查连接">
            <ElSwitch v-model="model.checkConnection" />
        </ElFormItem>
    </EditDialog>

    <ElDialog v-model="showDetailDialog" title="详情" width="800px">
        <PagingTable url="/task/item" :where="{ taskId: (selectedRow || {}).id }" ref="phoneTable" height="50vh">
            <ElTableColumn prop="id" label="#" width="80" />
            <ElTableColumn prop="number" label="号码" min-width="120" />
            <ElTableColumn prop="sendAt" label="发送时间" :formatter="timeFormatter" align="center" />
            <ElTableColumn prop="status" label="状态" align="center">
                <template #default="{ row }">
                    <el-tooltip class="box-item" effect="dark" content="Top Left prompts info" placement="top-start">
                        <ElTag v-if="row.status === 'success'" type="success">成功</ElTag>
                        <ElTag v-else-if="row.status === 'fail'" type="danger">失败</ElTag>
                        <ElTag v-else-if="row.status === 'pending'" type="warning">发送中</ElTag>
                        <ElTag v-else-if="row.status === 'idle'" type="info">待发送</ElTag>
                    </el-tooltip>
                </template>
            </ElTableColumn>
        </PagingTable>
    </ElDialog>

    <EditDialog
        v-model="showDmDialog"
        :model="dmModel"
        @success="table.refresh()"
        label-width="120px"
        title="编辑动态内容"
    >
        <ElFormItem prop="key" label="关键字">
            <ElInput v-model="dmModel.key" placeholder="请输入需要替换的关键字" />
        </ElFormItem>
        <ElFormItem prop="values" label="替换内容">
            <ElInput
                v-for="(item, index) in dmModel.values"
                v-model="dmModel.values[index]"
                :key="index"
                placeholder="请输入替换内容"
            >
                <template #append>
                    <ElButton @click="delValue(index)" :icon="Trash"></ElButton>
                </template>
            </ElInput>
            <ElButton @click="addValue" :icon="Plus"></ElButton>
        </ElFormItem>
    </EditDialog>
</template>
<script setup>
import { computed, inject, ref, onMounted } from 'vue'
import PagingTable from '@/components/PagingTable.vue'
import { useTimeFormatter } from '@/utils/formatter'
import { Plus, Refresh, Trash } from '@vicons/tabler'
import EditDialog from '@/components/EditDialog.vue'
import { setupEditDialog } from '@/utils/editDialog'
import { http } from '@/plugins/http'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/user'
import ExpandItem from '@/components/ExpandItem.vue'

const { user } = storeToRefs(useUserStore())
const where = ref({})
const isAdmin = inject('isAdmin')
const isAdminOrApi = inject('isAdminOrApi')
const timeFormatter = useTimeFormatter()
const table = ref(null)
const model = ref({
    checkConnection: true
})
const rules = {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    listId: [{ required: true, message: '请选择发送列表', trigger: 'blur' }],
    message: [{ required: true, message: '请输入内容', trigger: 'blur' }],
    dynamicMessage: [{ required: false, message: '请输入动态内容', trigger: 'blur' }],
    rcsWait: [{ required: false, message: '请输入RCS等待时间', trigger: 'blur' }],
    rcsInterval: [{ required: false, message: '请输入RCS发送间隔', trigger: 'blur' }],
    cleanCount: [{ required: false, message: '请输入清理数量', trigger: 'blur' }],
    requestNumberInterval: [{ required: false, message: '请输入请求号码间隔', trigger: 'blur' }],
    checkConnection: [{ required: false, message: '请选择是否检查连接', trigger: 'blur' }]
}
const { showEditDialog, onEdit } = setupEditDialog(model)

const countryList = ref([])
onMounted(() => {
    http.post('operator-config', { size: 10000 }).then((res) => {
        countryList.value = res.items.map((item) => item.country)
    })
})

const startedTimeFormatter = (row, column, value, index) => {
    if (row.status !== 'idle') {
        return timeFormatter(row, column, value, index);
    }
    return '';
};

const updatedTimeFormatter = (row, column, value, index) => {
    if (row.status === 'completed') {
        return timeFormatter(row, column, value, index);
    }
    return '';
};

function rowClick(row, column) {
    table.value.tableEl.toggleRowExpansion(row)
}

async function submit() {
    const result = await http.put(model.value.id ? `/task/${model.value.id}` : '/task', {
        ...model.value,
        dynamicMessage: model.value.id
            ? model.value.dynamicMessage
            : model.value.dynamicMessage?.map((item) => ({
            key: item.key,
            values: item.values
                .split('\n')
                .map((v) => v.trim())
                .filter((v) => !!v)
        })) || [],
        userId: user.value.id
    })
    if (result) {
        ElMessage.success('保存成功')
    } else {
        ElMessage.warning('所选择发送列表未添加号码,请先导入号码后再添加任务')
    }
}

const phoneList = ref([])

async function getPhoneList() {
    phoneList.value = (
        await http.post('/phone-list', {
            search: { page: { page: 1, limit: 100 }, order: { createdAt: 'DESC' }, where: where.value }
        })
    ).items
}

getPhoneList()

function phoneListFormatter(row, column, cellValue, index) {
    return phoneList.value.find((item) => item.id === cellValue)?.name
}

function del(row) {
    ElMessageBox.confirm('确定删除吗？', '提示', {
        type: 'warning'
    }).then(() => {
        http.delete(`/task/${row.id}`).then(() => {
            ElMessage.success('删除成功')
            table.value.refresh()
        })
    })
}

const selectedRow = ref(null)
const showDetailDialog = ref(false)
const phoneTable = ref(null)

function detail(row) {
    selectedRow.value = row
    showDetailDialog.value = true
}

function taskStatusFormatter(row, column, cellValue, index) {
    switch (cellValue) {
        case 'idle':
            return '未发送'
        case 'pending':
            return '发送中'
        case 'completed':
            return '已发送'
        case 'error':
            return '错误'
        default:
            return '未知'
    }
}

function taskItemStatusFormatter(row, column, cellValue, index) {
    switch (cellValue) {
        case 'idle':
            return '未发送'
        case 'pending':
            return '发送中'
        case 'success':
            return '成功'
        case 'fail':
            return '失败'
        default:
            return '未知'
    }
}

async function getToBeSentNum(row) {
    const num = await http.get(`/task/toBeSentNum/${row.id}`)
    await ElMessageBox.alert('队列中还有' + num + '条数据待发送,请耐心等待.', '排队消息')
}

async function start(row) {
    const cost = await http.get(`/task/verification/${row.id}`)
    const num = await http.get(`/task/toBeSentNum/${row.id}`)
    let message = ''
    if (cost > 0 && row.status === 'idle') {
        if (num > 0) {
            message = `该任务需要从余额中扣除 ${cost} ,且当前系统剩余 ${num} 条待发送号码,需要排队,是否继续?`
        } else {
            message = `该任务需要从余额中扣除 ${cost} ,是否继续?`
        }
        const confirm = await ElMessageBox.confirm(message, '提示', {
            type: 'warning'
        })
        if (confirm) {
            await http.post(`/task/${row.id}/start`)
            table.value.refresh()
        }
    } else if (cost < 0 && row.status === 'idle') {
        await ElMessageBox.alert('余额不足,请充值后再启动任务.', '提示')
        table.value.refresh()
    } else {
        if (num > 0) {
            message = `剩余 ${num} 条待发送号码,是否继续?`
        } else {
            message = `确定开始发送吗?`
        }
        await ElMessageBox.confirm(message, '提示', {
            type: 'warning'
        })
        await http.post(`/task/${row.id}/start`)
        table.value.refresh()
    }
}

async function pause(row) {
    await ElMessageBox.confirm('确定暂停发送吗？', '提示', {
        type: 'warning'
    })
    await http.post(`/task/${row.id}/pause`)
    table.value.refresh()
}

async function receipt(row) {
    const loading = ElLoading.service({
        lock: true,
        text: '正在生成回执...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
    const successNum = await http.get(`/task/num/${row.id}`)
    try {
        const response = await http.post(`/task/item/${row.id}/receipt`)
        const uint8Array = new Uint8Array(response.data)
        const blob = new Blob([uint8Array], { type: 'application/octet-stream' })
        const link = document.createElement('a')
        const blobUrl = URL.createObjectURL(blob)
        link.href = blobUrl
        link.download = `${row.name}_发送成功${successNum}_回执.xlsx`
        link.click()
        window.URL.revokeObjectURL(blobUrl)
        loading.close()
    } catch (error) {
        loading.close()
        console.error('Error receipt:', error)
        ElMessage.error('获取回执错误,请稍后再试.')
    }
}

const dmModel = ref({
    key: '',
    values: []
})
const showDmDialog = ref(false)

function editDm(row) {
    dmModel.value = row || {
        key: '',
        values: []
    }
    showDmDialog.value = true
}

function addValue() {
    dmModel.value.values.push('')
}

function delValue(index) {
    dmModel.value.values.splice(index, 1)
}
</script>
<style lang="less" scoped>
.tip {
    color: #999;
    font-size: 12px;
    margin-left: 10px;
}

.task-edit-dialog {
    .el-form-item {
        width: 50%;
        margin-right: 0;
        padding-left: 20px;
        vertical-align: top;
    }

    .el-input,
    .el-input-number,
    .el-select {
        width: 100% !important;
    }
}
</style>
