<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"
                    size="mini"
                    @click="handleAdd"
                >
                    新增轮播图
                </el-button>
            </el-col>
        </el-row>

        <el-table :data="swiperList" border>
            <el-table-column
                label="序号"
                align="center"
                width="100"
                type="index"
            />
            <el-table-column
                prop="slidePicture"
                label="图片链接"
                align="center"
                show-overflow-tooltip
            />
            <el-table-column prop="isShow" label="是否禁用" align="center">
                <template slot-scope="{ row }">
                    <el-switch
                        active-text="激活"
                        inactive-text="禁用"
                        v-model="row.delFlag"
                        @change="onSwitchChange($event, row)"
                    />
                </template>
            </el-table-column>
            <el-table-column
                prop="slideLink"
                label="外部链接"
                align="center"
                show-overflow-tooltip
            />
            <el-table-column label="操作" align="center">
                <template slot-scope="{ row }">
                    <el-button
                        size="mini"
                        type="danger"
                        @click="onClickDelete(row)"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog
            width="50%"
            append-to-body
            title="新增轮播图"
            :visible.sync="addSwiperVisible"
        >
            <el-form
                ref="addSwiperFormRef"
                :model="addSwiperForm"
                :rules="addSwiperFormRules"
                label-width="120px"
            >
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="外部链接：" prop="slideLink">
                            <el-input
                                placeholder="请输入外部链接"
                                v-model="addSwiperForm.slideLink"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="是否激活：" prop="delFlag">
                            <el-switch
                                active-text="激活"
                                inactive-text="禁用"
                                v-model="addSwiperForm.delFlag"
                            ></el-switch>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="轮播图上传：" prop="fileList">
                            <el-upload
                                :limit="1"
                                :headers="headers"
                                :show-file-list="true"
                                :action="uploadFileUrl"
                                list-type="picture-card"
                                :on-exceed="handleExceed"
                                :on-remove="handleRemove"
                                :on-preview="handlePreview"
                                :on-success="handleSuccess"
                                :before-upload="handleBeforeUpload"
                                :file-list="addSwiperForm.fileList"
                            >
                                <i class="el-icon-plus"></i>
                            </el-upload>
                        </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
                width="30%"
                append-to-body
                :before-close="
                    () => {
                        dialogInnerVisible = false
                    }
                "
                :visible.sync="dialogInnerVisible"
            >
                <img
                    :src="previewUrl"
                    style="display: block; max-width: 100%; margin: 0 auto"
                />
            </el-dialog>
        </el-dialog>
    </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import {
    addHomeSwiperApi,
    getSwiperListApi,
    deleteHomeSwiperApi,
    editHomeSwiperTypeApi,
} from '@/api/swiper-manage/index.js'
export default {
    data() {
        return {
            uploadFileUrl: process.env.VUE_APP_BASE_API + '/file/upload',
            dialogInnerVisible: false,
            fileType: ['png', 'jpg', 'jpeg'],
            previewUrl: '',
            addSwiperVisible: false,
            value1: true,
            value2: true,
            addSwiperFormRules: {},
            addSwiperForm: {
                fileList: [],
                slidePicture: '',
                slideLink: '',
                delFlag: true,
            },
            headers: {
                Authorization: 'Bearer ' + getToken(),
            },
            swiperList: [],
        }
    },
    created() {
        this.getSwiperListData()
    },
    methods: {
        handleAdd() {
            this.addSwiperVisible = true
        },
        // 获取列表
        async getSwiperListData() {
            const res = await getSwiperListApi()
            this.swiperList = res.rows

            this.swiperList.forEach((e) => {
                e.delFlag == 0 ? (e.delFlag = true) : (e.delFlag = false)
            })
            // console.log(res, "列表数据--");
        },
        async submitForm() {
            // 组装参数
            const { slidePicture, slideLink, delFlag } = this.addSwiperForm
            const params = {
                slidePicture,
                slideLink,
                delFlag: delFlag ? 0 : 2,
            }
            const res = await addHomeSwiperApi(params)
            if (res.code === 200) {
                this.$modal.msgSuccess('新增成功')
                this.$refs.addSwiperFormRef.resetFields()
                this.addSwiperVisible = false
                this.getSwiperListData()
            }
            // console.log(res, "上传结果--");
            // this.addSwiperVisible = false;
        },
        cancel() {
            this.addSwiperVisible = false
        },
        // 上传之前
        handleBeforeUpload(file) {
            const isSvg = this.fileType.some((e) => file.type.includes(e))
            if (!isSvg) {
                this.$modal.msgError(
                    `文件格式不正确, 请上传${this.fileType.join(
                        '、',
                    )}格式的文件!`,
                )
                return false
            }
            const isLt = file.size / 1024 / 1024 < 10
            if (!isLt) {
                this.$modal.msgError(`图片大小不能超过 10 MB`)
                return false
            }
            this.$modal.loading('图片正在上传，请稍候...')
        },
        // 移除
        handleRemove(file) {
            this.addSwiperForm.fileList = this.addSwiperForm.fileList.filter(
                (item) => item.uid !== file.uid,
            )
            this.addSwiperForm.slidePicture = ''
        },
        // 预览 图片
        handlePreview(file) {
            this.dialogInnerVisible = true
            this.previewUrl = file.url
        },

        // 文件个数超出限制
        handleExceed() {
            this.$modal.msgError(`上传的图片数量不能超过 1 个`)
        },
        // 上传成功
        handleSuccess(res) {
            if (res.code === 200) {
                this.addSwiperForm.slidePicture = res.data.url
            } else {
                this.$modal.msgError('上传失败')
                this.addSwiperForm.fileList = []
                this.addSwiperForm.slidePicture = ''
            }
            this.$modal.closeLoading()
        },

        onClickDelete(row) {
            this.$confirm('确定删除该轮播图吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    const res = await deleteHomeSwiperApi(row.id)
                    if (res.code === 200) {
                        this.$modal.msgSuccess('删除成功')
                        this.getSwiperListData()
                    }
                })
                .catch(() => {})
        },
        async onSwitchChange(val, row) {
            const { id } = row
            const params = {
                id,
                delFlag: val ? 0 : 2,
            }
            const res = await editHomeSwiperTypeApi(params)
            if (res.code === 200) {
                this.$modal.msgSuccess('状态修改成功')
                this.getSwiperListData()
            }
        },
    },
}
</script>
