<template>
    <div class="add-edit-dialog-container">
        <el-dialog
            :title="title"
            :visible.sync="visible"
            width="600px"
            :before-close="close"
            :close-on-click-modal="false"
        >
            <el-form :model="formData" ref="formData" :rules="rules" label-width="90px">
                <el-form-item label="名称:" prop="imgName">
                    <el-input placeholder="请输入" v-model="formData.imgName"></el-input>
                </el-form-item>
                <el-form-item label="图片:" class="plate-icon" prop="file">
                    <!-- <p class="color666">图片大小不能超过3MB</p> -->
                    <Upload
                        :fileList="fileList"
                        @changeUploadFile="changeUploadFile"
                        @validateUpload="validateUpload"
                        :limitUpload="1"
                        :maximumSize="maximumSize"
                        :uploadType="1"
                        ref="upload"
                    ></Upload>
                </el-form-item>
                <el-form-item label="跳转类型:" prop="jumpType">
                    <el-select v-model="formData.jumpType" placeholder="请选择">
                        <el-option label="pdf" :value="1"></el-option>
                        <el-option label="网页链接" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="跳转链接:" prop="url" v-show="formData.jumpType == 2">
                    <el-input placeholder="跳转链接" v-model="formData.url"></el-input>
                </el-form-item>
                <el-form-item label="文件:" prop="jumpType" v-show="formData.jumpType == 1">
                    <el-upload
                        ref="uploadPdf"
                        :action="uploadUrl"
                        :on-remove="handlePdfRemove"
                        :on-success="handlePdfSuccess"
                        :on-exceed="handlePdfExceed"
                        :before-upload="beforeUpload"
                        :file-list="pdfList"
                        :multiple="false"
                        :limit="1"
                        accept="application/pdf">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
                
                <el-form-item label="显示位置:" prop="type">
                    <el-select v-model="formData.type" placeholder="请选择">
                        <el-option label="工作台banner" :value="1"></el-option>
                        <el-option label="物业端banner" :value="2"></el-option>
                        <el-option label="4.0首页banner" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="排序:" prop="serialNo">
                    <el-input placeholder="请排序" v-model="formData.serialNo" class="sort-input" maxlength="20"></el-input>
                </el-form-item>
                <!-- <el-form-item label="启用状态:">
                    <el-switch
                        v-model="formData.statuz"
                        active-text="开"
                        inactive-text="关"
                        :active-value="1"
                        :inactive-value="0"
                    ></el-switch> -->
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="close()">取 消</el-button>
                <el-button
                    type="primary"
                    @click="submitForm('formData')"
                    :disabled="submitBtndisabled"
                >确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { uploadUrl } from '@/config.js';
