<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="name" class="classify-input">
                    <el-input placeholder="请输入" v-model="formData.name"></el-input>
                </el-form-item>
                <el-form-item label="品牌:" prop="brandId" class="classify-input">
                    <BrandList
                        ref="brand"
                        @brandEmpty="brandEmpty"
                        @brandChange="brandChange"
                        :brandName="brandName"
                    ></BrandList>
                    <!-- <el-input placeholder="请输入" v-model="formData.brandId"></el-input> -->
                </el-form-item>
                <el-form-item label="图集:" prop="file">
                    <!-- <p class="color666">图片大小不能超过3MB</p> -->
                    <Upload
                        :fileList="fileList"
                        @changeUploadFile="changeUploadFile"
                        @validateUpload="validateUpload"
                        :limitUpload="3"
                        :maximumSize="maximumSize"
                        :uploadType="1"
                        ref="upload"
                    ></Upload>
                </el-form-item>
                <el-form-item label="推荐价格:" prop="price">
                    <el-input placeholder="请输入" v-model="formData.price"></el-input>
                </el-form-item>
                <el-form-item label="供应商:" prop="manufacturer">
                    <el-input placeholder="请输入" v-model="formData.manufacturer"></el-input>
                </el-form-item>
                <el-form-item label="联系电话:" prop="telephone">
                    <el-input placeholder="请输入" v-model="formData.telephone"></el-input>
                </el-form-item>
                <el-form-item label="联系人:" prop="contactPerson">
                    <el-input placeholder="请输入" v-model="formData.contactPerson"></el-input>
                </el-form-item>
                <el-form-item label="描述:" prop="descr">
                    <el-input placeholder="请输入" type="textarea" v-model="formData.descr" maxLength="300"></el-input>
                </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 Upload from '@/apps/mobile/components/uploadAuto/index';
import { staticPath } from '@/apps//mobile/utils/util';
import { addData, editData } from '@/apps/mobile/api/shop/index';
import BrandList from '@/apps/mobile/components/brandLongSerch/index'; // 电梯品牌远程搜索
import { validWithoutZero } from '@/apps/mobile/utils/validate';
export default {
    components: {
        Upload,
        BrandList,
    },

    data() {
        // 手机验证
        let phoneRoule = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入手机号码'));
            } else {
                let reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
                if (!reg.test(value)) {
                    callback(new Error('请输入正确电话号码！'));
                } else {
                    callback();
                }
            }
        };
        // 价格校验
        var checkPrice = (rule, value, callback) => {
            if (value && !validWithoutZero(value)) {
                callback(new Error('格式不正确'));
            } else {
                callback();
            }
        };
        return {
            type: null,
            visible: false,
            formData: { file: null },
            title: '新增',
            submitBtndisabled: false,
            rules: {
                telephone: [{ required: true, validator: phoneRoule, trigger: 'blur' }],
                contactPerson: [
                    { required: true, message: '请输入联系人', trigger: 'blur' },
                    { max: 20, message: '长度最大20个字符', trigger: 'blur' },
                ],
                descr: [
                    { required: true, message: '请输入描述', trigger: 'blur' },
                    { max: 300, message: '长度最大300个字符', trigger: 'blur' },
                ],
                name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { max: 20, message: '长度最大20个字符', trigger: 'blur' },
                ],
                brandId: [{ required: true, message: '请选择品牌', trigger: 'blur' }],
                file: [{ required: true, message: '请上传图片', trigger: 'blur' }],
                manufacturer: [
                    { required: true, message: '请添加供应商', trigger: 'blur' },
                    { max: 30, message: '长度最大30个字符', trigger: 'blur' },
                ],
                price: [
                    {
                        required: true,
                        message: '请输入推荐价格',
                        trigger: 'blur',
                    },
                    { validator: checkPrice, message: '请输入正确的价格', trigger: 'blur' },
                ],
            },
            fileList: [], // 图片列表
            maximumSize: 3, //图片大小  不超过3MB
            brandName: '', //电梯名称
        };
    },
    methods: {
        open(type, data) {
            this.type = type;
            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.visible = true;
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let message = '';
                    let imgs = this.fileList.map(item => {
                        return item.response.data.pathUrl;
                    });
                    imgs = imgs.join(',');
                    let obj = { ...this.formData, imgs };
                    delete obj.file;
                    if (this.type === 'add') {
                        message = '新增成功';
                        addData(obj)
                            .then(res => {
                                if(res.statusCode === "1"){
                                    this.completeOperation(message);
                                }
                                else{
                                    this.$message.error(data.message);
                                }
                            })
                            .catch(err => err);
                    }
                    if (this.type === 'edit') {
                        message = '修改成功';
                        let editObj = {
                            id: obj.id,
                            name: obj.name,
                            brandId: obj.brandId,
                            descr: obj.descr,
                            statuz: obj.statuz,
                            telephone: obj.telephone,
                            manufacturer: obj.manufacturer,
                            contactPerson: obj.contactPerson,
                            price: obj.price,
                            imgs,
                        };
                        console.log(editObj, 'editObj');
                        editData(editObj)
                            .then(res => {
                                if(res.statusCode === "1"){
                                    this.completeOperation(message);
                                }
                                else{
                                    this.$message.error(data.message);
                                }
                            })
                            .catch(err => err);
                    }
                } else {
                    return false;
                }
            });
        },
        close() {
            this.$refs['formData'].resetFields();
            this.visible = false;
            this.formData = { file: null };
            this.fileList = [];
            this.$refs.brand.reset();
        },
        validateUpload(data) {
            this.changeUploadFile(data.fileList);
            this.formData.file = data.validateValues;
            this.$refs['formData'].validateField('file');
        },
        changeUploadFile(fileList) {
            this.fileList = fileList;
        },
        completeOperation(message) {
            this.$message({
                type: 'success',
                message,
            });
            this.close();
            this.submitBtndisabled = false;
            this.$emit('queryListData');
        },
        brandChange(data) {
            if (data.id) {
                this.$set(this.formData, 'brandId', data.id);
            } else {
                this.formData.brandId = null;
            }
            this.$refs['formData'].validateField('brandId');
        },
        brandEmpty() {
            this.formData.brandId = null;
            this.$refs['formData'].validateField('brandId');
        },
    },
    watch: {
        addEditDialogType(val) {
            switch (val) {
                case 'add':
                    this.title = '新增';
                    break;
                case 'edit':
                    this.title = '编辑';
                    break;
                default:
                    this.title = '新增';
                    break;
            }
        },
        fileList(val) {
            this.$nextTick(() => {
                this.$refs.upload.changeHideUpload();
            });
        },
    },
};
</script>
<style lang="stylus" scoped>
.add-edit-dialog-container {
    ::v-deep .el-input__inner {
        width: 200px;
    }

    ::v-deep .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    ::v-deep .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    ::v-deep .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 80px;
        height: 80px;
        line-height: 80px;
        text-align: center;
    }

    ::v-deep .avatar {
        width: 80px;
        height: 80px;
        display: block;
    }
}
</style>
