<template>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="1000px" append-to-body>
        <div class="app-container">
            <el-row :gutter="10" class="mb8">
                <!-- 移除新增按钮 -->
            </el-row>

            <!-- 列表 -->
            <el-table v-loading="loading" :data="skuList">
                <!-- <el-table-column type="selection" width="55" align="center" /> -->
                <!-- <el-table-column label="规格编号" align="center" prop="id" /> -->
                <el-table-column label="规格详情" align="center" width="200" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <template v-if="!scope.row.specValLists || scope.row.specValLists.length === 0">
                            默认
                        </template>
                        <template v-else>
                            {{ scope.row.specValLists.join('，') }}
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="零售价（元）" align="center" width="180">
                    <template slot-scope="scope">
                        <el-input-number
                            v-model="scope.row.salePrice"
                            :precision="2"
                            :step="0.1"
                            :min="0"
                            controls-position="right"
                            :disabled="userInfoVO.userType != '00'"
                            size="mini"
                            @change="handlePriceStockChange(scope.row)" />
                    </template>
                </el-table-column>
                <el-table-column label="成本价（元）" align="center" width="180" v-if="userInfoVO.userType != '02'">
                    <template slot-scope="scope">
                        <el-input-number
                            v-model="scope.row.costPrice"
                            :precision="2"
                            :step="0.1"
                            :min="0"
                            controls-position="right"
                            size="mini"
                            @change="handlePriceStockChange(scope.row)" />
                    </template>
                </el-table-column>
                <el-table-column :label="userInfoVO.userType == '00' ? '批发价（元)' : '采购价（元)'" align="center" width="180">
                    <template slot-scope="scope">
                        <el-input-number
                            v-model="scope.row.purchasePrice"
                            :precision="2"
                            :step="0.1"
                            :min="0"
                            controls-position="right"
                            size="mini"
                            :disabled="userInfoVO.userType != '00'"
                            @change="handlePriceStockChange(scope.row)" />
                    </template>
                </el-table-column>
                <el-table-column label="库存" align="center" width="180">
                    <template slot-scope="scope">
                        <el-input-number
                            v-model="scope.row.stock"
                            :min="0"
                            :step="1"
                            controls-position="right"
                            size="mini"
                            :disabled="userInfoVO.userType != '00'"
                            @change="handlePriceStockChange(scope.row)" />
                    </template>
                </el-table-column>
                <el-table-column label="启用状态" align="center" width="120">
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.status"
                            active-value="0"
                            inactive-value="1"
                            @change="handleStatusChange(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
        </div>

        <!-- SKU编辑弹窗 -->
        <el-dialog
            :title="editTitle"
            :visible.sync="editDialogVisible"
            width="50%"
            append-to-body
        >
            <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-if="Object.keys(form).length > 0">
                <div class="specvo_content">
                    <div class="list_specvo">
                        <div class="title">物料规格</div>
                        <div v-for="(item, index) in specVoList" :key="index">
                            <el-row :gutter="15">
                                <el-col :span="10">
                                    <el-form-item label="规格名称">
                                        <el-input v-model="item.specName" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-form-item label="规格内容">
                                        <el-input v-model="item.specValue" disabled />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="零售价（元）" prop="salePrice">
                                <el-input-number v-model="form.salePrice" placeholder="请输入零售价" :precision="2" :step="0.1" :min="0" :max="9999999" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="成本价（元）" prop="costPrice" v-if="userInfoVO.userType != '02'">
                                <el-input-number v-model="form.costPrice" placeholder="请输入成本价" :precision="2" :step="0.1" :min="0" :max="9999999" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="批发价（元）" prop="purchasePrice">
                                <el-input-number v-model="form.purchasePrice" placeholder="请输入批发价" :precision="2" :step="0.1" :min="0" :max="9999999" :disabled="userInfoVO.userType != '00'" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="库存" prop="stock">
                                <el-input-number v-model="form.stock" placeholder="请输入库存" :precision="0" :step="1" :min="0" :max="9999999" :disabled="userInfoVO.userType != '00'" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancelEdit">取 消</el-button>
            </div>
        </el-dialog>
    </el-dialog>
</template>

<script>
import { listSku, getSku, delSku, addSku, updateSku, updateGoodsStatus } from '@/api/core/sku'

