<template>
    <div class="app-container p-5">
        <div class="h-full w-full" v-show="showInfo">
            <el-form :model="queryParams" ref="queryForm" class="main-search" :inline="true" v-show="showSearch">
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable style="width: 240px"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="所属店铺" prop="store">
                    <el-select v-model="queryParams.storeId" placeholder="所属店铺" clearable style="width: 180px">
                        <el-option :key="0" label="公共商品" v-if="!storeId" :value="0" />
                        <el-option v-for="storeInfo in storeOptions" :key="storeInfo.id" :label="storeInfo.name"
                            :value="storeInfo.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="商品分类" prop="cateId" style="width: 240px">
                    <el-select class="input" v-model="queryParams.cateId" clearable placeholder="请选择商品分类">
                        <el-option v-for="item in cateList" :key="item.id" :label="item.name" :value="item.id"
                            :disabled="item.status !== 'A'"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品类型" prop="type" style="width: 240px">
                    <el-select class="input" v-model="queryParams.type" clearable placeholder="请选择商品类型">
                        <el-option v-for="item in typeOptions" :key="item.key" :label="item.name"
                            :value="item.key"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="规格类型" prop="isSingleSpec" style="width: 200px">
                    <el-select v-model="queryParams.isSingleSpec" placeholder="规格类型" clearable>
                        <el-option key="Y" label="单一规格" value="Y" />
                        <el-option key="N" label="多种规格" value="N" />
                    </el-select>
                </el-form-item>
                <el-form-item label="上架状态" prop="status">
                    <el-select v-model="queryParams.status" placeholder="上架状态" style="width: 150px" clearable>
                        <el-option key="A" label="上架" value="A" />
                        <el-option key="N" label="下架" value="N" />
                    </el-select>
                </el-form-item>
                <el-form-item label="库存状态" prop="stock" style="width: 200px">
                    <el-select v-model="queryParams.stock" placeholder="库存状态" clearable>
                        <el-option key="Y" label="有库存" value="Y" />
                        <el-option key="N" label="无库存" value="N" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="mini" @click="handleQuery">
                        搜索
                    </el-button>
                    <el-button size="mini" @click="resetQuery">
                        重置
                    </el-button>
                    <el-button type="primary" plain size="mini" @click="handleAdd">
                        新增
                    </el-button>
                </el-form-item>
            </el-form>

            <el-table ref="tables" v-loading="loading" :data="list" @selection-change="handleSelectionChange"
                :default-sort="defaultSort" @sort-change="handleSortChange" class="p-3">
                <el-table-column label="ID" prop="id" width="80">
                    <template #default="scope">
                        <span>{{ showIdLastFour(scope.row.id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="店铺名称" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.storeInfo">{{ scope.row.storeInfo.name }}</span>
                        <span v-else>公共所有</span>
                    </template>
                </el-table-column>
                <el-table-column label="商品名称" align="center" min-width="200" prop="name" />
                <el-table-column label="主图" align="center" width="100">
                    <template #default="scope">
                        <img class="list-img" :src="scope.row.logo" alt="" />
                    </template>
                </el-table-column>
                <el-table-column label="剩余库存" align="center" prop="stock" width="100" />
                <el-table-column label="商品分类" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.cateInfo.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="价格" align="center" width="80">
                    <template #default="scope">
                        <span v-if="scope.row.price">{{ scope.row.price.toFixed(2) }}</span>
                        <span v-else>0.00</span>
                    </template>
                </el-table-column>
                <el-table-column label="上架状态" align="center" prop="status">
                    <template #default="scope">
                        <el-switch v-model="scope.row.status" active-value="A" inactive-value="N"
                            @change="handleStatusChange(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" width="150" prop="createTime">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" align="center" width="150" prop="updateTime">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.updateTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="180" fixed="right">
                    <template #default="scope">
                        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                            v-if="storeId == scope.row.storeId || storeId == 0">
                            编辑
                        </el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                            v-if="storeId == scope.row.storeId || storeId == 0">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination v-show="total > 0" :total="total" :page.sync="queryParams.page"
                :limit.sync="queryParams.pageSize" @pagination="getList" class="p-3" />
        </div>
        <div class="h-full w-full " v-show="!showInfo">
            <formUi :detailId="detailId"></formUi>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import formUi from './formUi.vue'
// 从 Vuex 中获取 storeId，这里假设 Vuex 配置正确
const storeId = ref(0)

// 遮罩层
const loading = ref(true)

// 选中数组
const ids = ref([])

// 非多个禁用
const multiple = ref(true)

// 显示搜索条件
const showSearch = ref(true)

// 总条数
const total = ref(0)

// 表格数据
const list = ref([])

// 店铺列表
const storeOptions = ref([])

// 商品类型
const typeOptions = ref([])

// 商品分类
const cateList = ref([])

// 是否显示弹出层
const open = ref(false)

// 默认排序
const defaultSort = ref({ prop: 'sort', order: 'descending' })

// 表单参数
const form = ref({ id: '', name: '', logo: '', sort: 0, status: 'A' })

// 上传地址
const uploadAction = ref('backendApi/file/upload')

// 隐藏上传
const hideUpload = ref(false)

// 上传文件列表
const uploadFiles = ref([])

// 查询参数
const queryParams = reactive({
    page: 1,
    pageSize: 10,
    storeId: '',
    cateId: '',
    name: '',
    isSingleSpec: '',
    goodsNo: '',
    stock: '',
    status: ''
})

// 表单校验
const rules = ref({
    name: [
        { required: true, message: '名称不能为空', trigger: 'blur' },
        { min: 2, max: 200, message: '名称长度必须介于2 和 200 之间', trigger: 'blur' }
    ],
    logo: [{ required: true, message: '请上传图片', trigger: 'blur' }]
})

// 假数据模拟
const fakeGoodsList = [
    {
        id: 1,
        storeInfo: { name: '店铺1' },
        name: '商品1',
        logo: 'https://example.com/logo1.png',
        stock: 'Y',
        cateInfo: { name: '分类1' },
        price: 10.99,
        status: 'A',
        createTime: '2023-01-01 00:00:00',
        updateTime: '2023-01-01 00:00:00'
    },
    {
        id: 2,
        storeInfo: null,
        name: '商品2',
        logo: 'https://example.com/logo2.png',
        stock: 'N',
        cateInfo: { name: '分类2' },
        price: 0,
        status: 'N',
        createTime: '2023-01-02 00:00:00',
        updateTime: '2023-01-02 00:00:00'
    }
]

const fakeStoreOptions = [
    { id: 1, name: '店铺1' },
    { id: 2, name: '店铺2' }
]

const fakeTypeOptions = [
    { key: 'type1', name: '类型1' },
    { key: 'type2', name: '类型2' }
]

const fakeCateList = [
    { id: 1, name: '分类1', status: 'A' },
    { id: 2, name: '分类2', status: 'A' }
]

onMounted(() => {
    getList()
})

// 查询商品列表
const getList = () => {
    loading.value = true
    // 使用假数据
    list.value = fakeGoodsList
    total.value = fakeGoodsList.length
    storeOptions.value = fakeStoreOptions
    typeOptions.value = fakeTypeOptions
    cateList.value = fakeCateList
    loading.value = false
}

// 搜索按钮操作
const handleQuery = () => {
    queryParams.page = 1
    getList()
}

// 重置按钮操作
const resetQuery = () => {
    // 这里简单重置表单数据，未实现完整的表单重置
    queryParams.name = ''
    queryParams.status = ''
    queryParams.page = 1
    getList()
}

// 状态修改
const handleStatusChange = (row) => {
    let text = row.status === 'A' ? '上架' : '下架'
    ElMessageBox.confirm(`确认要${text}“${row.name}”吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            // 模拟状态修改成功
            ElMessage.success(`${text}成功`)
        })
        .catch(() => {
            row.status = row.status === 'N' ? 'A' : 'N'
        })
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
    ids.value = selection.map((item) => item.id)
    multiple.value = !selection.length
}

// 排序触发事件
const handleSortChange = (column, prop, order) => {
    queryParams.orderByColumn = column.prop
    queryParams.isAsc = column.order
    getList()
}

const showInfo = ref(true)
const detailId = ref(0)
// 新增按钮操作
const handleAdd = () => {
    // 这里简单模拟跳转，实际需根据路由配置调整
    console.log('跳转到新增页面')
    showInfo.value = false
    detailId.value = 0
}

// 修改按钮操作
const handleUpdate = (row) => {
    // 这里简单模拟跳转，实际需根据路由配置调整
    console.log(`跳转到编辑页面，商品ID: ${row.id}`)
    showInfo.value = false
    detailId.value = row.id
}

// 删除按钮操作
const handleDelete = (row) => {
    const name = row.name
    ElMessageBox.confirm(`确认要删除“${name}”吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            // 模拟删除成功
            getList()
            ElMessage.success('删除成功')
        })
        .catch(() => { })
}

const handleUploadSuccess = (file) => {
    form.value.logo = file.data.fileName
}

const handleRemove = (file, fileList) => {
    setTimeout(() => {
        hideUpload.value = fileList.length > 0
    }, 520)
}

const showIdLastFour = (id) => {
    return String(id).slice(-4)
}

const parseTime = (time) => {
    return time
}
</script>

<style scoped>
/* 这里可以添加你的样式 */
</style>