<template>
    <div class="add-edit-dialog-container">
        <el-dialog :title="addEditDialogTitle" :visible.sync="addEditDialogVisible" width="600px" :before-close="close">
            <el-form :model="addEditDialogForm" ref="addEditDialogForm" :rules="addEditDialogRules" label-width="90px">
                <el-form-item label="文件名:" prop="name" class="classify-input">
                    <el-input placeholder="请输入" v-model="addEditDialogForm.name" class="file-input"></el-input>
                </el-form-item>
                <el-form-item label="文件:" prop="file">
                    <el-upload
                        ref="upload"
                        :action="uploadUrl"
                        :on-remove="handlePdfRemove"
                        :on-success="handlePdfSuccess"
                        :on-change="handlePdfChange"
                        :on-exceed="handlePdfExceed"
                        :before-upload="beforeUpload"
                        :file-list="fileList"
                        :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="sort" class="classify-input">
                    <el-input placeholder="请排序" v-model="addEditDialogForm.sort" class="file-input" maxlength="9"></el-input>
                </el-form-item>
                <el-form-item label="是否展示:" prop="statuz">
                    <el-radio-group v-model="addEditDialogForm.statuz">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="close()">取 消</el-button>
                <el-button type="primary" @click="submitForm('addEditDialogForm')" :disabled="submitBtndisabled">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { validPositiveInteger } from '@/apps/mobile/utils/validate';
import { uploadUrl, staticUrl } from '@/config.js';
import { addLifeFiles, updateLifeFilesStatus } from '@/apps/mobile/api/databank/index';
export default {
    data() {
        // 排序校验
        var checkSort = (rule, value, callback) => {
            if (value && !validPositiveInteger(value)) {
                callback(new Error('格式不正确'));
            } else {
                callback();
            }
        };
        return {
            addEditDialogVisible: false,
            addEditDialogTitle: '新增',
            addEditDialogForm: {},
            submitBtndisabled: false,
            addEditDialogRules: {
                name: [
                    {
                        required: true,
                        message: '请输入文件名',
                        trigger: 'blur',
                    },
                    {
                        max: 30,
                        message: '长度最大30个字符',
                        trigger: 'blur',
                    },
                ],
                sort: [
                    {
                        required: true,
                        message: '请输入排序',
                        trigger: 'blur',
                    },
                    { validator: checkSort, message: '请输入正整数', trigger: 'blur' }
                ],
                statuz: [
                    {
                        required: true,
                        message: '请选择是否展示',
                        trigger: 'change',
                    },
                ],
                file: [
                    {
                        required: true,
                        message: '请上传文件',
                        trigger: 'blur',
                    },
                ],
            },
            fileList: [],
            type: null,
            uploadUrl: uploadUrl,
        };
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let formData = {
                        ...this.addEditDialogForm,
                        dataTable: 1,
                    };
                    if (this.type === 'add') {
                        console.log(formData);
                        let message = '新增成功';
                        addLifeFiles(formData)
                            .then(res => {
                                console.log(res);
                                this.completeOperation(message);
                            })
                            .catch(() => {
                                this.submitBtndisabled = false;
                            });
                    }
                    if (this.type === 'edit') {
                        console.log(formData);
                        let message = '修改成功';
                        let data = {
                            id: formData.id,
                            name: formData.name,
                            url: formData.url,
                            sort: formData.sort,
                            statuz: formData.statuz,
                            dataTable: formData.dataTable,
                        };
                        console.log(data);
                        updateLifeFilesStatus(data)
                            .then(res => {
                                console.log(res);
                                    this.completeOperation(message);
                            })
                            .catch(() => {
                                this.submitBtndisabled = false;
                            });
                    }
                } else {
                    return false;
                }
            });
        },
        handlePdfChange() {},
        handlePdfRemove() {
            this.addEditDialogForm.url = '';
            this.addEditDialogForm.file = null;
        },
        handlePdfSuccess(response) {
            console.log(response);
            this.addEditDialogForm.url = response.data.pathUrl;
            this.addEditDialogForm.file = true;
            this.$refs['addEditDialogForm'].validateField('file');
        },
        handlePdfExceed() {
            this.$message.warning('只能上传一个文件!');
        },
        beforeUpload(file) {
            console.log(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;
        },
        open(type, data) {
            this.type = type;
            console.log(data);
            if (type === 'edit') {
                this.addEditDialogTitle = '编辑';
                if (data.url) {
                    this.fileList = [
                        {
                            name: data.url,
                            url: data.url,
                            hasBeenUploaded: true,
                            newName: data.url,
                        },
                    ];
                    this.addEditDialogForm = Object.assign({ file: true }, data);
                } else {
                    this.addEditDialogForm = Object.assign({ file: null }, data);
                }
            } else {
                this.addEditDialogTitle = '新增';
                this.addEditDialogForm = { statuz: 1, file: null };
            }
            this.addEditDialogVisible = true;
        },
        close() {
            this.$refs.upload.clearFiles();
            this.fileList = [];
            this.$refs['addEditDialogForm'].resetFields();
            this.addEditDialogVisible = false;
        },
        completeOperation(message) {
            this.$message({
                type: 'success',
                message,
            });
            this.close();
            this.submitBtndisabled = false;
            this.$emit('queryListData');
        },
    },
};
</script>
<style lang="stylus" scoped>
.add-edit-dialog-container {
    .file-input {
        width: 200px;
    }

    .sort-input {
        width: 120px;
    }

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