<template>
    <div>
        <h2>创建轮播图</h2>

        <el-form ref="mapForm" :model="mapForm" :rules="rules" label-width="120px">
            <el-form-item label="轮播图名称" style="width: 60%;" prop="title">
                <el-input
                        v-model.trim="mapForm.title">
                </el-input>
            </el-form-item>
            <Category :data="isMapData"  categorys="add"></Category>
            <el-collapse v-model="activeName" accordion>
                <el-collapse-item v-for="(item, index) in mapForm.content" :name="item.collapseName" :key="item.collapseTitle">
                    <template slot="title">
                        {{item.collapseTitle}}
                        <span style="display:inline-block; margin-left:30px;">
                            <el-button class="btn-primary" size="small" v-if="index !== 0"
                                       @click.stop="zIndexUp(mapForm.content, index, mapForm.content.length)">上移</el-button>
                            <el-button class="btn-primary" size="small" 
                                        v-if="index !== mapForm.content.length-1"
                                        @click.stop="zIndexDown(mapForm.content, index, mapForm.content.length)">下移</el-button>
                            <el-button type="danger" size="small" 
                                        v-if="index !== 0" 
                                        @click.stop="delectPic(index)">删除</el-button>
                        </span>
                    </template>
                    <el-form-item label="上传图片" prop="url" >
                        <el-upload
                                class="upload-demo"
                                drag
                                action="https://api-ces-test.oasgames.com/api/item/upload"
                                :on-success="(res)=>{ return handleSuccess(res, index)}"
                                :beforeUpload="beforeAvatarUpload"
                                :before-remove="(res)=>{ return beforeRemove(res, index, 1)}"
                                :limit="1"
                                :on-exceed="resetUpload"
                                :file-list="item.fileList"
                                list-type="picture"
                                multiple>
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">只能上传小于2MB的JPG、PNG、GIF格式的图片</div>
                        </el-upload>
                        <div class="el-form-item__error" ref="uploadErr" style="display: none;" :data-key=index>
                            请上传图片
                        </div>
                    </el-form-item>
                    <el-form-item label="上传缩略图"  >
                        <el-upload
                                class="upload-demo"
                                drag
                                action="https://api-ces-test.oasgames.com/api/item/upload"
                                :on-success="(res)=>{ return handleThumbnail(res, index)}"
                                :beforeUpload="beforeAvatarUpload"
                                :before-remove="(res)=>{ return beforeRemove(res, index, 2)}"
                                :limit="1"
                                :on-exceed="resetUpload"
                                :file-list="item.thumbnailFileList"
                                list-type="picture"
                                multiple>
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">只能上传小于2MB的JPG、PNG、GIF格式的图片</div>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="图片名称" style="width: 60%;">
                        <el-input
                                v-model="item.name">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="图片链接" style="width: 60%;">
                        <el-input
                                v-model="item.redirect_url">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-col>
                            <el-radio v-model="item.is_show" label="1">显示</el-radio>
                            <el-radio v-model="item.is_show" label="0">隐藏</el-radio>
                        </el-col>
                    </el-form-item>
                </el-collapse-item>
            </el-collapse>
            <el-button type="primary" icon="el-icon-plus" style="margin:20px 0" @click="addMapImg">添加图片</el-button>
            <el-form-item label-width="0">
                <el-button type="primary" plain @click="openDialog">预览</el-button>
                <el-button type="primary" @click="onSubmit('mapForm')">提交</el-button>
                <el-button @click="$router.go(-1)">取消</el-button>
            </el-form-item>
        </el-form>

        <previewDialog :previewData="mapForm"> </previewDialog>   
    </div>

</template>

