<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />

			<!-- 删除按钮 -->
			<cl-multi-delete-btn />

			<cl-filter label="分类">
				<cl-select tree :options="options.type" prop="typeId" all-levels-id :width="140" />
			</cl-filter>

			<cl-flex1 />
			<!-- 关键字搜索 -->
			<cl-search-key placeholder="搜索标题" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table" :autoHeight="false" />
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination :page-sizes="[5, 7, 10, 20]" />
		</cl-row>
	</cl-crud>
</template>

<script lang="ts" name="assembly-goods" setup>
import { useCrud, useTable } from "@cool-vue/crud";
import { useCool } from "/@/cool";
import { computed, reactive } from "vue";
import { deepTree } from "/@/cool/utils";
import type { Dict } from "/$/dict/types";

const { service } = useCool();

const props = defineProps({
	multiple: Boolean
});

const emit = defineEmits(["change"]);

const options = reactive({
	type: [] as Dict.Item[],
	status: [
		{
			label: "已上架",
			value: 1
		},
		{
			label: "已下架",
			value: 0
		}
	]
});

// cl-table
const Table = useTable({
	columns: [
		{ type: "selection" },
		{ label: "分类", prop: "typeId", minWidth: 160, dict: computed(() => options.type) },
		{ label: "标题", prop: "title", minWidth: 240 },
		{
			label: "主图",
			prop: "mainPic",
			minWidth: 100,
			component: { name: "cl-image", props: { size: 50 } }
		},
		{
			label: "示例图",
			prop: "pics",
			minWidth: 100,
			component: { name: "cl-image", props: { size: 50 } }
		},
		{ label: "价格", prop: "price", minWidth: 100, sortable: "custom" },
		{ label: "已售", prop: "sold", minWidth: 100, sortable: "custom" },
		{ label: "状态", prop: "status", minWidth: 100, component: { name: "cl-switch" } },
		{ label: "排序", prop: "sortNum", minWidth: 100, sortable: "desc" },
		{ label: "创建时间", prop: "createTime", minWidth: 160, sortable: "custom" },
		{
			type: "op",
			width: 160,
			buttons: [
				{
					label: "选择TA",
					type: "success",
					onClick({ scope }) {
						select(scope.row);
					}
				}
			]
		}
	]
});

// cl-crud
const Crud = useCrud(
	{
		service: service.goods.info,
		async onRefresh(params, { next, done, render }) {
			const { list, pagination } = await next(params);
			list.forEach((e) => {
				e.content = "";
			});
			render(list, pagination);
			done();
		},
		dict: {
			label: {
				multiDelete: "多选/确定"
			}
		},
		onDelete(selection, { next }) {
			choice(selection);
		}
	},
	(app) => {
		app.refresh({ size: 5, page: 1 ,status: 1});
		getTypes();
	}
);
// 多选
function choice(items: any[]) {
	if (props.multiple) {
		emit("change", items);
	}
}
// 单选
function select(item: any) {
	emit("change", item);
}
// 获取分类
function getTypes() {
	service.goods.type.list().then((res) => {
		res.forEach((e) => {
			e.label = e.name;
			e.value = e.id;
		});

		options.type = deepTree(res);
	});
}
</script>
