<template>
    <PagingTable url="/task" :where="where" ref="table">
        <template #filter>
            <ElButton :icon="Refresh" @click="table.refresh()"></ElButton>
            <ElButton :icon="Plus" @click="onEdit(), getPhoneList()"> 添加</ElButton>
        </template>
        <ElTableColumn prop="id" label="#" width="80" />
        <ElTableColumn prop="name" label="名称" min-width="120" />
        <ElTableColumn prop="remark" label="备注" show-overflow-tooltip />
        <ElTableColumn prop="message" label="内容" show-overflow-tooltip />
        <ElTableColumn prop="listId" label="发送列表" :formatter="phoneListFormatter" />
        <ElTableColumn prop="rcsWait" label="RCS等待时间" />
        <ElTableColumn prop="rcsInterval" label="RCS发送间隔" />
        <ElTableColumn prop="cleanCount" label="清理数量" />
        <ElTableColumn prop="requestNumberInterval" label="请求号码间隔" />
        <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 === 'error'" type="danger">错误</ElTag>
                <ElTag v-else>未知</ElTag>
            </template>
        </ElTableColumn>
        <ElTableColumn prop="sent" label="已发送" align="center" />
        <ElTableColumn prop="successRate" label="发送成功率" align="center" />
        <ElTableColumn prop="createdAt" label="创建时间" :formatter="timeFormatter" width="150" />
        <ElTableColumn label="操作" align="center" width="200">
            <template #default="{ row }">
                <ElButton type="primary" size="small" @click="detail(row)">详情</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="row.status === 'pending'">
                    暂停
                </ElButton>
                <ElButton type="primary" size="small" @click="receipt(row)" v-if="row.status === 'completed'">
                    回执
                </ElButton>
                <ElButton type="danger" size="small" @click="del(row)" v-if="row.status === 'idle'">删除</ElButton>
            </template>
        </ElTableColumn>
    </PagingTable>
    <EditDialog
        v-model="showEditDialog"
        :model="model"
        :rules="rules"
        :on-submit="submit"
        @success="table.refresh()"
        label-width="120px"
    >
        <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="请选择发送列表">
                <ElOption v-for="item in phoneList" :key="item.id" :label="item.name" :value="item.id" />
            </ElSelect>
        </ElFormItem>
        <ElFormItem prop="listId" label="渠道列表">
            <ElSelect v-model="model.channelId" placeholder="请选择渠道列表">
                <ElOption v-for="item in operatorList" :key="item.id"
                          :label="item.mcc+'-'+item.mnc+'-'+item.country+'-'+item.operator" :value="item.id" />
            </ElSelect>
        </ElFormItem>
        <ElFormItem prop="message" label="内容">
            <ElInput v-model="model.message" placeholder="请输入内容" type="textarea" />
        </ElFormItem>
        <ElFormItem prop="rcsWait" label="RCS等待时间">
            <ElInputNumber :controls="false" v-model="model.rcsWait" placeholder="请输入RCS等待时间" />
            <div class="tip">(0表示使用系统默认值)</div>
        </ElFormItem>
        <ElFormItem prop="rcsInterval" label="RCS发送间隔">
            <ElInputNumber :controls="false" v-model="model.rcsInterval" placeholder="请输入RCS发送间隔" />
            <div class="tip">(0表示使用系统默认值)</div>
        </ElFormItem>
        <ElFormItem prop="cleanCount" label="清理数量">
            <ElInputNumber :controls="false" v-model="model.cleanCount" placeholder="请输入清理数量" />
            <div class="tip">(0表示使用系统默认值)</div>
        </ElFormItem>
        <ElFormItem prop="requestNumberInterval" label="请求号码间隔">
            <ElInputNumber :controls="false" v-model="model.requestNumberInterval" placeholder="请输入请求号码间隔" />
            <div class="tip">(0表示使用系统默认值)</div>
        </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 }">
                    <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>
                </template>
            </ElTableColumn>
        </PagingTable>
    </ElDialog>

    <EditDialog
        v-model="showPhoneEditDialog"
        :model="phoneModel"
        :rules="phoneRules"
        :on-submit="submitPhone"
        @success="phoneTable.refresh()"
    >
        <ElFormItem prop="number" label="号码">
            <ElInput v-model="phoneModel.number" placeholder="号码" />
        </ElFormItem>
    </EditDialog>
</template>
<script setup>
import { ref } from 'vue'
import PagingTable from '@/components/PagingTable.vue'
import { useTimeFormatter } from '@/utils/formatter'
import { Plus, Refresh } from '@vicons/tabler'
import EditDialog from '@/components/EditDialog.vue'
import { setupEditDialog } from '@/utils/editDialog'
import { http } from '@/plugins/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const { user } = useUserStore()
console.log(user)
const where = ref({})
const timeFormatter = useTimeFormatter()
const table = ref(null)
const model = ref({})
const rules = {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    listId: [{ required: true, message: '请选择发送列表', trigger: 'blur' }],
    channelId: [{ required: true, message: '请选择渠道列表', trigger: 'blur' }],
    message: [{ required: true, message: '请输入内容', trigger: 'blur' }],
    rcsWait: [{ required: true, message: '请输入RCS等待时间', trigger: 'blur' }],
    rcsInterval: [{ required: true, message: '请输入RCS发送间隔', trigger: 'blur' }],
    cleanCount: [{ required: true, message: '请输入清理数量', trigger: 'blur' }],
    requestNumberInterval: [{ required: true, message: '请输入请求号码间隔', trigger: 'blur' }]
}
const { showEditDialog, onEdit } = setupEditDialog(model)

async function submit() {
    model.value.userId = user.id
    await http.put('/task', model.value)
    ElMessage.success('保存成功')
}

const phoneList = ref([])

async function getPhoneList() {
    phoneList.value = (await http.post('/phone-list')).items
}

getPhoneList()
const operatorList = ref([])

async function getOperatorList() {
    operatorList.value = (await http.post('/channel')).items
}

getOperatorList()

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
}

const phoneModel = ref({})
const phoneRules = {
    number: [{ required: true, message: '请输入号码', trigger: 'blur' }]
}
const { showEditDialog: showPhoneEditDialog, onEdit: onPhoneEdit } = setupEditDialog(phoneModel)

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 start(row) {
    await ElMessageBox.confirm('确定开始发送吗？', '提示', {
        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) {
    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}_回执.xlsx`
        link.click()
        window.URL.revokeObjectURL(blobUrl)
    } catch (error) {
        console.error('Error receipt:', error)
        ElMessage.error('获取回执错误,请稍后再试.')
    }
}
</script>
<style lang="less" scoped>
.tip {
    color: #999;
    font-size: 12px;
    margin-left: 10px;
}
</style>
