<template>
    <div class="app-container">

        <!-- 查询和其他操作 -->
        <div class="filter-container">
            <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;"
                placeholder="请输入广告标题" />
            <el-input v-model="listQuery.content" clearable class="filter-item" style="width: 200px;"
                placeholder="请输入广告内容" />
            <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">查找</el-button>
            <el-button class="filter-item" type="primary" icon="plus" @click="handleCreate">添加</el-button>
            <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="download"
                @click="handleDownload">导出</el-button>
        </div>

        <!-- 查询结果 -->
        <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

            <el-table-column align="center" label="广告ID" prop="id" sortable />

            <el-table-column align="center" label="广告标题" prop="name" />

            <el-table-column align="center" label="广告内容" prop="content" />

            <el-table-column align="center" label="广告图片" prop="url">
                <template #default="scope">
                    <el-image :src="scope.row.url" :preview-src-list="srcList" preview-teleported="true"
                        style="width: 80px; height: 40px" :initial-index="scope.$index" />
                </template>
            </el-table-column>

            <el-table-column align="center" label="广告位置" prop="position" />

            <el-table-column align="center" label="活动链接" prop="link" />

            <el-table-column align="center" label="是否启用" prop="enabled">
                <template #default="scope">
                    <el-tag :type="scope.row.enabled ? 'success' : 'error'">{{ scope.row.enabled ? '启用' : '不启用' }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="primary" link @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <litemall-page :page-data="listQuery" :total="total" @size-change="sizeChange"
            @current-change="currentChange" />

        <!-- 添加或修改对话框 -->
        <el-dialog :title="textMap[dialogStatus]" v-model="dialogFormVisible">
            <el-form ref="dataFormRef" :rules="rules" :model="dataForm" status-icon label-position="left"
                label-width="100px" style="width: 400px; margin-left:50px;">
                <el-form-item label="广告标题" prop="name">
                    <el-input v-model="dataForm.name" />
                </el-form-item>
                <el-form-item label="广告内容" prop="content">
                    <el-input v-model="dataForm.content" />
                </el-form-item>
                <el-form-item label="广告图片" prop="url">
                    <el-upload :headers="headers" :action="uploadPath" :show-file-list="false" :on-success="uploadUrl"
                        :before-upload="checkFileSize" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
                        <img v-if="dataForm.url" :src="dataForm.url" class="avatar">
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">
                                只能上传jpg/png文件，且不超过1024kb
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="广告位置" prop="position">
                    <el-select v-model="dataForm.position" placeholder="请选择">
                        <el-option :value="1" label="首页" />
                    </el-select>
                </el-form-item>
                <el-form-item label="活动链接" prop="link">
                    <el-input v-model="dataForm.link" />
                </el-form-item>
                <el-form-item label="是否启用" prop="enabled">
                    <el-select v-model="dataForm.enabled" placeholder="请选择">
                        <el-option :value="true" label="启用" />
                        <el-option :value="false" label="不启用" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
                <el-button v-else type="primary" @click="updateData">确定</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { listAd, createAd, updateAd, deleteAd } from '@/services/api/promotion/ad'
import { ElMessage, ElMessageBox } from 'element-plus';
import { uploadPath } from '@/services/api/storage'
import LitemallPage from "@/components/pagination/litemallPage.vue";


let list = ref([] as any)
let total = ref(0)
let listLoading = ref(true)
let srcList = ref([] as any) //图片预览地址
let listQuery = ref({
    page: 1,
    limit: 10,
    name: undefined,
    content: undefined,
    sort: 'add_time',
    order: 'desc'
})
let dataForm = ref({
    id: undefined,
    name: undefined,
    content: undefined,
    url: undefined,
    link: undefined,
    position: 1,
    enabled: true
} as any)
let dataFormRef = ref()
let dialogFormVisible = ref(false)
let dialogStatus = ref('')
let textMap = ref({
    update: '编辑',
    create: '创建'
} as any)
let rules = ref({
    name: [
        { required: true, message: '广告标题不能为空', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '广告内容不能为空', trigger: 'blur' }
    ],
    url: [{ required: true, message: '广告图片不能为空', trigger: 'blur' }]
})
let downloadLoading = ref(false)
let headers = computed(() => {
    return {
        'Authorization': sessionStorage.getItem('token')
    }
})

let getList = () => {
    listLoading.value = true
    listAd(listQuery.value)
        .then((res: any) => {
            let urls = [] as any
            res.data.list.forEach((item: any) => { urls.push(item.url) })
            srcList.value = urls
            urls = []
            list.value = res.data.list
            total.value = res.data.total
            listLoading.value = false
        })
        .catch(() => {
            list.value = []
            total.value = 0
            listLoading.value = false
        })
}
getList()

let currentChange = (val: number) => {
    listQuery.value.page = val
    getList()
}

let sizeChange = (val: number) => {
    listQuery.value.limit = val
    getList()
}

let handleFilter = () => {
    listQuery.value.page = 1
    getList()
}
let resetForm = () => {
    dataForm.value = {
        id: undefined,
        name: undefined,
        content: undefined,
        url: undefined,
        link: undefined,
        position: 1,
        enabled: true
    }
}
let handleCreate = () => {
    resetForm()
    dialogStatus.value = 'create'
    dialogFormVisible.value = true
    nextTick(() => {
        dataFormRef.value?.clearValidate()
    })
}
let uploadUrl = (res: any) => {
    dataForm.value.url = res.data.url
}
let checkFileSize = (file: any) => {
    if (file.size > 1048576) {
        ElMessage.error(`${file.name}文件大于1024KB，请选择小于1024KB大小的图片`)
        return false
    }
    return true
}
let createData = () => {
    dataFormRef.value?.validate((valid: any) => {
        if (valid) {
            createAd(dataForm.value)
                .then((res: any) => {
                    list.value.unshift(res.data)
                    dialogFormVisible.value = false
                    ElMessage({
                        type: 'success',
                        message: '创建成功'
                    })
                })
                .catch(res => {
                    ElMessage({
                        type: 'error',
                        message: res.data.msg
                    })
                })
        }
    })
}
let handleUpdate = (row: any) => {
    dataForm.value = Object.assign({}, row)
    dialogStatus.value = 'update'
    dialogFormVisible.value = true
    nextTick(() => {
        dataFormRef.value?.clearValidate()
    })
}
let updateData = () => {
    dataFormRef.value?.validate((valid: any) => {
        if (valid) {
            updateAd(dataForm.value)
                .then(() => {
                    for (const v of list.value) {
                        if (v.id === dataForm.value.id) {
                            const index = list.value.indexOf(v)
                            list.value.splice(index, 1, dataForm.value)
                            break
                        }
                    }
                    dialogFormVisible.value = false
                    ElMessage({
                        type: 'success',
                        message: '更新广告成功'
                    })
                })
                .catch(res => {
                    ElMessage.error({
                        type: 'error',
                        message: res.data.msg
                    })
                })
        }
    })
}
let handleDelete = (row: any) => {
    ElMessageBox.confirm(
        '确认删除?', '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
            deleteAd(row)
                .then((res: any) => {
                    if (res.code === 200) {
                        ElMessage({
                            type: 'success',
                            message: '删除成功'
                        })
                        getList()
                    }
                })
                .catch(res => {
                    ElMessage({
                        type: 'error',
                        message: res.msg
                    })
                })
        })
}
let handleDownload = () => {
    // downloadLoading.value = true
    // import('@/vendor/Export2Excel').then(excel => {
    //     const tHeader = [
    //         '广告ID',
    //         '广告标题',
    //         '广告内容',
    //         '广告图片',
    //         '广告位置',
    //         '活动链接',
    //         '是否启用'
    //     ]
    //     const filterVal = [
    //         'id',
    //         'name',
    //         'content',
    //         'url',
    //         'postion',
    //         'link',
    //         'enabled'
    //     ]
    //     excel.export_json_to_excel2(tHeader, list, filterVal, '广告信息')
    //     downloadLoading.value = false
    // })
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.avatar {
    width: 145px;
    height: 145px;
    display: block;
}
</style>