<template>
    <div class="content-view">
        <div class="table-head-tool">
            <Button type="primary" @click="showAddModal">新增资源</Button>
            <Form ref="formInline" :model="gridOption.param.seachOption" inline :label-width="80">
                <FormItem :label-width="20" class="flex">
                    <Select v-model="gridOption.param.seachOption.key" style="width: 120px"
                        :placeholder="seachTypePlaceholder">
                        <Option v-for="(item, index) in seachTypes" :key="index" :value="item.key">{{ item.title }}
                        </Option>
                    </Select>
                    <Input class="ml10" v-model="gridOption.param.seachOption.value" style="width: 200px" search
                        placeholder="请输入关键字" @on-search="query(1)" />
                </FormItem>
                <FormItem label="资源类型">
                    <Select v-model="gridOption.param.seachOption.resource_type" style="width: 120px" clearable @on-change="query(1)">
                        <Option value="image">图片</Option>
                        <Option value="video">视频</Option>
                        <Option value="audio">音频</Option>
                        <Option value="document">文档</Option>
                    </Select>
                </FormItem>
                <FormItem label="状态">
                    <Select v-model="gridOption.param.seachOption.status" style="width: 120px" clearable @on-change="query(1)">
                        <Option value="active">正常</Option>
                        <Option value="inactive">禁用</Option>
                        <Option value="deleted">已删除</Option>
                    </Select>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="query(1)">查询</Button>
                    <Button type="default" @click="resetQuery" class="ml10">重置</Button>
                    <Button type="default" @click="exportCsv">导出</Button>
                </FormItem>
            </Form>
        </div>
        <div class="table-body">
            <tables :columns="listColumns" :value="gridOption.data" :pageOption="gridOption.param.pageOption"
                @changePage="query"></tables>
        </div>
        <Modal v-model="editWarp" :title="editTitle" @on-ok="save" @on-cancel="cancel" width="600">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
                <FormItem v-for="(item, index) in editColumns" :key="index" :label="item.title" :prop="item.key">
                    <Input v-if="item.type === 'text'" v-model="formValidate[item.key]"
                        :placeholder="'请输入' + item.title" />
                    <Input v-else-if="item.type === 'textarea'" v-model="formValidate[item.key]" type="textarea"
                        :placeholder="'请输入' + item.title" :rows="4" />
                    <Input v-else-if="item.type === 'number'" v-model="formValidate[item.key]" type="number"
                        :placeholder="'请输入' + item.title" />
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>

<script>
import { getList, add, edit, del, exportData } from '@/api/ball/resources_server'
import uiTool from '@/libs/uiTool'
import funTool from '@/libs/funTool'

