<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="名称">
                <el-input v-model="queryParams.imgName" placeholder="请输入名称" maxlength="20" clearable style="width: 220px"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @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"
                size="mini"
                @click="handleAdd"
            >新增</el-button>
            </el-col>  
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tableListData" border size="mini"> 
            <el-table-column label="序号" align="center" width="80" type="index">
                <template scope="scope"> 
                    <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                </template> 
            </el-table-column> 
            <el-table-column label="名称" align="center" prop="imgName" :show-overflow-tooltip="true"/>
            <el-table-column label="外链" align="center" prop="externalUrl" :show-overflow-tooltip="true"/> 
            <el-table-column label="图片" align="center" prop="imgUrl">
                <template slot-scope="scope">
                    <img :src="scope.row.imgUrl" v-if="scope.row.imgUrl" alt="" style="width: 80px;height: 40px;" @click="openImg(scope.row)">
                    <span v-else>无</span>
                </template>
            </el-table-column>
            <el-table-column label="图片地址" align="center" prop="imgUrl" :show-overflow-tooltip="true"/>
            <el-table-column label="用途类型" align="center" prop="usageType" :show-overflow-tooltip="true">
                <template scope="scope">
                    <span v-if="scope.row.usageType==1">后台</span>
                    <span v-if="scope.row.usageType==2">APP</span>
                    <span v-if="scope.row.usageType==3">双屏消费机</span> 
                </template>
            </el-table-column>
            <el-table-column label="是否启用" align="center" prop="ifEnabled" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.ifEnabled"
                        active-value="1"
                        inactive-value="2"
                        @change="handleStatusChange(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true"/>
            <el-table-column label="更新时间" align="center" prop="updateTime" :show-overflow-tooltip="true"/>
            <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
            <template slot-scope="scope"> 
                <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)" 
                >编辑</el-button>
                <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)" 
                >删除</el-button>
            </template>
            </el-table-column>
        </el-table>

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

        <!-- 添加或修改参数配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="名称" prop="imgName">
                            <el-input  v-model="form.imgName" placeholder="请输入名称" maxlength="30" clearable/>
                        </el-form-item> 
                    </el-col> 
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="外链地址" prop="externalUrl">
                            <el-input  v-model="form.externalUrl" placeholder="请输入外链地址" maxlength="100" clearable/>
                        </el-form-item> 
                    </el-col> 
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="用途类型" prop="usageType">
                             <el-select v-model="form.usageType" style="width: 100%"> 
                                <el-option label="后台" value="1"></el-option>
                                <el-option label="APP" value="2"></el-option> 
                            </el-select>   
                        </el-form-item> 
                    </el-col> 
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="图片地址">
                            <el-input  v-model="form.imgUrl" placeholder="图片地址" disabled clearable/>
                        </el-form-item> 
                    </el-col> 
                </el-row> 
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="图片" prop="imgUrl">
                            <el-upload
                                :http-request="
                                    (obj) => imgUpLoad(obj, 'fileUrl')
                                "
                                action="#"
                                :limit="1"
                                :file-list="fileList"
                                :show-file-list="true"
                                list-type="picture-card"
                                accept=".png, .jpg, .jpeg"
                                :on-change="handleFileChange"
                                :on-success="handleAvatarSuccess"
                                :class="{ disabled: uploadDisabled }"
                                :on-preview="handlePictureCardPreview"
                                :on-remove="handleRemove"
                            >
                                <i
                                    class="el-icon-plus avatar-uploader-icon"
                                ></i>
                            </el-upload>
                            <span>* 提示：图片宽高比例为750px*520px</span>
                        </el-form-item> 
                    </el-col> 
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>


        <el-dialog :visible.sync="dialogVisible" width="700px">
            <img style="width: 100%;height: 100%;" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script> 