import Upload from '@/apps/mobile/components/uploadAuto/index';
import { addBanner, editBanner } from '@/apps/mobile/api/banner/index';
import { validPositiveInteger, validHttps } from '@/apps/mobile/utils/validate';
import { staticPath } from '@/apps//mobile/utils/util';
export default {
    components: {
        Upload,
    },
    data() {
        // http(s)校验
        var checkHttps = (rule, value, callback) => {
            if (value && !validHttps(value)) {
                callback(new Error('格式不正确'));
            } else {
                callback();
            }
        };

        // 排序校验
        var checkSort = (rule, value, callback) => {
            if (value && !validPositiveInteger(value)) {
                callback(new Error('格式不正确'));
            } else {
                callback();
            }
        };
        return {
            uploadUrl: uploadUrl,
            jumpType: null,
            type: null,
            visible: false,
            title: '新增',
            formData: { file: null },
            submitBtndisabled: false,
            fileList: [], // 图片列表
            pdfList: [],//pdf列表
            maximumSize: 3, //图片大小  不超过3MB
            limitUpload: 1,
            rules: {
                imgName: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { max: 30, message: '长度最大30个字符', trigger: 'blur' },
                ],
                jumpType: [{ required: true, message: '请选择跳转类型', trigger: 'change' }],
                type: [{ required: true, message: '请选择显示位置', trigger: 'blur' }],
                serialNo: [
                    { validator: checkSort, message: '请输入正整数', trigger: 'blur' }
                ],
                file: [{ required: true, message: '请上传图片', trigger: 'blur' }],
                url: [
                    { validator: checkHttps, message: '请输入正确的链接地址', trigger: 'blur' }
                ],
            },
        };
    },
    methods: {
        open(type, data) {
            this.type = type;
            let obj1 = {
                file: null,
            };
            if (type === 'edit') {
                this.title = '编辑';
                if (data.image) {
                    obj1.file = true;
                    let url = staticPath(data.image);
                    let obj = {
                        name: '',
                        url,
                        response: {
                            data: { pathUrl: data.image },
                        },
                    };
                    this.fileList.push(obj);

                    this.pdfList = [
                        {
                            name: data.url,
                            url: data.url,
                            hasBeenUploaded: true,
                            newName: data.url,
                        },
                    ];
                }
                this.formData = Object.assign({ ...data, ...obj1 });
            } else {
                this.title = '新增';
                this.formData = obj1;
            }
            this.visible = true;
        },
        close() {
            this.type = null;
            this.$refs['formData'].resetFields();
            this.$refs.upload.clearFiles(); // 清空已上传的文件列表
            this.fileList = [];
            this.pdfList = [];
            this.submitBtndisabled = false;
            this.visible = false;
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.submitBtndisabled = true;
                    let message = '';
                    let image = null;
                    if (this.fileList.length > 0) {
                        console.log(this.fileList, 'this.fileList');

                        image = this.fileList[0].response.data.pathUrl;
                    }
                    let obj = Object.assign({ ...this.formData, image });
                    console.log(obj, 'objj');

                    if (this.type === 'add') {
                        message = '新增成功';
                        delete obj.file;
                        obj.createBy = 0; //创建者ID
                        addBanner(obj)
                            .then(res => {
                                this.completeOperation(message);
                            })
                            .catch(err => err);
                    }
                    if (this.type === 'edit') {
                        message = '修改成功';
                        let editObj = {
                            id: obj.id,
                            imgName: obj.imgName,
                            url: obj.url,
                            jumpType: obj.jumpType,
                            type: obj.type,
                            serialNo: obj.serialNo,
                            image: obj.image,
                        };
                        editBanner(editObj)
                            .then(() => {
                                this.completeOperation(message);
                            })
                            .catch(err => err);
                    }
                }
            });
        },
        /**
         * 手动验证upload、更新选择完成的图片数据
         * @param {Object} data: fileList是上传的图片数据 validateValues为true时说明有上传图片 为null时无上传图片
         */
        validateUpload(data) {
            this.changeUploadFile(data.fileList);
            // console.log(data,'data');
            this.formData.file = data.validateValues;
            this.$refs['formData'].validateField('file');
        },
        changeUploadFile(fileList) {
            this.fileList = fileList;
            console.log(this.fileList, 'this.fileList');
        },
        /**
         * 将新增、编辑操作完成之后共同需要调用的方法放在此函数里面
         * @param {String} message 提示信息
         */
        completeOperation(message) {
            this.$message({
                type: 'success',
                message,
            });
            this.close();
            this.submitBtndisabled = false;
            this.$emit('queryListData');
        },

        handlePdfRemove() {
            this.formData.url = '';
            this.formData.file = null;
        },
        handlePdfSuccess(response) {
            this.formData.url = response.data.pathUrl;
            this.formData.file = true;
            this.$refs['formData'].validateField('file');
        },
        handlePdfExceed() {
            this.$message.warning('只能上传一个文件!');
        },
        beforeUpload(file) {
            let fileType = ['application/pdf'].indexOf(file.type);
            const isLt5M = file.size / 1024 / 1024 < 8;
            if (fileType === -1) {
                this.$message.warning('文件只能是pdf格式!');
            }
            if (!isLt5M) {
                this.$message.warning('文件大小不能超过8MB!');
            }
            return fileType !== -1 && isLt5M;
        },
    },
    watch: {
        fileList(val) {
            this.$nextTick(() => {
                this.$refs.upload.changeHideUpload();
            });
        },
    },
};
</script>
<style lang="stylus" scoped>
.add-edit-dialog-container {
    ::v-deep .el-input {
        width: auto;
    }

    ::v-deep .el-input__inner {
        width: 200px;
    }

    .upload {
        display: inline-block;
    }
}
</style>
