<template>
    <div class="app-container calendar-list-container">

        <!-- 查询和其他操作 -->
        <div class="filter-container">
            <el-input clearable class="filter-item" style="width: 200px;" placeholder="商品名称"
                v-model="listQuery.name"></el-input>
            <el-input clearable class="filter-item" style="width: 200px;" placeholder="商品编号"
                v-model="listQuery.seq"></el-input>
            <el-date-picker class="filter-item" v-model="listQuery.shelfTime" type="datetime" placeholder="商品上架时间">
            </el-date-picker>
            <el-select v-model="listQuery.status" clearable placeholder="状态" style="top: -4px;width: 200px;">
                <el-option :key="item.type" v-for="item in goodsStatusList" :label="item.name" :value="item.type">
                </el-option>
            </el-select>
            <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
            <el-button class="filter-item" type="primary" @click="handleCreate" icon="el-icon-edit">添加</el-button>

        </div>

        <!-- 查询结果 -->
        <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit
            highlight-current-row>
            <el-table-column type="index" label="序号" header-align="center" align="center">
            </el-table-column>

            <el-table-column align="center" min-width="100px" label="商品名称" prop="name">
            </el-table-column>

            <el-table-column align="center" min-width="100px" label="商品编号" prop="seq">
            </el-table-column>

            <el-table-column align="center" min-width="80px" label="商品属性">
                <template slot-scope="props">
                    <span v-if="props.row.productAttribute == 1">实物</span>
                    <span v-if="props.row.productAttribute == 0">虚拟</span>
                </template>
            </el-table-column>
            <el-table-column align="center" min-width="80px" label="积分" prop="integral">
            </el-table-column>
            <el-table-column align="center" min-width="100px" label="库存量" prop="actualStock">
            </el-table-column>

            <el-table-column align="center" min-width="80px" label="兑换方式">
                <template slot-scope="props">
                    <span v-if="props.row.deliveryType == 1">快递</span>
                    <span v-if="props.row.deliveryType == 0">无需快递</span>
                </template>
            </el-table-column>
            <el-table-column align="center" min-width="100px" label="商品所在地" prop="location">
            </el-table-column>
            <el-table-column align="center" min-width="150px" label="上架时间" prop="shelfTime">
            </el-table-column>
            <el-table-column align="center" min-width="80px" label="商品状态">
                <template slot-scope="props">
                    <span v-if="props.row.status == 1">上架</span>
                    <span v-if="props.row.status == 0">下架</span>
                </template>
            </el-table-column>
            <el-table-column align="center" min-width="80px" label="兑换记录">
                <template slot-scope="props">
                    <span @click="handleView(props.row)" style="color:green;cursor: pointer;">查看</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="240px" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button v-if="scope.row.status == 0" type="success" size="small"
                        @click="changeGoodsState(scope.row.skuId, 1)">上架</el-button>
                    <el-button v-if="scope.row.status == 1" type="warning" size="small"
                        @click="changeGoodsState(scope.row.skuId, 0)">下架</el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row.skuId, -1)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="listQuery.page" :page-sizes="[10, 20, 30, 50]" :page-size="listQuery.limit"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <!-- 员工积分记录列表 -->
        <el-dialog title="兑换记录" :visible.sync="dialogListVisible" width="70%">
            <div class="filter-container">
                <el-select v-model="itemListQuery.deptId" clearable placeholder="部门" style="top: -4px;width: 200px;">
                    <el-option :key="item.type" v-for="item in depTypeList" :label="item.name" :value="item.type">
                    </el-option>
                </el-select>
                <el-input clearable class="filter-item" style="width: 200px;" placeholder="员工名称"
                    v-model="itemListQuery.purchaserName"></el-input>
                <el-button class="filter-item" type="primary" v-waves icon="el-icon-search"
                    @click="itemHandleFilter">查找</el-button>
                <el-button class="filter-item" type="primary" v-waves icon="el-icon-download">导出</el-button>

            </div>
            <!-- 查询结果 -->
            <el-table size="small" :data="itemList" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit
                highlight-current-row>
                <el-table-column type="index" label="序号" header-align="center" align="center">
                </el-table-column>
                <el-table-column align="center" min-width="100px" label="部门" prop="deptName">
                </el-table-column>
                <el-table-column align="center" min-width="100px" label="员工姓名" prop="purchaserName">
                </el-table-column>
                <el-table-column align="center" min-width="100px" label="兑换方式" prop="deliveryName">
                </el-table-column>
                <el-table-column align="center" min-width="80px" label="联系人" prop="contact">
                </el-table-column>
                <el-table-column align="center" min-width="80px" label="联系方式" prop="contactPhone">
                </el-table-column>
                <el-table-column align="center" min-width="80px" label="地址/邮箱" prop="contactAddr">
                </el-table-column>
                <el-table-column align="center" min-width="80px" label="兑换时间" prop="createTime">
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination background @size-change="itemHandleSizeChange" @current-change="itemHandleCurrentChange"
                    :current-page="itemListQuery.page" :page-sizes="[10, 20, 30, 50]" :page-size="itemListQuery.limit"
                    layout="total, sizes, prev, pager, next, jumper" :total="itemTotal">
                </el-pagination>
            </div>
        </el-dialog>
        <!-- 添加或修改对话框 -->
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="70%">
            <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width:700px;margin-left:50px;'>
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="dataForm.name"></el-input>
                </el-form-item>

                <el-form-item label="商品编号" prop="seq">
                    <el-input placeholder="添加成功后自动生成" readonly v-model="dataForm.seq"></el-input>
                </el-form-item>

                <el-form-item label="商品属性" prop="productAttribute">
                    <el-select v-model="dataForm.productAttribute" filterable placeholder="请选择" style="width: 350px"
                        value-key="value" @change="changeProductAttribute">
                        <el-option :key="item.type" v-for="item in productAttributeList" :label="item.name"
                            :value="item.type">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="兑换方式" prop="deliveryType">
                    <el-select v-model="dataForm.deliveryType" filterable placeholder="请选择" style="width: 350px">
                        <el-option :key="item.type" v-for="item in deliveryTypeList" :label="item.name" :value="item.type">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item v-if="dataForm.deliveryType==1" label="商品所在地" prop="location">
                    <el-select v-model="dataForm.location" filterable placeholder="请选择" style="width: 350px">
                        <el-option :key="item.index" v-for="item in locationList" :label="item" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="width: 800px" label="商品图片">
                    <el-tooltip content="建议图片宽高比260*200" placement="top-start">
                        <el-upload :action="fileImgUrl" list-type="picture-card" :file-list="dataForm.images"
                            :on-success="handleGallerySucess" :on-exceed="handleExceed" :before-upload="uploadBannerImg"
                            :on-remove="handleRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-tooltip>
                </el-form-item>

                <el-form-item label="积分" prop="integral">
                    <el-input v-model="dataForm.integral"></el-input>
                </el-form-item>
                <el-form-item label="库存量" prop="actualStock">
                    <el-input-number :precision="0" :step="1" v-model="dataForm.actualStock"></el-input-number>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
                <el-button v-else type="primary" @click="updateData">确定</el-button>
            </div>
        </el-dialog>

    </div>
