<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="image">
                    <p class="color666">图片大小不能超过5MB</p>
                    <UploadImage v-model="formData.image" :limit="1" ref="bannerUpload"></UploadImage>
                    <!-- <Upload :fileList="bannerList" @changeUploadFile="bannerChangeUploadFile" @validateUpload="bannerValidateUpload" :limitUpload="1" :maximumSize="maximumSize" :uploadType="1" ref="bannerUpload"></Upload> -->
                </el-form-item>
                <el-form-item label="跳转类型:" prop="jumpType">
                    <el-select v-model="formData.jumpType" placeholder="请选择" clearable="true">
                        <el-option label="pdf" :value="1"></el-option>
                        <el-option label="网页链接" :value="2"></el-option>
                        <el-option label="图片" :value="3"></el-option>
                    </el-select>
                </el-form-item>

                <span v-show="formData.jumpType">
                    <el-form-item label="落地页:" prop="url">
                        <span v-show="formData.jumpType == 1">
                            <el-upload ref="uploadPdf" :action="uploadUrl" :on-remove="handlePdfRemove" :on-success="handlePdfSuccess" :on-exceed="handlePdfExceed" :before-upload="beforePdfUpload" :file-list="pdfList" :multiple="false" :limit="1" accept="application/pdf">
                                <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                        </span>
                        <span v-show="formData.jumpType == 2">
                            <el-input placeholder="跳转链接" v-model="formData.url"></el-input>
                        </span>
                        <span v-show="formData.jumpType == 3">
                            <p class="color666">图片大小不能超过5MB</p>
                            <UploadImage v-model="formData.url" :limit="1" ref="bannerDetailUpload"></UploadImage>
                            <!-- <Upload :fileList="bannerDetailList" @changeUploadFile="bannerDetailChangeUploadFile" @validateUpload="bannerDetailValidateUpload" :limitUpload="1" :maximumSize="maximumSize" :uploadType="1" ref="bannerDetailUpload"></Upload> -->
                        </span>
                    </el-form-item>
                </span>

                <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 UploadImage from '@/apps/mobile/components/UploadImage/index';
const defaultFormData = { jumpType: null, imgName: null, url: null, type: 3, serialNo: null };
export default {
    components: { Upload,UploadImage },
    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,
            visible: false,
            title: '新增',
            type: '',
            formData: JSON.parse(JSON.stringify(defaultFormData)),
            submitBtndisabled: false,
            pdfList: [], //pdf列表
            maximumSize: 3, //图片大小  不超过3MB
            limitUpload: 1,
            rules: {
                imgName: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { max: 30, message: '长度最大30个字符', trigger: 'blur' },
                ],
                // jumpType: [{ message: '请选择跳转类型', trigger: 'change' }],
                type: [{ required: true, message: '请选择显示位置', trigger: 'change' }],
                serialNo: [{ validator: checkSort, message: '请输入正整数', trigger: 'blur' }],
                image: [{ required: true, message: '请上传图片', trigger: 'change' }],
                url: [{ validator: checkHttps, message: '请输入正确的链接地址', trigger: 'blur' }],
            },
        };
    },
    methods: {
        open(type, data) {
            if (type === 'edit') {
                this.type = "edit";
                this.title = '编辑';
                let tempData = { ...JSON.parse(JSON.stringify(defaultFormData)), ...JSON.parse(JSON.stringify(data)) };
                
                //pdf
                if (tempData.jumpType === 1) {
                    this.pdfList.push({ name: tempData.url, url: tempData.url });
                }
                //网页链接
                if (tempData.jumpType === 2) {
                }
                //图片
                if (tempData.jumpType === 3) {
                    
                }
                this.formData = tempData;

            }
            if (type === 'add') {
                this.type = "add";
                this.formData = JSON.parse(JSON.stringify(defaultFormData));
            }

            this.visible = true;
        },
        close() {
            this.$refs.formData.resetFields();
            this.type = "";
            this.formData = JSON.parse(JSON.stringify(defaultFormData));
            this.pdfList = [];
            this.submitBtndisabled = false;
            this.visible = false;
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitBtndisabled = true;
                    let message = '';
                    let obj = Object.assign({ ...this.formData });
                    if (this.type === 'add') {
                        message = '新增成功';
                        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);
                    }
                }
            });
        },

        /**
         * 将新增、编辑操作完成之后共同需要调用的方法放在此函数里面
         * @param {String} message 提示信息
         */
        completeOperation(message) {
            this.$message({
                type: 'success',
                message,
            });
            this.close();
            this.submitBtndisabled = false;
            this.$emit('queryListData');
        },

        //--------------------------------pdf上传----------------------------------------------------------
        handlePdfRemove() {
            this.formData.url = '';
        },
        handlePdfSuccess(response) {
            this.formData.url = response.data.pathUrl;
            this.$refs['formData'].validateField('url');
        },
        handlePdfExceed() {
            this.$message.warning('只能上传一个文件!');
        },
        beforePdfUpload(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;
        },
        //--------------------------------pdf上传----------------------------------------------------------
    },
};
</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>
