<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="name">
                    <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="type">
                    <el-select placeholder="请选择" v-model="addEditDialogForm.type">
                        <el-option label="用户协议" :value="1"></el-option>
                        <el-option label="专家协议" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="启用状态:" prop="statuz">
                    <el-switch
                        v-model="addEditDialogForm.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('addEditDialogForm')"
                    :disabled="submitBtndisabled"
                >确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { uploadUrl, staticUrl } from '@/config.js';
import { addExpertAgreement, updateExpertAgreement, queryAllExpert } from '@/apps/mobile/api/expert/index';
export default {
    data() {
        return {
            addEditDialogVisible: false,
            addEditDialogTitle: '新增',
            addEditDialogForm: {},
            submitBtndisabled: false,
            addEditDialogRules: {
                name: [
                    {
                        required: true,
                        message: '请输入',
                        trigger: 'blur',
                    },
                    {
                        max: 30,
                        message: '长度最大30个字符',
                        trigger: 'blur',
                    },
                ],
                // createUserId: [
                //     {
                //         required: true,
                //         message: '请选择',
                //         trigger: ['change', 'blur'],
                //     },
                // ],
                url: [
                    {
                        required: true,
                        message: '请输入',
                        trigger: 'blur',
                    },
                ],
                statuz: [
                    {
                        required: true,
                        message: '请选择启用状态',
                        trigger: 'change',
                    },
                ],
                file: [
                    {
                        required: true,
                        message: '请上传文件',
                        trigger: 'blur',
                    },
                ],
                type: [
                    {
                        required: true,
                        message: '请选择',
                        trigger: 'change',
                    },
                ],
            },
            type: null,
            expertList: [],
            uploadUrl: uploadUrl,
            fileList: [],
        };
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let formData = Object.assign({}, this.addEditDialogForm);
                    if (this.type === 'add') {
                        let message = '新增成功';
                        formData.createUserId = this.$userId();
                        addExpertAgreement(formData)
                            .then(res => {
                                this.completeOperation(message);
                            })
                            .catch(() => {
                                this.submitBtndisabled = false;
                            });
                    }
                    if (this.type === 'edit') {
                        let message = '修改成功';
                        let data = {
                            id: formData.id,
                            name: formData.name,
                            createUserId: formData.createUserId,
                            url: formData.url,
                            statuz: formData.statuz,
                            type: formData.type,
                        };
                        updateExpertAgreement(data)
                            .then(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;
            if (type === 'edit') {
                this.addEditDialogTitle = '编辑';
                if (data.url) {
                    this.fileList = [
                        {
                            name: data.url,
                            url: staticUrl + 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;
        },
        queryAllExpert() {
            queryAllExpert()
                .then(res => {
                    this.expertList = res;
                })
                .catch();
        },
        close() {
            this.$refs.upload.clearFiles();
            this.$refs['addEditDialogForm'].resetFields();
            this.fileList = [];
            this.addEditDialogVisible = false;
        },
        completeOperation(message) {
            this.$message({
                type: 'success',
                message,
            });
            this.close();
            this.submitBtndisabled = false;
            this.$emit('queryListData');
        },
    },
    watch: {
        addEditDialogType(val) {
            switch (val) {
                case 'add':
                    this.addEditDialogTitle = '新增';
                    break;
                case 'edit':
                    this.addEditDialogTitle = '编辑';
                    break;
                default:
                    this.addEditDialogTitle = '新增';
                    break;
            }
        },
    },
};
</script>
<style lang="stylus" scoped>
.add-edit-dialog-container {
    .el-input {
        width: auto;
    }

    ::v-deep .el-input__inner {
        width: 200px;
    }
}
</style>