export default {
    name: 'resources',
    data() {
        // 定义表单验证规则
        const rules = {
            resource_name: [{ required: true, message: '请输入资源名称', trigger: 'blur' }],
            resource_type: [{ required: true, message: '请输入资源类型', trigger: 'blur' }],
            resource_url: [{ required: true, message: '请输入资源链接', trigger: 'blur' }]
        }

        return {
            editWarp: false,
            editTitle: '新增',
            formValidate: {},
            ruleValidate: rules,
            seachTypes: [
                { key: 'user_id', title: '用户ID' }
            ],
            gridOption: {
                data: [],
                param: {
                    seachOption: {
                        key: 'user_id',
                        value: '',
                        resource_type: null,
                        status: null
                    },
                    pageOption: {
                        page: 1,
                        pageSize: 20,
                        total: 0
                    }
                }
            },
            listColumns: [
                { title: 'ID', key: 'id' },
                {
                    title: '用户',
                    key: 'user_id',
                    render: (h, params) => {
                        const userInfo = params.row.user_info;
                        if (userInfo && userInfo.nickname) {
                            return h('div', [
                                h('img', {
                                    attrs: {
                                        src: userInfo.avatar_url || '/default-avatar.png',
                                        alt: userInfo.nickname,
                                        title: userInfo.nickname
                                    },
                                    style: {
                                        width: '24px',
                                        height: '24px',
                                        borderRadius: '50%',
                                        marginRight: '8px',
                                        verticalAlign: 'middle'
                                    }
                                }),
                                h('span', { style: { verticalAlign: 'middle' } }, userInfo.nickname)
                            ]);
                        }
                        return h('span', `用户ID: ${params.row.user_id}`);
                    }
                },
                {
                    title: '资源类型',
                    key: 'resource_type',
                    render: (h, params) => {
                        const typeMap = {
                            'image': { text: '图片', color: 'blue' },
                            'video': { text: '视频', color: 'purple' },
                            'audio': { text: '音频', color: 'orange' },
                            'document': { text: '文档', color: 'green' },
                            'other': { text: '其他', color: 'default' }
                        };
                        const type = typeMap[params.row.resource_type] || { text: params.row.resource_type || '未知', color: 'default' };
                        return h('Tag', { props: { color: type.color } }, type.text);
                    }
                },
                {
                    title: '文件预览',
                    key: 'file_url',
                    render: (h, params) => {
                        const fileUrl = params.row.file_url;
                        const resourceType = params.row.resource_type;

                        if (!fileUrl) {
                            return h('span', { style: { color: '#c5c8ce' } }, '无文件');
                        }

                        // 图片预览
                        if (resourceType === 'image') {
                            return h('img', {
                                attrs: {
                                    src: fileUrl,
                                    alt: params.row.original_name || '图片',
                                    title: '点击查看大图'
                                },
                                style: {
                                    width: '60px',
                                    height: '60px',
                                    objectFit: 'cover',
                                    borderRadius: '4px',
                                    cursor: 'pointer'
                                },
                                on: {
                                    click: () => {
                                        window.open(fileUrl, '_blank');
                                    }
                                }
                            });
                        }

                        // 其他文件类型显示链接
                        return h('a', {
                            attrs: {
                                href: fileUrl,
                                target: '_blank',
                                title: '点击下载/查看文件'
                            },
                            style: {
                                color: '#2d8cf0',
                                textDecoration: 'none'
                            }
                        }, '查看文件');
                    }
                },
                { title: '文件大小(字节)', key: 'file_size' },
                { title: 'MIME类型', key: 'mime_type' },
                {
                    title: '是否公开',
                    key: 'is_public',
                    render: (h, params) => {
                        return h('Tag', {
                            props: { color: params.row.is_public == 1 ? 'green' : 'default' }
                        }, params.row.is_public == 1 ? '是' : '否');
                    }
                },
                {
                    title: '状态',
                    key: 'status',
                    render: (h, params) => {
                        const statusMap = {
                            'active': { text: '正常', color: 'green' },
                            'deleted': { text: '已删除', color: 'red' },
                            'pending': { text: '待审核', color: 'orange' }
                        };
                        const status = statusMap[params.row.status] || { text: params.row.status || '未知', color: 'default' };
                        return h('Tag', { props: { color: status.color } }, status.text);
                    }
                },
                { title: '创建时间', key: 'create_time' },
                {
                    title: '操作',
                    key: 'action',
                    fixed: 'right',
                    render: (h, params) => {
                        let btns = [
                            {
                                title: '编辑',
                                type: 'primary',
                                click: () => {
                                    this.showEditWarp(params.row)
                                }
                            },
                            {
                                title: '删除',
                                type: 'error',
                                click: () => {
                                    this.del(params.row)
                                }
                            }
                        ];
                        return uiTool.getBtn(h, btns);
                    }
                }
            ],
            editColumns: [
                { title: '资源名称', key: 'resource_name', type: 'text', required: true },
                { title: '资源类型', key: 'resource_type', type: 'text', required: true },
                { title: '资源链接', key: 'resource_url', type: 'text', required: true },
                { title: '资源描述', key: 'resource_description', type: 'textarea', required: false }
            ]
        }
    },
    mounted() {
        this.query(1)
    },
    methods: {
        query(page) {
            this.gridOption.param.pageOption.page = page
            getList(this.gridOption.param).then(res => {
                if (res && res.data) {
                    this.gridOption.data = res.data.rows || res.data
                    this.gridOption.param.pageOption.total = res.data.count || 0
                }
            })
        },
        showAddModal() {
            this.editTitle = '新增'
            this.formValidate = {}
            this.editWarp = true
        },
        showEditWarp(row) {
            this.editTitle = '编辑'
            this.formValidate = { ...row }
            this.editWarp = true
        },
        save() {
            this.$refs.formValidate.validate((valid) => {
                if (valid) {
                    if (this.formValidate.id) {
                        edit(this.formValidate).then(res => {
                            this.$Message.success('编辑成功')
                            this.editWarp = false
                            this.query(1)
                        })
                    } else {
                        add(this.formValidate).then(res => {
                            this.$Message.success('新增成功')
                            this.editWarp = false
                            this.query(1)
                        })
                    }
                }
            })
        },
        cancel() {
            this.editWarp = false
        },
        del(row) {
            this.$Modal.confirm({
                title: '确认删除',
                content: '确定要删除这条记录吗？',
                onOk: () => {
                    del({ id: row.id }).then(res => {
                        this.$Message.success('删除成功')
                        this.query(1)
                    })
                }
            })
        },
        exportCsv() {
            exportData(this.gridOption.param).then(res => {
                funTool.downloadFile(res, '资源管理.csv')
            })
        },
        resetQuery() {
            this.gridOption.param.seachOption = {
                key: 'user_id',
                value: '',
                resource_type: null,
                status: null
            };
            this.query(1);
        }
    },
    computed: {
        seachTypePlaceholder() {
            const selected = this.seachTypes.find(item => item.key === this.gridOption.param.seachOption.key);
            return selected ? selected.title : '请选择搜索类型';
        }
    }
}
</script>

<style scoped>
.content-view {
    padding: 20px;
}

.table-head-tool {
    padding: 10px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.table-body {
    margin-top: 10px;
}

.ml10 {
    margin-left: 10px;
}
</style>
