<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="brandId">
                    <BrandList
                        ref="brand"
                        :brandName="brandName"
                        @brandChange="brandChange"
                        @brandEmpty="brandEmpty"
                    ></BrandList>
                </el-form-item>
                <el-form-item label="故障代码" prop="code">
                    <el-input placeholder="请输入内容" v-model="addEditDialogForm.code" maxlength="20"></el-input>
                </el-form-item>
                <el-form-item label="图片:" prop="file" class="plate-icon">
                    <Upload
                        :fileList="fileList"
                        @changeUploadFile="changeUploadFile"
                        @validateUpload="validateUpload"
                        :limitUpload="4"
                        :maximumSize="maximumSize"
                        :uploadType="1"
                        ref="upload"
                    ></Upload>
                </el-form-item>
                <el-form-item label="故障描述:" prop="descr">
                    <el-input
                        type="textarea"
                        placeholder="请输入内容"
                        v-model="addEditDialogForm.descr"
                        maxlength="500"
                    ></el-input>
                </el-form-item>
                <el-form-item label="问题现象:" prop="cause">
                    <el-input
                        type="textarea"
                        placeholder="请输入内容"
                        v-model="addEditDialogForm.cause"
                        maxlength="500"
                    ></el-input>
                </el-form-item>
                <el-form-item label="解决方法:" prop="recoveryMethod">
                    <el-input
                        type="textarea"
                        placeholder="请输入内容"
                        v-model="addEditDialogForm.recoveryMethod"
                        maxlength="500"
                    ></el-input>
                </el-form-item>
                <el-form-item label="排序:" prop="sort">
                    <el-input placeholder="请排序" v-model="addEditDialogForm.sort" maxlength="9"></el-input>
                </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-item label="首页展示:" prop="topFlag">
                    <el-switch
                        v-model="addEditDialogForm.topFlag"
                        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 { staticUrl } from '@/config.js';
