<template>
    <div class="app-container">
        <!-- 查询和其他操作 -->
        <div class="filter-container">
            <el-button class="filter-item" type="primary" icon="edit" @click="handleCreate">添加</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" />

            <el-table-column align="center" label="类目名" prop="name" />

            <el-table-column align="center" property="iconUrl" label="类目图标">
                <template #default="scope">
                    <img v-if="scope.row.iconUrl" :src="scope.row.iconUrl" width="40" />
                </template>
            </el-table-column>

            <el-table-column align="center" property="picUrl" label="类目图片">
                <template #default="scope">
                    <el-image :src="scope.row.picUrl" style="width: 100px; height: 40px"></el-image>
                    <!-- <el-image :src="thumbnail(scope.row.picUrl)"
                        :preview-src-list="toPreview(scope.row, scope.row.picUrl)" style="width: 80px; height: 40px" /> -->
                </template>
            </el-table-column>

            <el-table-column align="center" label="关键字" prop="keywords" />

            <el-table-column align="center" min-width="100" label="简介" prop="desc" />

            <el-table-column align="center" label="级别" prop="level">
                <template #default="scope">
                    <el-tag :type="scope.row.level === 'L1' ? 'primary' : 'info'">{{
                            scope.row.level === "L1" ? "一级类目" : "二级类目"
                    }}</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" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @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="keywords">
                    <el-input v-model="dataForm.keywords" />
                </el-form-item>
                <el-form-item label="级别" prop="level">
                    <el-select v-model="dataForm.level" @change="onLevelChange">
                        <el-option label="一级类目" value="L1" />
                        <el-option label="二级类目" value="L2" />
                    </el-select>
                </el-form-item>
                <el-form-item v-if="dataForm.level === 'L2'" label="父类目" prop="pid">
                    <el-select v-model="dataForm.pid">
                        <el-option v-for="item in catL1" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="类目图标" prop="iconUrl">
                    <el-upload :headers="headers" :action="uploadPath" :show-file-list="false" list-type='picture'
                        :on-success="uploadIconUrl" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
                        <img v-if="dataForm.iconUrl" :src="dataForm.iconUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </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="dataForm.iconUrl" :src="dataForm.iconUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="类目简介" prop="desc">
                    <el-input v-model="dataForm.desc" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span 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>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, nextTick } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import {
    listCategory,
    listCatL1,
    createCategory,
    updateCategory,
    deleteCategory,
} from "@/services/api/market/category";
import { uploadPath } from "@/services/api/storage";
import LitemallPage from "@/components/pagination/litemallPage.vue";
// import { thumbnail, toPreview } from "@/utils/index";

let dataFormRef = ref();
let list = ref([] as any);
let listLoading = ref(true);
let catL1 = ref({} as any);
let dataForm = reactive({
    id: undefined,
    name: "",
    keywords: "",
    level: "L2",
    pid: 0,
    desc: "",
    iconUrl: "",
    picUrl: "",
});
let listQuery = ref({
    page: 1,
    limit: 10,
    sort: "add_time",
    order: "desc",
});
let total = ref(0)
let dialogFormVisible = ref(false);
let dialogStatus = ref("");
let textMap = reactive({
    update: "编辑",
    create: "创建",
} as any);
let rules = reactive({
    name: [{ required: true, message: "类目名不能为空", trigger: "blur" }],
});

let headers = computed(() => {
    return {
        'Authorization': localStorage.getItem("token"),
    };
});

let getList = () => {
    listLoading.value = true;
    listCategory(listQuery.value)
        .then((res: any) => {
            list.value = res.data.list;
            total.value = res.data.total
            console.log(res);

            listLoading.value = false;
        })
        .catch(() => {
            list.value = [];
            listLoading.value = false;
        });
};
getList()
let getCatL1 = () => {
    listCatL1().then((res: any) => {
        catL1.value = res.data.list;
    });
};
getCatL1()

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

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

let resetForm = () => {
    dataForm = {
        id: undefined,
        name: "",
        keywords: "",
        level: "L2",
        pid: 0,
        desc: "",
        iconUrl: "",
        picUrl: "",
    };
};
let onLevelChange = (value: any) => {
    if (value === "L1") {
        dataForm.pid = 0;
    }
};
let handleCreate = () => {
    resetForm();
    dialogStatus.value = "create";
    dialogFormVisible.value = true;
    nextTick(() => {
        dataFormRef.value?.clearValidate();
    });
};
let uploadIconUrl = (res: any) => {
    dataForm.iconUrl = res.data.url;
};
let uploadPicUrl = (res: any) => {
    dataForm.picUrl = res.data.url;
};
let createData = () => {
    dataFormRef.value?.validate((valid: any) => {
        if (valid) {
            createCategory(dataForm)
                .then((res: any) => {
                    getList();
                    // 更新L1目录
                    getCatL1();
                    dialogFormVisible.value = false;
                    ElNotification.success({
                        type: 'success',
                        title: "成功",
                        message: "创建成功",
                    });
                })
                .catch((res: any) => {
                    ElNotification({
                        title: "失败",
                        message: res.data.errmsg,
                    });
                });
        }
    });
};
let handleUpdate = (row: any) => {
    dataForm = Object.assign({}, row);
    dialogStatus.value = "update";
    dialogFormVisible.value = true;
    nextTick(() => {
        dataFormRef.value?.clearValidate();
    });
};
let updateData = () => {
    dataFormRef.value?.validate((valid: any) => {
        if (valid) {
            updateCategory(dataForm)
                .then(() => {
                    getList();
                    // 更新L1目录
                    getCatL1();
                    dialogFormVisible.value = false;
                    ElNotification({
                        type: 'success',
                        title: "成功",
                        message: "更新成功",
                    });
                })
                .catch((res: any) => {
                    ElNotification({
                        title: "失败",
                        message: res.data.errmsg,
                    });
                });
        }
    });
};
let handleDelete = (row: any) => {
    deleteCategory(row)
        .then((res: any) => {
            getList();
            // 更新L1目录
            getCatL1();
            ElNotification({
                type: 'success',
                title: "成功",
                message: "删除成功",
            });
        })
        .catch((res: any) => {
            ElNotification({
                type: 'error',
                title: "失败",
                message: res.data.errmsg,
            });
        });
};
</script>
