<template>
    <div class="add-edit-dialog-container">
        <el-dialog
            :title="title"
            :visible.sync="visible"
            width="700px"
            :before-close="close"
            :close-on-click-modal="false"
        >
            <el-form :model="formData" ref="formData" :rules="rules" label-width="90px">
                <el-form-item label="标题:" prop="title">
                    <el-input placeholder="请输入" v-model="formData.title"></el-input>
                </el-form-item>
                <el-form-item label="作者:" prop="userId" class="classify-input">
                    <el-select placeholder="请输入作者并选择" v-model="formData.userId" clearable filterable :filter-method="brandKeyChange">
                        <el-option
                            :label="item.name"
                            :value="item.userId"
                            v-for="item in exportList"
                            :key="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="品牌:" prop="brandId" class="classify-input">
                    <BrandList
                        @brandChange="brandChange"
                        @brandEmpty="brandEmpty"
                        :brandName="brandName"
                        ref="brand"
                    ></BrandList>
                </el-form-item>

                <el-form-item label="封面图:" prop="cover" class="plate-icon pic">
                    <!-- <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="fileVideo" class="classify-input video-input">
                    <Upload
                        :fileListVideo="videofileList"
                        @changeUploadFileVideo="changeUploadFileVideo"
                        @validateUploadVideo="validateUploadVideo"
                        :limitUploadVideo="1"
                        :maximumSizeVideo="maximumSizeVideo"
                        :uploadType="2"
                        ref="videoupload"
                        class="video"
                    ></Upload>
                </el-form-item>
                <el-form-item label="描述:" prop="descr">
                    <el-input placeholder="请输入" v-model="formData.descr" type="textarea"></el-input>
                </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 { validPrice } from '@/apps/mobile/utils/validate';
