<template>
    <div class="app-container">
        <!-- 查询 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" v-hasPermi="['commonGoods:commonGoods:add']" v-if="userInfoVO.userType == '00'">新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <!-- 列表 -->
        <Page uri="/mapi/core/sku/list" :request-params="queryParams" ref="pagination">
            <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">
                    <span v-for="spec in scope.row.specVoList" :key="spec.id">
                        <p>{{ spec.specName }}:{{ spec.specValue }}</p>
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="零售价（元）" align="center" prop="salePrice" />
            <el-table-column label="成本价（元）" align="center" prop="costPrice"  v-if="userInfoVO.userType == '00'" />
            <el-table-column label="采购价（元）" align="center" prop="purchasePrice" v-if="userInfoVO.userType != '02'"/>
            <el-table-column label="库存" align="center" prop="stock" />
            <el-table-column label="启用状态" align="center" prop="status">
                <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-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <!-- <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['goods:commonGoods:edit']">修改</el-button> -->
                    <!--                  <el-button type="text" icon="el-icon-edit" @click="stockRecord(scope.row)" v-hasPermi="['goods:commonGoods:edit']">库存记录</el-button>-->
                    <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['goods:commonGoods:remove']" v-if="userInfoVO.userType == '00'">删除</el-button>
                </template>
            </el-table-column>
        </Page>
        <!-- 分页 -->
        <!-- 添加或修改商品管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body size="50%">
            <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="规格名称" required>
                                        <el-input v-model="item.specName" placeholder="请输入名称" :disabled="userInfoVO.userType != '00' ? true : false" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-form-item label="规格内容" required>
                                        <el-input v-model="item.specValue" placeholder="请输入内容" :disabled="userInfoVO.userType != '00' ? true : false" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="4" v-if="index == '0' && specVoList.length == 1 && userInfoVO.userType == '00'">
                                    <el-button @click="addSpecList" style="width: 100px" type="primary">新增规格</el-button>
                                </el-col>
                                <el-col :span="4" v-if="index != '0' && userInfoVO.userType == '00'">
                                    <el-button @click="deleteSpecList(index)" type="danger">删除</el-button>
                                </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' ? true : false" 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' ? true : false" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div class="remark">* 物料规格最多两条 使用同一价格体系 *</div>
                </div>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" style="margin-left: 5%">提交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

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

export default {
    name: 'setGoodsSku',
    dicts: ['goods_type', 'sys_yes_no'],
    data() {
        return {
            userInfoVO: null,
            specVO: null,
            goodsId: '',
            // 遮罩层
            loading: true,
            stockLoading: true,

            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 商品管理表格数据
            skuList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {},
            // 表单参数
            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.handleUser()
        this.goodsId = this.$route.params.goodsId
        this.queryParams.goodsId = this.goodsId
        this.getList()
    },
    methods: {
        handleUser() {
            this.userInfoVO = this.getUserInfo()
        },
        addSpecList() {
            if (this.specVoList.length < 2) {
                this.specVoList.push({
                    specName: '',
                    specValue: ''
                })
            } else {
                this.$modal.msgSuccess('最多添加2种规格')
            }
        },
        deleteSpecList(index) {
            this.specVoList.splice(index, 1)
        },
        /** 查询商品管理列表 */
        getList() {
            this.$nextTick(() => {
                this.$refs.pagination.handleSearch(true)
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                sort: null,
                status: null,
                salePrice: null,
                costPrice: null,
                purchasePrice: null,
                specVoList: [
                    {
                        specName: null,
                        specValue: null
                    }
                ],
                createBy: null,
                createById: null,
                createTime: null,
                updateBy: null,
                updateById: null,
                updateTime: null,
                remark: null
            }
            this.specVoList = [
                {
                    specName: '',
                    specValue: ''
                }
            ]
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加物料明细'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getSku(id).then((response) => {
                this.form = response.data
                this.specVoList = this.form.specVoList
                this.open = true
                this.title = '修改物料明细'
            })
        },
        stockRecord(row) {
            this.$tab.openPage('库存记录', '/goods/stockRecord/' + row.id)
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate((valid) => {
                for (let i = 0; i < this.specVoList.length; i++) {
                    if (this.specVoList[i].specName == '') {
                        this.$message.error('规格名称不能为空')
                        return
                    }
                }
                if (valid) {
                    this.form.goodsId = this.goodsId
                    this.handleSpecVOList()
                    if (this.form.id != null) {
                        // 处理工厂/门店传参
                        updateSku(this.handleUpdateParams(this.form)).then((response) => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addSku(this.form).then((response) => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        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
            }
        },
        handleSpecVOList() {
            this.form.specVoList = this.specVoList
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal
                .confirm('是否确认删除商品管理编号为"' + ids + '"的数据项？')
                .then(function () {
                    return delSku(ids)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'commonGoods/commonGoods/export',
                {
                    ...this.queryParams
                },
                `goods_${new Date().getTime()}.xlsx`
            )
        },
        checkClose(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        handleStatusChange(row) {
            let text = row.status === '0' ? '启用' : '停用'
            this.$confirm('确认要' + text + '吗？')
                .then(function () {
                    return updateGoodsStatus(row.id, row.status)
                })
                .then(() => {
                    this.$modal.msgSuccess(text + '成功')
                })
                .catch(function () {
                    row.status = row.status === '0' ? '1' : '0'
                })
        }
    }
}
</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>