import Upload from '@/apps/mobile/components/uploadAuto/index';
import { validPositiveInteger } from '@/apps/mobile/utils/validate';
import BrandList from '@/apps/mobile/components/brandLongSerch/index';
import { addFaultCodes, updateFaultCodesStatus } from '@/apps/mobile/api/databank/index';
export default {
    components: {
        Upload,
        BrandList,
    },
    data() {
        // 排序校验
        var checkSort = (rule, value, callback) => {
            if (value && !validPositiveInteger(value)) {
                callback(new Error('格式不正确'));
            } else {
                callback();
            }
        };
        return {
            addEditDialogVisible: false,
            addEditDialogTitle: '新增',
            addEditDialogForm: {
                brandId: null,
            },
            submitBtndisabled: false,
            addEditDialogRules: {
                brandId: [
                    {
                        required: true,
                        message: '请选择电梯品牌',
                        trigger: 'blur',
                    },
                ],
                code: [
                    {
                        required: true,
                        message: '请填写故障代码',
                        trigger: 'blur',
                    },
                    { max: 20, message: '长度最大20个字符', trigger: 'blur' },
                ],
                descr: [
                    {
                        required: true,
                        message: '请填写故障描述',
                        trigger: 'blur',
                    },
                    { max: 500, message: '长度最大500个字符', trigger: 'blur' },
                ],
                cause: [
                    {
                        required: true,
                        message: '请填写问题现象',
                        trigger: 'blur',
                    },
                    { max: 500, message: '长度最大500个字符', trigger: 'blur' },
                ],
                recoveryMethod: [
                    {
                        required: true,
                        message: '请填写解决方法',
                        trigger: 'blur',
                    },
                    { max: 500, message: '长度最大500个字符', trigger: 'blur' },
                ],
                sort: [
                    {
                        required: true,
                        message: '请填写排序',
                        trigger: 'blur',
                    },
                    { validator: checkSort, message: '请输入正整数', trigger: 'blur' },
                ],
                statuz: [
                    {
                        required: true,
                        message: '请选择状态',
                        trigger: 'change',
                    },
                ],
                topFlag: [
                    {
                        required: true,
                        message: '请选择状态',
                        trigger: 'change',
                    },
                ],
                file: [
                    {
                        required: true,
                        message: '请上传图片',
                        trigger: 'blur',
                    },
                ],
            },
            type: null,
            fileList: [],
            maximumSize: 3,
            brandName: '', //品牌名称
        };
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let imgs = [];
                    if (this.fileList.length > 0) {
                        console.log(this.fileList);
                        imgs = this.fileList.map(item => {
                            return item.response.data.pathUrl;
                        });
                    }
                    imgs = imgs.join(',');
                    console.log(imgs);
                    let formData = Object.assign({}, { ...this.addEditDialogForm, imgs });
                    if (this.type === 'add') {
                        console.log(formData);
                        let message = '新增成功';
                        addFaultCodes(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,
                            brandId: formData.brandId,
                            code: formData.code,
                            descr: formData.descr,
                            cause: formData.cause,
                            recoveryMethod: formData.recoveryMethod,
                            sort: formData.sort,
                            statuz: formData.statuz,
                            topFlag: formData.topFlag,
                            imgs: imgs,
                        };
                        console.log(data);
                        updateFaultCodesStatus(data)
                            .then(res => {
                                console.log(res);
                                this.completeOperation(message);
                            })
                            .catch(() => {
                                this.submitBtndisabled = false;
                            });
                    }
                } else {
                    return false;
                }
            });
        },
        brandChange(data) {
            console.log(data);
            if (data.id) {
                console.log('yes');
                this.$set(this.addEditDialogForm, 'brandId', data.id);
                this.$nextTick(() => {
                    this.$refs['addEditDialogForm'].validateField('brandId');
                });
            } else {
                console.log('no');
                this.$set(this.addEditDialogForm, 'brandId', null);
            }
        },
        brandEmpty() {
            console.log('empty');
            this.$set(this.addEditDialogForm, 'brandId', null);
            this.$nextTick(() => {
                this.$refs['addEditDialogForm'].validateField('brandId');
            });
        },
        validateUpload(data) {
            this.changeUploadFile(data.fileList);
            console.log(data);
            this.addEditDialogForm.file = data.validateValues;
            this.$refs['addEditDialogForm'].validateField('file');
        },
        changeUploadFile(fileList) {
            console.log(fileList);
            this.fileList = fileList;
        },
        open(type, data) {
            this.type = type;
            if (type === 'edit') {
                this.addEditDialogTitle = '编辑';
                this.brandName = data.brandName;
                console.log(data);
                if (data.imgs) {
                    data.file = true;
                    let images = data.imgs.split(',');
                    console.log(images);
                    images.forEach(item => {
                        let obj = {
                            name: '',
                            url: item,
                            response: {
                                data: { pathUrl: item },
                            },
                        };
                        this.fileList.push(obj);
                    });
                    this.addEditDialogForm = { ...data };
                } else {
                    this.addEditDialogForm = Object.assign({ file: null }, data);
                }
            } else {
                this.addEditDialogTitle = '新增';
                this.addEditDialogForm = { statuz: 1, topFlag: 1, file: null };
            }
            this.addEditDialogVisible = true;
        },
        close() {
            this.fileList = [];
            this.brandName = null;
            this.$refs['addEditDialogForm'].resetFields();
            this.$refs.brand.reset();
            this.addEditDialogVisible = false;
        },
        completeOperation(message) {
            this.$message({
                type: 'success',
                message,
            });
            this.close();
            this.submitBtndisabled = false;
            this.$emit('queryListData');
        },
    },
    watch: {
        fileList(val) {
            this.$nextTick(() => {
                this.$refs.upload.changeHideUpload();
            });
        },
    },
};
</script>
<style lang="stylus" scoped>
.add-edit-dialog-container {
    ::v-deep .el-input__inner {
        width: 200px;
    }
}
</style>