</template>
  
<style>
.demo-table-expand {
    font-size: 0;
}

.demo-table-expand label {
    width: 200px;
    color: #99a9bf;
}

.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
}
</style>
  
<script>
import { createItem, updateItem, goodsList, goodsState, exchangeHistory } from "@/api/goodsManage";
import { companyTypeList, depTypeList } from "@/api/public";
import waves from "@/directive/waves"; // 水波纹指令
import Tinymce from '@/components/Tinymce'

export default {
    name: 'pointList',
    components: { Tinymce },
    directives: { waves },
    data() {
        return {
            locationList:['洛阳','北京','上海'],
            productAttributeList: [
                {
                    type: 1,
                    name: '实物'
                },
                {
                    type: 0,
                    name: '虚拟'
                },
            ],
            deliveryTypeList: [
                {
                    type: 1,
                    name: '快递'
                },
                {
                    type: 0,
                    name: '无需快递'
                },
            ],
            goodsStatusList: [
                {
                    type: 1,
                    name: '上架'
                },
                {
                    type: 0,
                    name: '下架'
                },
            ],
            depTypeList: [
                {
                    type: 'highTechnology',
                    name: '高科技'
                },
                {
                    type: 'fastExtinction',
                    name: '快销'
                },
                {
                    type: 'manufacturingIndustry',
                    name: '制造业'
                },
                {
                    type: 'all',
                    name: '全部'
                },
            ],
            list: [
                {
                    id: 1,
                    name: '类型1',
                    seq: 'sp123456',
                    productAttribute: 0,
                    integral: '100',
                    actualStock: '12',
                    deliveryType: 0,
                    location: '北京',
                    shelfTime: '2023-3-24 12:12:12',
                    imgUrl: 'https://xiaoyou.dgtis.com/images/image/2023/04/04/knitu6huek0c0f4jbshq.jpg',
                    status: 1,
                },
                {
                    id: 2,
                    name: '类型1',
                    seq: 'sp123456',
                    productAttribute: 1,
                    integral: '100',
                    actualStock: '12',
                    deliveryType: 1,
                    location: '上海',
                    shelfTime: '2023-3-24 12:12:12',
                    imgUrl: 'https://xiaoyou.dgtis.com/images/image/2023/04/04/knitu6huek0c0f4jbshq.jpg',
                    status: 0,
                },
                {
                    id: 3,
                    name: '类型1',
                    seq: 'sp123456',
                    productAttribute: 1,
                    integral: '100',
                    actualStock: '12',
                    deliveryType: 1,
                    location: '洛阳',
                    shelfTime: '2023-3-24 12:12:12',
                    imgUrl: 'https://xiaoyou.dgtis.com/images/image/2023/04/04/knitu6huek0c0f4jbshq.jpg',
                    status: 0,
                },
            ],
            itemList: [
                {
                    id: 1,
                    deptName: '软件工程院',
                    purchaserName: '张三',
                    deliveryName: '邮寄',
                    contact: '李四',
                    contactPhone: '13613885046',
                    contactAddr: '正大西区CPL',
                    createTime: '2023-4-3',
                },
                {
                    id: 2,
                    deptName: '软件工程院',
                    purchaserName: '张三',
                    deliveryName: '邮寄',
                    contact: '李四',
                    contactPhone: '13613885046',
                    contactAddr: '正大西区CPL',
                    createTime: '2023-4-3',
                },
                {
                    id: 3,
                    deptName: '软件工程院',
                    purchaserName: '张三',
                    deliveryName: '邮寄',
                    contact: '李四',
                    contactPhone: '13613885046',
                    contactAddr: '正大西区CPL',
                    createTime: '2023-4-3',
                },
            ],
            total: 0,
            itemTotal: 0,
            listLoading: false,
            downloadLoading: false,
            listQuery: {
                page: 1,
                limit: 10,
                name: '',
                seq: '',
                shelfTime: '',
                status: '',
            },
            itemListQuery: {
                page: 1,
                limit: 10,
                deptId: '',
                purchaserName: '',
            },
            dataForm: {
                name: undefined,
                seq: undefined,
                productAttribute: undefined,
                imgUrl: undefined,
                integral: undefined,
                actualStock: undefined,
                deliveryType: undefined,
                location: undefined,
                images: [],
            },
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: "编辑",
                create: "创建",
            },
            rules: {
                name: [{ required: true, message: "请填写商品名称", trigger: "blur" }],
                imgUrl: [{ required: true, message: "请上传商品图片", trigger: "blur" }],
                productAttribute: [{ required: true, message: "请选择商品属性", trigger: "blur" }],
                integral: [{ required: true, message: "请填写商品积分", trigger: "blur" }],
                actualStock: [{ required: true, message: "请设置库存量", trigger: "blur" }],
                deliveryType: [{ required: true, message: "请选择兑换方式", trigger: "blur" }],
                location: [{ required: true, message: "请选择商品所在地", trigger: "blur" }],
            },
            dialogListVisible: false,
            fileImgUrl: "https://xiaoyou.dgtis.com/admin/storage/create",
        }
    },
    created() {
        // this.getCompanyTypeList();
        // this.getDepTypeList(); 
        // this.getList();
    },
    methods: {
        changeProductAttribute(val) {
            this.dataForm.deliveryType = '';
            this.dataForm.location = '';
            if (val == 1) {
                this.deliveryTypeList = [
                    {
                        type: 1,
                        name: '快递'
                    },
                    {
                        type: 0,
                        name: '无需快递'
                    },
                ]
            } else {
                this.deliveryTypeList = [
                    {
                        type: 0,
                        name: '无需快递'
                    },
                ]
            }
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
            let images = [];
            for (let i in fileList) {
                let response = fileList[i].response;
                let url = response.data.url;
                images.push(url);
                this.dataForm.image = images.join(",");
            }
        },
        uploadBannerImg(file) {
            const isJPGs = file.type === "image/jpeg";
            console.log(isJPGs);
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件！，共选择了 ${files.length + fileList.length
                } 个文件`
            );
        },
        handleGallerySucess(res, file, fileList) {
            this.dataForm.image = ""; // 清空画廊图片数组

            let images = [];
            for (let i in fileList) {
                let response = fileList[i].response;
                if (response.errno && response.errno != "0") {
                    this.$message.error("该图片上传失败,已被移除,请重新上传!");
                    // 上传失败移除该 file 对象
                    fileList.splice(i, 1);
                } else {
                    let url = response.data.url;
                    images.push(url);
                }
            }

            this.dataForm.image = images.join(",");
        },
        resetForm() {
            this.dataForm = {
                name: undefined,
                seq: undefined,
                productAttribute: undefined,
                imgUrl: undefined,
                integral: undefined,
                actualStock: undefined,
                deliveryType: undefined,
                location: undefined,
                images: [],
            };
        },
        handleCreate() {
            this.resetForm();

            this.dialogFormVisible = true;
            this.dialogStatus = "create";

            this.$nextTick(() => {
                this.$refs["dataForm"].clearValidate();
            });
        },
        createData() {
            
            this.$refs["dataForm"].validate((valid) => {
                if (valid) {
                    console.log(this.dataForm);
                    // if (!this.dataForm.imgUrl) {
                    //     this.$alert("请上传商品图片", "提示", {
                    //         confirmButtonText: "确定",
                    //     });
                    // } else {
                    //     createItem(this.dataForm)
                    //         .then((response) => {
                    //             this.getList();
                    //             this.dialogFormVisible = false;
                    //             this.$notify({
                    //                 title: "成功",
                    //                 message: "创建成功",
                    //                 type: "success",
                    //                 duration: 2000,
                    //             });
                    //             this.reload();
                    //         })
                    //         .catch(() => { });
                    // }
                }
            });
        },
        handleUpdate(row) {
            this.dataForm = Object.assign({}, row);
            if (row.productAttribute == 1) {
                this.deliveryTypeList = [
                    {
                        type: 1,
                        name: '快递'
                    },
                    {
                        type: 0,
                        name: '无需快递'
                    },
                ]
            } else {
                this.deliveryTypeList = [
                    {
                        type: 0,
                        name: '无需快递'
                    },
                ]
            }
            if (this.dataForm.imgUrl) {
                let images = this.dataForm.imgUrl.split(",");
                this.dataForm.images = [];
                for (let i in images) {
                    let url = images[i];
                    let name = "image_" + i;

                    this.dataForm.images.push({
                        name: name,
                        url: url,
                        response: { error: "0", data: { url: url } },
                    });
                }
            }
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        updateData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    if (!this.dataForm.imgUrl) {
                        this.$alert("请上传商品图片", "提示", {
                            confirmButtonText: "确定",
                        });
                    } else {
                        updateItem(this.dataForm).then(() => {
                            this.dialogFormVisible = false
                            this.$notify({
                                title: '成功',
                                message: '更新成功',
                                type: 'success',
                                duration: 2000
                            })
                            this.getList()
                        })
                    }

                }

            })
        },
        changeGoodsState(id, index) {
            goodsState({ skuId: id, status: index }).then(response => {
                this.$notify({
                    title: '成功',
                    message: '商品状态修改成功',
                    type: 'success',
                    duration: 2000
                })
                this.getList()
            })
        },
        handleDelete(id, index) {
            this.$confirm('确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                goodsState({ skuId: id, status: index }).then(response => {
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                    const index = this.list.indexOf(row)
                    this.list.splice(index, 1)
                })
            }).catch(() => {

            })

        },
        getDepTypeList() {
            depTypeList().then(response => {
                this.depTypeList = response.data.data;
            }).catch(() => {
                this.depTypeList = []
            });
        },
        getList() {
            this.listLoading = true
            goodsList(this.listQuery).then(response => {
                this.list = response.data.data.items
                this.total = response.data.data.total
                this.listLoading = false
            }).catch(() => {
                this.list = []
                this.total = 0
                this.listLoading = false
            })
        },
        getItemList() {
            this.listLoading = true
            exchangeHistory(this.itemListQuery).then(response => {
                this.itemList = response.data.data.items
                this.itemLotal = response.data.data.total
                this.listLoading = false
            }).catch(() => {
                this.itemList = []
                this.itemLotal = 0
                this.listLoading = false
            })
        },

        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        handleSizeChange(val) {
            this.listQuery.limit = val
            this.getList()
        },
        handleCurrentChange(val) {
            this.listQuery.page = val
            this.getList()
        },

        itemHandleFilter() {
            this.itemListQuery.page = 1
            this.getItemList()
        },
        itemHandleSizeChange(val) {
            this.itemListQuery.limit = val
            this.getItemList()
        },
        itemHandleCurrentChange(val) {
            this.itemListQuery.page = val
            this.getItemList()
        },

        handleView(row) {
            this.itemListQuery.id = row.id;
            // getPointRulesType()
            // this.getItemList()
            this.dialogListVisible = true
        },
    }
}
</script>
<style>
.ad-avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.ad-avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.ad-avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.ad-avatar {
    display: block;
}
</style>
  