import { getCarouselListApi,addCarouselApi,updateCarouselApi,removeCarouselApi } from "@/api/base/mobile.js";
import { imgUpLoadTwo } from '@/api/system/upload'
export default {
    name: "",
    dicts: [],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            //表格数据
            tableListData: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false, 
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                imgName: undefined, 
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                imgName: [
                    { required: true, message: "名称不能为空", trigger: "blur" }
                ],
                imgUrl: [
                    { required: true, message: "图片不能为空", trigger: "change" }
                ]
            },
            fileList: [],//图片
            checkUrlList: [],//图片
            checkUrlNameList: [],//食堂图片
            dialogVisible:false,//图片弹窗
            dialogImageUrl:"",//图片弹窗  
        };
    },
    created() { 
        this.getList();
    },
    computed: {
        //图片上传1张后，隐藏上传框
        uploadDisabled() {
            return this.checkUrlList.length > 1
        },
    },
    methods: { 
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() { 
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                imgName: undefined, 
            }
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 查询列表 */
        getList() {
            this.loading = true;
            let param = {
                "pageNum": this.queryParams.pageNum, 
                "pageSize": this.queryParams.pageSize,  
                "imgName": this.queryParams.imgName
            }
            getCarouselListApi(param).then(response => {
                this.tableListData = response.rows;
                this.total = Number(response.total);
                this.loading = false;
            });
        },  
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "新增";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.form = Object.assign({}, row)
            if(this.form.imgUrl){
                this.fileList=[{url:this.form.imgUrl}]
                this.checkUrlList=[this.form.imgUrl]
            }else{
                this.fileList=[]
                this.checkUrlList=[]
            }
            this.open = true;
            this.title = "修改"; 
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.checkUrlList=[]
            this.checkUrlNameList=[]
            this.fileList=[]
            this.form = {};
            this.$set(this.form,"usageType","2")
            this.resetForm("form");
        }, 
        /** 提交按钮 */
        submitForm: function() {
            this.$refs["form"].validate(valid => {
            if (valid) {
                this.form.imgUrl = this.checkUrlList[0]
                if (this.form.id != undefined) {
                    updateCarouselApi(this.form).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.open = false;
                        this.getList();
                    });
                } else {
                    addCarouselApi(this.form).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.open = false;
                        this.getList();
                    });
                }
            }
            });
        },
        handleStatusChange(row){
            console.log(row)
            let param = {
                id:row.id,
                imgName:row.imgName,
                externalUrl:row.externalUrl,
                imgUrl:row.imgUrl, 
                ifEnabled:row.ifEnabled
            }
            updateCarouselApi(param).then(response => {
                this.$modal.msgSuccess("修改成功"); 
                this.getList();
            }); 
        },
        /** 删除按钮操作 */
        handleDelete(row) { 
            this.$modal.confirm('是否确认删除数据项？').then(function() {
                return removeCarouselApi({id:row.id});
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
        },
        // 图片上传
        imgUpLoad(param, name, index) {
            // console.log(param,'image')
            param.type = 'canteen'
            imgUpLoadTwo(param).then((res) => {
                if (res.code == 200) {
                    this.checkUrlList.push(res.data.url)
                    this.checkUrlNameList.push(res.data.name)
                    this.form.imgUrl = this.checkUrlList[0]
                } else { 
                    this.$modal.msgError(res.msg)
                }
            })
            .catch((error) => { 
                this.$modal.msgError(error)
            })
        },
        checkImageSize(file, fileType) { 
            const reader = new FileReader();
            reader.onload = (e) => {
                const img = new Image();
                img.onload = () => {
                    const { width, height } = img;
                    // 设置你希望限制的图片尺寸
                    const MAX_WIDTH = 750;
                    const MAX_HEIGHT = 520;
                    console.log(width)
                    console.log(height)
                    if (width <= MAX_WIDTH && height <= MAX_HEIGHT) {
                        this.form[fileType] = file.raw
                        this.$refs['form'].validateField(fileType)
                        this.$message.success(`图片尺寸符合要求: ${width}x${height}`);
                    } else {
                        this.$message.error(`图片尺寸不能超过 ${MAX_WIDTH}x${MAX_HEIGHT}`);
                        this.checkUrlNameList=[]
                        this.checkUrlList=[]
                        this.fileList=[]
                        // 清空当前上传的文件
                        this.form[fileType] = '' 
                        this.$refs['form'].validateField(fileType)
                       
                    }
                };
                img.src = e.target.result;
            };
            reader.readAsDataURL(file.raw);
        },
        handleFileChange(file){
            this.checkImageSize(file,'imgUrl');
        },
        handleAvatarSuccess(res, file) {
            console.log('success')
        },
        handleExceed(files, fileList) {
            this.$message.warning('最多只可以上传一张图片')
        },
        handleRemove(file, fileList) {
            let sum = 0
            this.checkUrlNameList.forEach((item, index) => {
                if (item == file.name) {
                    sum = index
                }
            })
            this.checkUrlNameList.splice(sum, 1)
            this.checkUrlList.splice(sum, 1)
        },
        //图片点击查看
        handlePictureCardPreview(file) {
            console.log(file)
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        }
    }
};
</script>
  <style lang="scss" scoped>
  //隐藏图片上传框的css
  ::v-deep.disabled {
      .el-upload--picture-card {
          display: none;
      }
  }
</style>