import Upload from '@/apps/mobile/components/uploadAuto/index';
import { addData, editData } from '@/apps/mobile/api/school/index';
import { queryExpertList } from '@/apps/mobile/api/expert/index';
import { staticUrl } from '@/config.js';
import { staticPath } from '@/apps//mobile/utils/util';
import { queryPageUser } from '@/apps/mobile/api/operation/user/index';
import BrandList from '@/apps/mobile/components/brandLongSerch/index'; // 电梯品牌远程搜索
export default {
    components: {
        Upload,
        BrandList,
    },
    data() {
        // 验证数字
        var checkNumber = (rule, value, callback) => {
            if (value && !validPrice(value)) {
                callback(new Error('格式不正确'));
            } else {
                callback();
            }
        };
        return {
            title: '新增',
            submitBtndisabled: false,
            rules: {
                file: [
                    {
                        required: true,
                        message: '请上传课程封面',
                        trigger: 'blur',
                    },
                ],
                fileVideo: [
                    {
                        required: true,
                        message: '请上传课程视频',
                        trigger: 'blur',
                    },
                ],
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                    {
                        max: 50,
                        message: '长度最大50个字符',
                        trigger: 'blur',
                    },
                ],
                userId: [
                    {
                        required: true,
                        message: '请选择作者',
                        trigger: ['blur', 'change'],
                    },
                ],
                descr: [
                    { required: true, message: '请输入描述', trigger: 'blur' },
                    {
                        max: 500,
                        message: '长度最大500个字符',
                        trigger: 'blur',
                    },
                ],
                brandId: [{ required: true, message: '请从列表中选择品牌,直接输入无效', trigger: 'blur' }],
            },
            userId: null,
            fileList: [], // 图片列表
            maximumSize: 3, //图片大小不超过3MB
            videofileList: [], // 视频列表
            maximumSizeVideo: 50, //视频大小
            formData: { fileVideo: null, file: null },
            visible: false,
            type: null,
            exportList: [], //专家列表
            brandName: '', //电梯名称
        };
    },
    methods: {
        open(type, data) {
            this.type = type;
            if (type === 'edit') {
                let obj = {
                    sort: {
                        order: 'desc',
                        orderBy: 'create_time',
                    },
                }
                queryPageUser(obj)
                    .then(res => {
                        console.log('res.data.records---',res.data.records);
                        for (let i = 0; i < res.data.records.length; i++) {
                            this.exportList.push(res.data.records[i]);
                        }
                    })
                    .catch(err => err);
                this.brandName = data.brandName;
                this.title = '编辑';
                this.formData = { ...data, file: null, fileVideo: null };
                if (this.formData.cover) {
                    this.formData.file = true;
                    let picList = this.formData.cover.split(',');
                    let picfileList = picList.map(item => {
                        let url = staticPath(item);
                        return {
                            name: '',
                            url,
                            response: {
                                data: {
                                    pathUrl: this.formData.cover,
                                },
                            },
                        };
                    });
                    this.fileList = picfileList;
                }
                if (this.formData.url) {
                    this.formData.fileVideo = true;
                    let videoList = this.formData.url.split(',');
                    //   console.log(videoList, "videoList");
                    let fileListVideo = videoList.map(item => {
                        let url = staticPath(item);
                        if (item.indexOf('/') === -1) {
                            let name = item.split('/').pop();
                        } else {
                            name = item;
                        }
                        let name = item.split('/');
                        name = name.pop();
                        return {
                            url,
                            hasBeenUploaded: true,
                            response: {
                                data: { pathUrl: item, pathUrl: url },
                            },
                            name,
                        };
                    });
                    //   console.log(fileListVideo,'fileListVideo');
                    this.videofileList = fileListVideo;
                }
            } else {
                this.title = '新增';
            }
            this.visible = true;
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.submitBtndisabled = true;
                    let message = '';
                    let cover;
                    let url;
                    cover = this.fileList.map(item => {
                        return item.response.data.pathUrl;
                    });
                    cover = cover.join(',');
                    url = this.videofileList.map(item => {
                        return item.response.data.pathUrl;
                    });
                    url = url.join(',');

                    let addobj = Object.assign({}, { ...this.formData });
                    delete addobj.file;
                    delete addobj.fileVideo;
                    let obj = {
                        ...addobj,
                        cover,
                        url,
                    };

                    if (this.type === 'add') {
                        this.$refs['formData'].validateField('brandId');
                        console.log('add');
                        message = '新增成功';
                        obj.checkFlag = 2;
                        obj.createBy = 0; //创建者ID
                        obj.statuz = 0;
                        addData(obj)
                            .then(res => {
                                console.log('success');
                                this.completeOperation(message);
                            })
                            .catch(err => err);
                    }
                    if (this.type === 'edit') {
                        console.log('edit');
                        message = '修改成功';
                        console.log(obj);
                        let editObj = {
                            id: obj.id,
                            createBy: obj.createBy,
                            brandId: obj.brandId,
                            cover: obj.cover,
                            url: obj.url,
                            descr: obj.descr,
                            statuz: obj.statuz,
                            title: obj.title,
                            userId: obj.userId,
                        };
                        console.log(editObj, 'editObj');
                        editData(editObj)
                            .then(() => {
                                this.completeOperation(message);
                            })
                            .catch(err => err);
                    }
                } else {
                    return false;
                }
            });
        },
        /**
         * 将新增、编辑操作完成之后共同需要调用的方法放在此函数里面
         * @param {String} message 提示信息
         */
        completeOperation(message) {
            this.$message({
                type: 'success',
                message,
            });
            this.close();
            this.submitBtndisabled = false;
            this.$emit('queryListData');
        },
        close() {
            this.type = null;
            this.$refs.upload.clearFiles(); // 清空已上传的文件列表
            this.$refs.videoupload.clearFiles(); // 清空已上传的文件列表
            this.fileList = [];
            this.videofileList = [];
            this.formData = { fileVideo: null, file: null };
            this.submitBtndisabled = false;
            this.visible = false;
            this.brandName = null; //清空品牌框内容
            this.$refs.brand.reset(); //清空品牌框内容 两种方法都要写
            this.$refs['formData'].resetFields();
        },
        /**
         * 手动验证upload、更新选择完成的图片数据
         * @param {Object} data: fileList是上传的图片数据 validateValues为true时说明有上传图片 为null时无上传图片
         */
        validateUpload(data) {
            this.changeUploadFile(data.fileList);
            this.formData.file = data.validateValues;
            this.$refs['formData'].validateField('file');
        },
        changeUploadFile(fileList) {
            this.fileList = fileList;
            console.log(this.fileList, 'this.fileList');
        },
        validateUploadVideo(data) {
            this.changeUploadFileVideo(data.fileList);
            this.formData.fileVideo = data.validateValues;
            this.$refs['formData'].validateField('fileVideo');
        },
        changeUploadFileVideo(fileList) {
            this.videofileList = fileList;

            console.log(fileList, 'ssa');
        },
        brandChange(data) {
            if (data.id) {
                this.$set(this.formData, 'brandId', data.id);
            } else {
                this.formData.brandId = null;
            }
            this.$refs['formData'].validateField('brandId');
        },
        brandKeyChange:function(inputKey){
            if(this.formData.userId){
                this.formData.userId = null;
            }
            let obj = {
                name: inputKey,
                sort: {
                    order: 'desc',
                    orderBy: 'create_time',
                },
            }
            queryPageUser(obj)
                .then(res => {
                    this.exportList = res.data.records;
                })
                .catch(err => err);
        },
        // 删除品牌名时调用
        brandEmpty() {
            this.formData.brandId = null;
            this.$refs['formData'].validateField('brandId');
        },
    },
    created() {
        
    },
    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;
    }

    ::v-deep .video .el-upload {
        height: auto;
    }

    ::v-deep .el-upload {
        margin-right: 10px;
    }
}
</style>
