<template>
    <PagingTable url="/phone-list" :where="where" ref="table">
        <template #filter>
            <ElButton :icon="Plus" @click="onEdit()">添加</ElButton>
        </template>
        <ElTableColumn prop="id" label="#" width="80" />
        <ElTableColumn prop="name" label="名称" show-overflow-tooltip />
        <ElTableColumn prop="remark" label="备注" show-overflow-tooltip />
        <ElTableColumn prop="userName" 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="danger" size="small" @click="del(row)">删除</ElButton>
                <ElButton @click="download(row)" v-if="isAdmin">下载</ElButton>
            </template>
        </ElTableColumn>
    </PagingTable>
    <EditDialog v-model="showEditDialog" :model="model" :rules="rules" :on-submit="submit" @success="table.refresh()">
        <ElFormItem prop="name" label="昵称">
            <ElInput v-model="model.name" placeholder="请输入昵称" />
        </ElFormItem>
        <ElFormItem prop="remark" label="备注">
            <ElInput v-model="model.remark" placeholder="请输入备注" />
        </ElFormItem>
    </EditDialog>

    <ElDialog v-model="showDetailDialog" title="详情" width="800px">
        <PagingTable url="/phone-list/phone" :where="{ listId: (selectedRow || {}).id }" ref="phoneTable" height="50vh">
            <template #filter>
                <ElButton :icon="Plus" @click="onPhoneEdit()">添加</ElButton>
                <ElButton :icon="Plus" @click="importList()">导入</ElButton>
            </template>
            <ElTableColumn prop="id" label="#" width="80" />
            <ElTableColumn prop="number" label="号码" min-width="120" />
            <ElTableColumn label="操作" align="center" width="200">
                <template #default="{ row }">
                    <ElButton type="primary" size="small" @click="onPhoneEdit(row)">编辑</ElButton>
                    <ElButton type="danger" size="small" @click="delPhone(row)">删除</ElButton>
                </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 { inject, ref } from 'vue'
import PagingTable from '@/components/PagingTable.vue'
import { useTimeFormatter } from '@/utils/formatter'
import { Plus } from '@vicons/tabler'
import EditDialog from '@/components/EditDialog.vue'
import { setupEditDialog } from '@/utils/editDialog'
import EnumSelect from '@/components/EnumSelect.vue'
import { UserRole } from '@/enums'
import { axiosInstance, http } from '@/plugins/http'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { useClipboard } from '@vueuse/core'
import { useUserStore } from '@/stores/user'

const isAdmin = inject('isAdmin')
const where = ref({})
const timeFormatter = useTimeFormatter()
const table = ref(null)
const model = ref({})
const rules = {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
}
const { showEditDialog, onEdit } = setupEditDialog(model)

async function submit() {
    await http.put('/phone-list', model.value)
    ElMessage.success('保存成功')
}

function del(row) {
    ElMessageBox.confirm('确定删除吗？', '提示', {
        type: 'warning'
    }).then(() => {
        http.delete(`/phone-list/${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)

async function submitPhone() {
    phoneModel.value.listId = selectedRow.value.id
    await http.put('/phone-list/phone', phoneModel.value)
    ElMessage.success('保存成功')
}

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

const importing = ref(false)

function importList() {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.txt'
    input.onchange = async () => {
        const loading = ElLoading.service({
            lock: true,
            text: '导入中...',
            background: 'rgba(0, 0, 0, 0.7)'
        })
        const file = input.files[0]
        const formData = new FormData()
        formData.append('file', file)
        try {
            importing.value = true
            await http.post(`/phone-list/${selectedRow.value.id}/import`, formData)
            loading.close()
            ElMessage.success('导入成功')
        } catch (e) {
            loading.close()
            ElMessage.error(e.message || '导入失败')
        }
        importing.value = false
        phoneTable.value.refresh()
    }
    input.click()
}

function download(row) {
    axiosInstance.get(`/phone-list/${row.id}/download`, { responseType: 'blob' }).then((res) => {
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', `${row.number}.txt`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    })
}
</script>
