<template>
    <el-drawer v-model="createDrawer" title="新增专题" size="50%" :before-close="handleCancel">
        <el-form ref="topicRef" :rules="rules" :model="topic" status-icon label-position="left" label-width="100px"
            style="width: 800px; margin-left:50px;">
            <el-form-item label="专题标题" prop="title">
                <el-input v-model="topic.title" />
            </el-form-item>
            <el-form-item label="专题子标题" prop="subtitle">
                <el-input v-model="topic.subtitle" />
            </el-form-item>
            <el-form-item label="专题图片" prop="picUrl">
                <el-upload :headers="headers" :action="uploadPath" :show-file-list="false" :on-success="uploadPicUrl"
                    class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
                    <img v-if="topic.picUrl" :src="topic.picUrl" class="avatar">
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="专题内容" prop="content">
                <richTextEditor :valueHtml='topic.content' @htmlChange="htmlChange" />
            </el-form-item>
            <el-form-item label="商品低价" prop="price">
                <el-input v-model="topic.price" />
            </el-form-item>
            <el-form-item label="阅读量" prop="readCount">
                <el-input v-model="topic.readCount" />
            </el-form-item>
            <el-form-item label="专题商品" prop="goods">
                <div style="display: flex; justify-content: end; width: 100%;">
                    <el-button style="margin-bottom: 10px;" size="small" type="primary" @click="handleCreate()">创建商品
                    </el-button>
                </div>

                <!-- 查询结果 -->
                <el-table :data="goodsList" border fit highlight-current-row>

                    <el-table-column align="center" label="商品ID" prop="id" />
                    <el-table-column align="center" prop="picUrl" label="图片">
                        <template #default="scope">
                            <img :src="scope.row.picUrl" width="60">
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="商品名称" prop="name" />
                    <el-table-column align="center" label="商品介绍" prop="brief" />
                    <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
                        <template #default="scope">
                            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
        </el-form>
        <template #footer class="dialog-footer">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleConfirm">确定</el-button>
        </template>
    </el-drawer>

    <el-dialog v-model="addVisiable" title="添加商品">
        <div class="search">
            <div class="filter-container">
                <el-input v-model="listQuery.goodsSn" clearable class="filter-item" style="width: 200px;"
                    placeholder="请输入商品编号" />
                <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;"
                    placeholder="请输入商品名称" />
                <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">查找</el-button>
            </div>
            <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit
                highlight-current-row @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column align="center" label="商品ID" prop="id" />
                <el-table-column align="center" prop="picUrl" label="图片">
                    <template #default="scope">
                        <img :src="scope.row.picUrl" width="40">
                    </template>
                </el-table-column>
                <el-table-column align="center" label="商品名称" prop="name" />
            </el-table>

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

        </div>
        <template #footer class="dialog-footer">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="confirmAdd">确定</el-button>
        </template>
    </el-dialog>

</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { createTopic } from '@/services/api/promotion/topic'
import { listGoods } from '@/services/api/commodityManage/list'
import { uploadPath } from '@/services/api/storage'
import { ElMessage } from "element-plus";
import LitemallPage from "@/components/pagination/litemallPage.vue";
import richTextEditor from '@/components/richTextEditor.vue'

let emits = defineEmits(['init'])
let topic = ref({
    goods: [],
    title: '',
    subtitle: '',
    picUrl: '',
    price: '',
    readCount: '',
} as any)
let createDrawer = ref(false)
let topicRef = ref()
let goodsList = ref([] as any)
let addVisiable = ref(false)
let list = ref([])
let total = ref(0)
let listLoading = ref(false)
let listQuery = ref({
    page: 1,
    limit: 10,
    id: undefined,
    name: undefined,
    sort: 'add_time',
    order: 'desc',
    goodsSn: ''
})
let selectedlist = ref([])
let rules = ref({
    title: [
        { required: true, message: '专题标题不能为空', trigger: 'blur' }
    ],
    subtitle: [
        { required: true, message: '专题子标题不能为空', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '专题内容不能为空', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '专题低价不能为空', trigger: 'blur' }
    ]
})
let headers = computed(() => {
    return {
        'Authorization': sessionStorage.getItem('token')
    }
})

let htmlChange = (value: any) => topic.value.content = value

let getList = () => {
    listLoading.value = true
    listGoods(listQuery.value).then((res: any) => {
        if (res.code === 200) {
            list.value = res.data.list
            total.value = res.data.total
            listLoading.value = false
        }
    }).catch(() => {
        list.value = []
        total.value = 0
        listLoading.value = false
    })
}

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 handleSelectionChange = (val: any) => {
    selectedlist.value = val
    console.log(selectedlist.value);

}
let uploadPicUrl = (res: any) => {
    topic.value.picUrl = res.data.url
}
let handleCreate = () => {
    listQuery.value = {
        page: 1,
        limit: 10,
        id: undefined,
        name: undefined,
        sort: 'add_time',
        order: 'desc',
        goodsSn: ''
    }
    list.value = []
    total.value = 0
    selectedlist.value = []
    addVisiable.value = true
}
let confirmAdd = () => {
    const newGoodsIds = [] as any
    const newGoodsList = [] as any

    selectedlist.value.forEach((item: any) => {
        const id = item.id
        let found = false

        topic.value.goods?.forEach((goodsId: any) => {
            if (id === goodsId) {
                found = true
            }
        })
        if (!found) {
            newGoodsIds.push(id)
            newGoodsList.push(item)
        }
    })

    if (newGoodsIds.length > 0) {
        topic.value.goods = topic.value.goods?.concat(newGoodsIds)
        goodsList.value = goodsList.value?.concat(newGoodsList)
    }
    addVisiable.value = false
}
let handleDelete = (row: any) => {
    for (var index = 0; index < topic.value.goods.length; index++) {
        if (row.id === topic.value.goods[index]) {
            topic.value.goods.splice(index, 1)
        }
    }
    for (var index2 = 0; index2 < goodsList.value.length; index2++) {
        if (row.id === goodsList.value[index2].id) {
            goodsList.value.splice(index2, 1)
        }
    }
}
let handleCancel = () => {
    topic.value = {
        goods: [],
        title: '',
        subtitle: '',
        picUrl: '',
        price: '',
        readCount: '',
    }
    goodsList.value = []
    createDrawer.value = false
}
let handleConfirm = () => {
    topicRef.value?.validate((valid: any) => {
        if (valid) {
            createTopic(topic.value).then((res: any) => {
                if (res.code === 200) {
                    handleCancel()
                    emits('init')
                }
            })
                .catch(res => {
                    ElMessage({
                        type: 'error',
                        message: res.msg
                    })
                })
        }
    })
}

defineExpose({
    createDrawer
})
</script>


<style>
.el-dialog {
    width: 800px;
}

.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>