<script>
import { mapGetters, mapMutations } from 'vuex';
import axios from '../../../common/axios';
import {categoryFn} from '../../../common/common';
import previewDialog from './Preview.vue'; 
var arr = [];
export default {
    name: "add",
    data() {
        let validateNumber = (rule, value, callback) => {
            callback();
        };
        return {
            activeName: '1',
            dialogVisible: false,
            mapForm: {
                type: 4,       // *
                parent_id: this.$route.query.id,   // *
                parent_title: '',
                category: 0,    // *
                title: '',      // *
                link: '',
                content: [{
                    id: 1,
                    url: "",
                    name: "",
                    redirect_url: "",
                    thumbnail_url: '',
                    is_show: '1',
                    sort: 1,
                    status: 0,
                    collapseTitle: '图片1',
                    collapseName: '1',
                    fileList: [],
                    thumbnailFileList: []
                }],
                release: "0",
                collapseTitle: '图片1',
                dialogFormVisible: false
            },
            rules: {
                title: [
                    {required: true, message: '请输入标题', trigger: 'blur'},
                ],
                url: [
                    {required: true, validator: validateNumber, trigger: 'change'}
                ]
            },
        };
    },
    methods: {
        resetUpload(file) {
            if (file.length) {
                this.$message({
                    message: '请您先删除已上传图片',
                    type: 'warning'
                });
            }
        },
        openDialog() {
            this.mapForm.dialogFormVisible = true;

        },
        beforeAvatarUpload(file) {
            let isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message({
                    message: '上传文件大小不能超过 2M!',
                    type: 'warning'
                });
            }
            return isLt2M;
        },
        beforeRemove(res, item, type) {
            if (type === 1) {
                this.mapForm.content[item].url = '';
                this.mapForm.content[item].fileList[0] = [];
            }
            else {
                this.mapForm.content[item].thumbnail_url = '';
                this.mapForm.content[item].thumbnailFileList[0] = [];
            }
        },
        handleSuccess(res, item) {
            this.mapForm.content[item].url = res.result;
            this.$refs.uploadErr[item].style.display = 'none';
            this.mapForm.content[item].fileList[0] = { 
                url: res.result 
            };
        },
        handleThumbnail(res, item) {
            this.mapForm.content[item].thumbnail_url = res.result;
            this.mapForm.content[item].thumbnailFileList[0] = { 
                url: res.result 
            };
        },
        swapArray(arr, index1, index2) {
            arr[index1] = arr.splice(index2, 1, arr[index1])[0];
            return arr;
        },
        zIndexDown(arr, index, length) {
            if (index + 1 !== length) {
                this.swapArray(arr, index, index + 1);
            }
        },
        zIndexUp(arr, index, length) {
            if (index !== 0) {
                this.swapArray(arr, index, index - 1);
            }
        },
        onSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                console.log(this.mapForm);
                for (let i = 0; i < this.mapForm.content.length; i++) {
                    if (this.mapForm.content[i].url === '') {
                        this.activeName = this.mapForm.content[i].collapseName;
                        this.$refs.uploadErr[i].style.display = 'block';
                        return false;
                    }
                    else {
                        this.$refs.uploadErr[i].style.display = 'none';
                    }
                    if (this.mapForm.content[i].is_show === '1') {
                        this.mapForm.content[i].status = 1;
                    }
                    else {
                        this.mapForm.content[i].status = 0;
                    }
                }
                if (this.iscategoryParentId) {
                    this.mapForm.parent_id = this.iscategoryParentId;
                }
                if (valid) {
                    axios({
                        method: 'post',
                        url: '//api-ces-test.oasgames.com/api/item/create',
                        params: this.mapForm
                    }).then((response) => {
                        console.log(response);
                        this.$router.go(-1);
                    });
                }
            });
        },
        addMapImg() {
            let count = 0;
            for (let i = 0; i < this.mapForm.content.length; i++) {
                if (this.mapForm.content[i].sort > count) {
                    count = this.mapForm.content[i].sort;
                } 
            }
            this.mapForm.content.push({
                id: count + 1,
                url: "",
                name: "",
                redirect_url: "",
                thumbnail_url: '',
                is_show: '1',
                sort: count + 1,
                status: 0,
                collapseTitle: `图片${count + 1}`,
                collapseName: (count + 1) + '',
                fileList: [],
                thumbnailFileList: []
            });
            this.activeName = (count + 1) + '';
        },
        delectPic(index) {
            this.mapForm.content.splice(index, 1);
        },
        ...mapMutations('utils', {
            iscategoryParentIdChange: 'iscategoryParentIdChange',
        })
    },
    computed: {
        ...mapGetters('map', {
            isMapData: 'isMapData',
        }),
        ...mapGetters('utils', {
            iscategoryParentId: 'iscategoryParentId'
        })
    },
    mounted() {
        this.iscategoryParentIdChange('');
        this.mapForm.parent_title = categoryFn(this.$route.query.breadcrumb, this.mapForm.parent_title);
    },
    components: {
        previewDialog
    }
};
</script>

<style scoped>

</style>
