<template>
    <div class="app-container">
        <!-- 查询 -->
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item prop="goodsName">
                <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item prop="brandId">
                <el-select v-model="queryParams.brandId" placeholder="请选择商品分类" clearable>
                    <el-option v-for="brand in brandList" :key="brand.id" :label="brand.brandName" :value="brand.id" />
                </el-select>
            </el-form-item>
            <el-form-item prop="goodsCategoryId">
                <el-select v-model="queryParams.goodsCategoryId" placeholder="请选择商品分类" clearable>
                    <el-option v-for="category in categoryList" :key="category.id" :label="category.categoryName" :value="category.id" />
                </el-select>
            </el-form-item>
            <el-form-item prop="goodsCode">
                <el-input v-model="queryParams.goodsCode" placeholder="请输入商品编号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" v-hasPermi="['goods: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/goods/list" :request-params="queryParams" ref="pagination">
            <el-table-column label="ID" align="center" prop="id" />
            <el-table-column label="商品编号" align="center" prop="goodsCode" />
            <el-table-column label="商品名称" align="center" prop="goodsName" />
            <el-table-column label="图片" align="center" prop="goodsImg" width="100">
                <template slot-scope="scope">
                    <el-image style="width: 80px; height: 80px" :src="scope.row.goodsImg" :preview-src-list="[scope.row.goodsImg]"> </el-image>
                </template>
            </el-table-column>
            <el-table-column label="品牌" align="center" prop="brandName" />
            <el-table-column label="商品分类" align="center" prop="goodsCategoryId">
                <template slot-scope="scope">
                    <span v-if="scope.row.goodsCategoryId == item.id" v-for="item in categoryList" :key="item.id"> {{ item.categoryName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="促销标识" align="center" prop="isSell">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.isSell == dict.value" v-for="dict in dict.type.sys_yes_no" :label="dict.value" :key="dict.code"> {{ dict.label }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="规格数量" align="center" prop="goodsItemNum">
                <template slot-scope="scope">
                    <el-button type="text" @click="handleSkuUpdate(scope.row)">{{ scope.row.goodsItemNum }}种规格</el-button>
                </template>
            </el-table-column>
            <el-table-column label="余额支付" align="center" prop="isBalancePay">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.isBalancePay == dict.value" v-for="dict in dict.type.sys_yes_no" :label="dict.value" :key="dict.code"> {{ dict.label }}</el-tag>
                </template>
            </el-table-column>
            <!--            <el-table-column label="金额（元）" align="center" prop="cashMoney" />-->
            <el-table-column label="排序值" align="center" prop="sort" />
            <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']" v-if="userInfoVO.userType == '00'">修改</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>
                    <el-button type="text" icon="el-icon-s-shop" @click="handleSkuUpdate(scope.row)" v-hasPermi="['goods:commonGoods:list']">查看规格</el-button>
                    <el-button type="text" icon="el-icon-view" v-if="goodsType != 1" @click="gotoComment(scope.row)">查看评论</el-button>
                </template>
            </el-table-column>
        </Page>
        <!-- 分页 -->
        <!-- 添加或修改商品管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
            <el-row :gutter="15">
                <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                    <el-col :span="24">
                        <el-form-item label="商品名称" prop="goodsName">
                            <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
                        </el-form-item>
                        <el-form-item label="品牌" prop="brandId">
                            <el-select v-model="form.brandId" placeholder="请选择商品分类" clearable>
                                <el-option v-for="brand in brandList" :key="brand.id" :label="brand.brandName" :value="brand.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goodsCategoryId">
                            <el-select v-model="form.goodsCategoryId" placeholder="请选择商品分类" clearable>
                                <el-option v-for="category in categoryList" :key="category.id" :label="category.categoryName" :value="category.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="商品编码" prop="goodsCode">
                            <el-input v-model="form.goodsCode" placeholder="请输入商品编码" />
                        </el-form-item>
                        <template v-if="goodsType === '0'">
                            <el-form-item label="促销标识" prop="isSell">
                                <el-radio-group v-model="form.isSell" size="small">
                                    <el-radio-button v-for="dict in dict.type.sys_yes_no" :label="dict.value" :key="dict.code">{{ dict.label }}</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                        </template>
                        <el-form-item label="是否余额支付" prop="isBalancePay">
                            <el-radio-group v-model="form.isBalancePay" size="small">
                                <el-radio-button v-for="dict in dict.type.sys_yes_no" :label="dict.value" :key="dict.code">{{ dict.label }}</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <!--                        <el-form-item label="是否现金支付" prop="isCashPay">-->
                        <!--                            <el-radio-group v-model="form.isCashPay" size="small">-->
                        <!--                                <el-radio-button v-for="dict in dict.type.sys_yes_no" :label="dict.value" :key="dict.code">{{ dict.label }}</el-radio-button>-->
                        <!--                            </el-radio-group>-->
                        <!--                        </el-form-item>-->
                        <!--                        <template v-if="form.isCashPay === 'Y'">-->
                        <!--                            <el-form-item label="现金金额" prop="cashMoney">-->
                        <!--                                <el-input v-model="form.cashMoney" placeholder="请输入金额" />-->
                        <!--                            </el-form-item>-->
                        <!--                        </template>-->
                        <el-form-item label="上传图片" prop="goodsImg">
                            <image-upload v-model="form.goodsImg" />
                        </el-form-item>
                        <el-form-item label="上传图片集" prop="goodsImgs">
                            <image-upload v-model="form.goodsImgs" :limit="limit" />
                        </el-form-item>
                        <el-form-item label="显示顺序" prop="sort">
                            <el-input-number v-model="form.sort" placeholder="请输入显示顺序(升序排列显示)" :min="0" :step-strictly="true" :style="{ width: '100%' }"> </el-input-number>
                        </el-form-item>
                        <el-form-item label="商品简介" prop="goodsSynopsis">
                            <editor v-model="form.goodsSynopsis" :min-height="192" />
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>

            <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 { listGoods, getGoods, delGoods, addGoods, updateGoods, updateGoodsStatus } from '@/api/core/goods'
import { listCategory } from '@/api/core/category'
import { listBrand } from '@/api/core/brand'

export default {
    name: 'appGoods',
    dicts: ['goods_type', 'sys_yes_no'],
    data() {
        return {
            userInfoVO: null,
            uploadAction: `${process.env.VUE_APP_BASE_API}` + '/common/uploadOSS',
            imgsList: [],
            fileSize: 3,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 商品管理表格数据
            goodsList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                goodsName: null,
                goodsType: null,
                status: null,
                goodsCategoryId: null,
                goodsCode: null
            },
            queryParams2: {
                pageNum: 1,
                pageSize: 9999,
                status: '0',
                goodsType: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                goodsName: [
                    {
                        required: true,
                        message: '商品名称不能为空',
                        trigger: 'blur'
                    }
                ],
                brandId: [
                    {
                        required: true,
                        message: '品牌不能为空',
                        trigger: 'blur'
                    }
                ],
                goodsCategoryId: [
                    {
                        required: true,
                        message: '商品分类不能为空',
                        trigger: 'blur'
                    }
                ],
                goodsCode: [
                    {
                        required: true,
                        message: '商品编号不能为空',
                        trigger: 'blur'
                    }
                ],
                goodsSynopsis: [
                    {
                        required: true,
                        message: '商品简介不能为空',
                        trigger: 'blur'
                    }
                ],
                goodsImg: [
                    {
                        required: true,
                        message: '商品头图不能为空',
                        trigger: 'blur'
                    }
                ],
                goodsImgs: [
                    {
                        required: true,
                        message: '商品图片集不能为空',
                        trigger: 'blur'
                    }
                ],
                isBalancePay: [
                    {
                        required: true,
                        message: '是否余额支付不能为空',
                        trigger: 'blur'
                    }
                ],
                isCashPay: [
                    {
                        required: true,
                        message: '是否现金支付不能为空',
                        trigger: 'blur'
                    }
                ],
                isSell: [
                    {
                        required: true,
                        message: '是否促销不能为空',
                        trigger: 'blur'
                    }
                ],
                cashMoney: [
                    {
                        required: true,
                        message: '现金金额不能为空',
                        trigger: 'blur'
                    }
                ]
            },
            categoryList: {},
            brandList: {},
            goodsType: '',
            limit: 9
        }
    },
    created() {
        this.handleUser()
        this.goodsType = this.getUrlParam('goodsType')
        this.form.goodsType = this.goodsType
        this.getList()
        this.getCategoryList()
        this.getBrandList()
    },
    methods: {
        handleUser() {
            this.userInfoVO = this.getUserInfo()
        },
        getBrandList() {
            listBrand({ ...this.queryParams2, ...{ goodsType: this.goodsType } }).then((response1) => {
                this.brandList = response1.rows
            })
        },
        getCategoryList() {
            listCategory({ ...this.queryParams2, ...{ goodsType: this.goodsType } }).then((response2) => {
                this.categoryList = response2.rows
            })
        },
        /** 查询商品管理列表 */
        getList() {
            this.queryParams.goodsType = this.goodsType
            this.$nextTick(() => {
                this.$refs.pagination.handleSearch(true)
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                goodsName: null,
                goodsCategoryId: null,
                goodsSynopsis: null,
                brandId: null,
                goodsImg: null,
                goodsImgs: [],
                goodsCode: null,
                isSell: 'N',
                isCashPay: 'Y',
                cashMoney: null,
                isBalancePay: 'Y',
                createBy: null,
                createById: null,
                createTime: null,
                updateBy: null,
                updateById: null,
                updateTime: null,
                remark: null
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            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()
            this.imgsList = []
            const id = row.id || this.ids
            getGoods(id).then((response) => {
                this.form = response.data
                if (this.form.goodsImgs != null && this.form.goodsImgs != '') {
                    this.form.goodsImgs.split(',').forEach((item) => {
                        const vo = {
                            name: '',
                            url: item
                        }
                        this.imgsList.push(vo)
                    })
                }
                this.open = true
                this.title = '修改商品管理'
            })
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.isCashPay != 'Y') {
                        this.form.cashMoney = '0'
                    }
                    this.form.goodsType = this.goodsType
                    if (this.form.id != null) {
                        updateGoods(this.form).then((response) => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        this.form.status = '0'
                        this.form.delFlag = '0'
                        addGoods(this.form).then((response) => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal
                .confirm('是否确认删除商品管理编号为"' + ids + '"的数据项？')
                .then(function () {
                    return delGoods(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'
                })
        },
        /** 设置物料 */
        handleSkuUpdate(row) {
            this.$tab.openPage(row.goodsName + '的物料', '/goods/setSku/' + row.id)
        },
        handleRemove(file, fileList) {
            console.log(fileList)
            this.imgsList = []
            fileList.forEach((item) => {
                const vo = {
                    name: item.name,
                    url: item.url
                }
                this.imgsList.push(vo)
                console.log(fileList)
            })
        },
        // 上传前校检格式和大小
        handleBeforeUpload(file) {
            // 校检文件大小
            if (this.fileSize) {
                const isLt = file.size / 1024 / 1024 < this.fileSize
                if (!isLt) {
                    this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`)
                    return false
                }
            }
            return true
        },
        handleUploadSuccessByImg(res, file) {
            // 获取富文本组件实例
            let quill = this.Quill
            // 如果上传成功
            if (res.code == 200) {
                // 获取光标所在位置
                this.form.goodsImg = res.data.src
                this.$forceUpdate()
            } else {
                this.$message.error('图片插入失败')
            }
        },
        handleUploadSuccessByImgs(res, file, fileList) {
            // 获取富文本组件实例
            let quill = this.Quill
            // 如果上传成功
            if (res.code == 200) {
                const vo = {
                    name: '',
                    url: res.data.src
                }
                this.imgsList.push(vo)
                this.$forceUpdate()
            } else {
                this.$message.error('图片插入失败')
            }
        },
        handleUploadError() {
            this.$message.error('图片插入失败')
        },
        handleExceed() {
            //提示最多只能上传9个
            this.$message.error('最多上传9个图片！')
        },
        gotoComment(row) {
            this.$router.push({ path: `/platform/goodsComment/appGoodsComment?goodsType=${this.goodsType}&goodsId=${row.id}` })
        }
    }
}
</script>