export default {
    name: 'GoodsSkuDialog',
    props: {
        title: {
            type: String,
            default: '规格管理'
        }
    },
    data() {
        return {
            dialogVisible: false,
            editDialogVisible: false,
            editTitle: '',
            loading: false,
            userInfoVO: null,
            goodsId: null,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                goodsId: null
            },
            // 总条数
            total: 0,
            // SKU列表数据
            skuList: [],
            // 表单参数
            form: {
                salePrice: 0,
                costPrice: 0,
                purchasePrice: 0
            },
            // 表单校验
            rules: {
                salePrice: [{ required: true, message: '零售价不能为空', trigger: 'blur' }],
                costPrice: [{ required: true, message: '成本价不能为空', trigger: 'blur' }],
                purchasePrice: [{ required: true, message: '批发价不能为空', trigger: 'blur' }]
            },
            specVoList: [
                {
                    specName: '',
                    specValue: ''
                }
            ]
        }
    },
    created() {
        this.userInfoVO = this.getUserInfo()
    },
    methods: {
        // 显示弹窗
        show(goodsId) {
            this.goodsId = goodsId
            this.queryParams.goodsId = goodsId
            this.dialogVisible = true
            this.getList()
        },
        // 获取SKU列表
        async getList() {
            this.loading = true
            try {
                const response = await listSku(this.queryParams)
                this.skuList = response.rows
                this.total = response.total
            } catch (error) {
                console.error('获取SKU列表失败:', error)
            } finally {
                this.loading = false
            }
        },
        // 新增SKU
        handleAdd() {
            this.reset()
            this.editDialogVisible = true
            this.editTitle = '添加规格'
        },
        // 修改SKU
        handleUpdate(row) {
            this.reset()
            getSku(row.id).then(response => {
                this.form = response.data
                this.specVoList = this.form.specVoList
                this.editDialogVisible = true
                this.editTitle = '修改价格和库存'
            })
        },
        // 删除SKU
        handleDelete(row) {
            this.$modal.confirm('是否确认删除该规格？').then(() => {
                return delSku(row.id)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            })
        },
        // 处理价格或库存变更
        handlePriceStockChange(row) {
            updateSku(this.handleUpdateParams(row)).then(() => {
                this.$modal.msgSuccess('更新成功')
            }).catch(() => {
                this.getList() // 更新失败时刷新数据
            })
        },
        // 状态变更
        handleStatusChange(row) {
            let text = row.status === '0' ? '启用' : '停用'
            this.$confirm('确认要' + text + '吗？')
                .then(function () {
                    // 这里应该调用 updateSku 而不是 updateGoodsStatus
                    return updateSku({
                        id: row.id,
                        status: row.status
                    })
                })
                .then(() => {
                    this.$modal.msgSuccess(text + '成功')
                    // 可以选择是否刷新列表
                    // this.getList()
                })
                .catch(() => {
                    // 如果失败，恢复状态
                    row.status = row.status === '0' ? '1' : '0'
                })
        },
        // 提交表单
        submitForm() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    updateSku(this.handleUpdateParams(this.form)).then(() => {
                        this.$modal.msgSuccess('修改成功')
                        this.editDialogVisible = false
                        this.getList()
                    })
                }
            })
        },
        // 重置表单
        reset() {
            this.form = {
                id: null,
                sort: null,
                status: null,
                salePrice: null,
                costPrice: null,
                purchasePrice: null,
                stock: null,
                specVoList: []
            }
            this.specVoList = []
            if (this.$refs.form) {
                this.$refs.form.resetFields()
            }
        },
        // 取消编辑
        cancelEdit() {
            this.editDialogVisible = false
            this.reset()
        },
        // 添加规格
        addSpecList() {
            if (this.specVoList.length < 2) {
                this.specVoList.push({
                    specName: '',
                    specValue: ''
                })
            } else {
                this.$modal.msgSuccess('最多添加2种规格')
            }
        },
        // 删除规格
        deleteSpecList(index) {
            this.specVoList.splice(index, 1)
        },
        // 处理更新参数
        handleUpdateParams(data) {
            if (this.userInfoVO.userType == '00') {
                return data
            }
            if (this.userInfoVO.userType == '01') {
                data.purchasePrice = null
                return data
            }
            if (this.userInfoVO.userType == '02') {
                data.costPrice = null
                data.purchasePrice = null
                return data
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.specvo_content {
    padding: 5px 20px 20px;
    .list_specvo {
        padding: 0px 0px 10px;
        margin-bottom: 40px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
        border-radius: 5px;
        .title {
            color: #606266;
            padding: 10px 20px;
            border-bottom: 1px #f4f4f4 solid;
            font-size: 14px;
            margin-bottom: 20px;
        }
    }
    .remark {
        margin-top: 30px;
        background-color: rgba(255, 228, 74, 0.1);
        border: 1px dashed #ffe44a;
        font-size: 14px;
        color: #e6a23c;
        width: 100%;
        padding: 20px;
        border-radius: 5px;
    }
}
</style>
