<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="title">
                    <el-input placeholder="请输入" v-model="formData.title"></el-input>
                </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="expression">
                    <el-input placeholder="请输入" v-model="formData.expression" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="解决方法:" prop="solution">
                    <el-input placeholder="请输入" v-model="formData.solution" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="图片:" prop="file" class="plate-icon">
                    <Upload
                        :fileList="fileList"
                        @changeUploadFile="changeUploadFile"
                        @validateUpload="validateUpload"
                        :limitUpload="limitUpload"
                        :maximumSize="maximumSize"
                        :uploadType="1"
                        ref="upload"
                    ></Upload>
                </el-form-item>
                <el-form-item prop="lockFlag" label="是否打赏:">
                    <el-switch
                        v-model="formData.lockFlag"
                        active-text="是"
                        inactive-text="否"
                        :active-value="1"
                        :inactive-value="0"
                    ></el-switch>
                </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 { validPrice } from '@/apps/mobile/utils/validate';
import Upload from '@/apps/mobile/components/uploadAuto/index';
import { addData, editData } from '@/apps/mobile/api/question/index';
import { queryAllExpert } from '@/apps/mobile/api/expert/index';
import { staticPath } from '@/apps//mobile/utils/util';
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 {
            type: null,
            title: '新增',
            submitBtndisabled: false,
            visible: false,
            rules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                    { max: 30, message: '长度最大30个字符', trigger: 'blur' },
                ],
                expression: [
                    {
                        required: true,
                        message: '请输入问题现象',
                        trigger: 'blur',
                    },
                    { max: 500, message: '长度最大500个字符', trigger: 'blur' },
                ],
                solution: [
                    {
                        required: true,
                        message: '请输入解决方法',
                        trigger: 'blur',
                    },
                    { max: 500, message: '长度最大500个字符', trigger: 'blur' },
                ],
                file: [
                    {
                        required: true,
                        message: '请上传图片',
                        trigger: 'blur',
                    },
                ],
                brandId: [
                    {
                        required: true,
                        message: '请从列表中选择品牌,直接输入无效',
                        trigger: ['blur', 'change'],
                    },
                ]
            },
            fileList: [], // 图片列表
            maximumSize: 3, //图片大小  不超过3MB
            limitUpload: 3, //图片不超过3张
            formData: { file: null, brandId: null, lockFlag: 0 },
            exportList: [], //专家列表
            brandName: '', //电梯名称
        };
    },
    methods: {
        open(type, data) {
            console.log(data, 'data');
            this.type = type;
            let obj1 = {
                file: null,
            };
            if (type === 'edit') {
                this.title = '编辑';
                this.brandName = data.brandName;
                this.formData = { ...data, file: true };
                if (this.formData.imgs)
                    this.fileList = this.formData.imgs.map(item => {
                        let url = staticPath(item);
                        return {
                            name: '',
                            url,
                            response: {
                                data: { pathUrl: item },
                            },
                        };
                    });
            } else {
                this.title = '新增';
                this.formData = { ...obj1 };
            }
            this.visible = true;
        },
        close() {
            this.type = null;
            this.$refs.upload.clearFiles(); // 清空已上传的文件列表
            this.fileList = [];
            this.formData = { file: null, brandId: null };
            this.submitBtndisabled = false;
            this.visible = false;
            this.brandName = null; //清空品牌框内容
            this.$refs['brand'].reset(); //清空品牌框内容 两种方法都要写
            this.$refs['formData'].resetFields();
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.submitBtndisabled = true;
                    let message = '';
                    let imgs = [];
                    if (this.fileList.length > 0) {
                        console.log(this.fileList, 'this.fileList');
                        imgs = this.fileList.map(item => {
                            return item.response.data.pathUrl;
                        });
                    }
                    imgs = imgs.join(',');
                    console.log(imgs, 'imgs');

                    let obj = Object.assign({}, { ...this.formData, imgs });
                    console.log(obj);
                    if (this.type === 'add') {
                        message = '新增成功';
                        delete obj.file;
                        obj.expert = 1;
                        addData(obj)
                            .then(res => {
                                if (res.statusCode === '1') {
                                    this.completeOperation(res.message);
                                } else {
                                    this.$message.warning(res.message);
                                }
                            })
                            .catch(err => err);
                    }
                    if (this.type === 'edit') {
                        message = '修改成功';
                        let editObj = {
                            id: obj.id,
                            statuz: obj.statuz,
                            title: obj.title,
                            expert: 1,
                            expression: obj.expression,
                            solution: obj.solution,
                            imgs,
                            brandId: obj.brandId,
                            lockFlag: obj.lockFlag,
                        };
                        console.log(editObj, 'editObj');
                        editData(editObj)
                            .then(res => {
                                if (res.statusCode === '1') {
                                    this.completeOperation(res.message);
                                } else {
                                    this.$message.warning(res.message);
                                }
                            })
                            .catch(err => err);
                    }
                }
            });
        },
        /**
         * 将新增、编辑操作完成之后共同需要调用的方法放在此函数里面
         * @param {String} message 提示信息
         */
        completeOperation(message) {
            this.$message({
                type: 'success',
                message,
            });
            this.close();
            this.submitBtndisabled = false;
            this.$emit('queryListData');
        },
        /**
         * 手动验证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');
        },
        queryExpert() {
            queryAllExpert()
                .then(res => {
                    console.log(res, '专家列表');
                    this.exportList = res.data;
                    this.exportList.forEach(item => {
                        // 需转字符串才能回显
                        item.userId = Number(item.userId);
                    });
                })
                .catch(err => err);
        },
        brandChange(data) {
            if (data.id) {
                this.$set(this.formData, 'brandId', data.id);
            } else {
                this.formData.brandId = null;
            }
            console.log(this.formData, 'this.formData');

            this.$refs['formData'].validateField('brandId');
        },
        brandEmpty() {
            this.formData.brandId = null;
            this.$refs['formData'].validateField('brandId');
        },
    },
    created() {
        this.queryExpert();
    },
    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>
