<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="100px"
            >
                <el-form-item label="分类名:" prop="name" class="classify-input">
                    <el-input placeholder="请输入" v-model="addEditDialogForm.name" maxlength="20"></el-input>
                </el-form-item>
                <el-form-item label="品牌" prop="brandId">
                    <BrandList
                        @brandChange="brandChange"
                        @brandEmpty="brandEmpty"
                        :brandName="brandName"
                        :disabled="pid"
                        ref="brand"
                    ></BrandList>
                </el-form-item>
                <el-form-item label="上级分类" class="cascader-father" prop="pid">
                    <el-cascader
                        class="casc"
                        :props="propsOptions"
                        :options="options"
                        v-model="addEditDialogForm.pid"
                        @change="handleChange"
                        filterable
                    ></el-cascader>
                </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="file">
                    <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="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 BrandList from '@/apps/mobile/components/brandLongSerch/index';
import Upload from '@/apps/mobile/components/uploadAuto/index';
import { addLiftCategorys, updateLiftCategorysStatus, queryLiftCategorysTree, queryBrandById } from '@/apps/mobile/api/databank/index';
import { staticUrl } from '@/config.js';
import { validPositiveInteger } from '@/apps/mobile/utils/validate';
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: {
                pid: 0,
                brandId: null,
            },
            submitBtndisabled: false,
            addEditDialogRules: {
                name: [
                    {
                        required: true,
                        message: '请填写分类名称',
                        trigger: 'blur',
                    },
                    { max: 20, message: '长度最大20个字符', trigger: 'blur' },
                ],
                pid: [
                    {
                        required: false,
                        message: '请选择上级分类',
                        trigger: '[blur,change]',
                    },
                ],
                brandId: [
                    {
                        required: false,
                        message: '请选择电梯品牌',
                        trigger: 'blur',
                    },
                ],
                sort: [
                    {
                        required: true,
                        message: '请填写排序',
                        trigger: 'blur',
                    },
                    { max: 20, message: '长度最大20个字符', trigger: 'blur' },
                    { validator: checkSort, message: '请输入正整数', trigger: 'blur' },
                ],
                statuz: [
                    {
                        required: true,
                        message: '请选择状态',
                        trigger: 'blur',
                    },
                ],
                file: [
                    {
                        required: true,
                        message: '请上传封面图',
                        trigger: 'blur',
                    },
                ],
            },
            fileList: [], // 图片列表
            maximumSize: 3, //图片大小  不超过3MB
            type: null,
            propsOptions: {
                checkStrictly: true,
                value: 'id',
                label: 'name',
                children: 'chilList',
                leaf: 'hasChildren',
            },
            options: [],
            brandId: null,
            brandName: '', //品牌名称
        };
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let formData = {
                        ...this.addEditDialogForm,
                    };
                    let files = this.fileList.map(item => {
                        if (item.response) {
                            return item.response.data.pathUrl;
                        } else {
                            return item.pathUrl;
                        }
                    });
                    let pid = this.addEditDialogForm.pid;
                    formData.icon = files.join(',');
                    formData.pid = pid ? pid : 0;
                    if (this.type === 'add') {
                        console.log(formData);
                        let message = '新增成功';
                        addLiftCategorys(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,
                            name: formData.name,
                            pid: formData.pid,
                            icon: formData.icon,
                            sort: formData.sort,
                            statuz: formData.statuz,
                        };
                        console.log(data);
                        updateLiftCategorysStatus(data)
                            .then(res => {
                                console.log(res);
                                this.completeOperation(message);
                            })
                            .catch(() => {
                                this.submitBtndisabled = false;
                            });
                    }
                } else {
                    return false;
                }
            });
        },
        validateUpload(data) {
            console.log(data);
            this.changeUploadFile(data.fileList);
            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;
                if (data.brandId) {
                    this.brandId = data.brandId;
                    this.queryTree();
                }
                console.log(data);
                if (data.icon) {
                    this.fileList = [
                        {
                            url: data.icon,
                            pathUrl: data.icon,
                        },
                    ];
                    this.addEditDialogForm = Object.assign({ file: true }, data);
                } else {
                    this.addEditDialogForm = Object.assign({ file: null }, data);
                }
            } else {
                this.addEditDialogTitle = '新增';
                this.addEditDialogForm = { statuz: 1, file: null };
                if(data){
                    this.brandId = data.brandId;
                    this.addEditDialogForm.brandId = data.brandId;
                    this.addEditDialogForm.pid = 0;
                    queryBrandById(this.brandId)
                    .then(res => {
                        this.brandName = res.data.name;
                        this.queryTree();
                    })
                    .catch();
                }
            }
            this.addEditDialogVisible = true;
        },
        close() {
            this.$refs.upload.clearFiles();
            this.fileList = [];
            this.brandName = null;
            this.$refs['addEditDialogForm'].resetFields();
            this.$refs.brand.reset();
            this.addEditDialogVisible = false;
            this.options = [];
        },
        completeOperation(message) {
            this.$message({
                type: 'success',
                message,
            });
            this.close();
            this.submitBtndisabled = false;
            this.$emit('queryListData');
            this.$emit('queryTree');
        },
        handleChange(node) {
            console.log(node);
            if (this.addEditDialogForm.pid && this.addEditDialogForm.pid != []) {
                let length = this.addEditDialogForm.pid.length;
                this.addEditDialogForm.pid = this.addEditDialogForm.pid[length - 1];
                console.log(this.addEditDialogForm.pid);
            }
        },
        queryTree() {
            queryLiftCategorysTree(this.brandId)
                .then(res => {
                    console.log(res);
                    if (res.data && res.data.length > 0) {
                        res.data.forEach(item => {
                            if (item.chilList && item.chilList.length > 0) {
                                item.chilList.forEach(i => {
                                    i.disabled = true;
                                });
                            }
                        });
                        this.options = res.data;
                    }
                })
                .catch();
        },
        brandChange(data) {
            console.log(data);
            if (data.id) {
                this.brandId = data.id;
                this.$set(this.addEditDialogForm, 'brandId', data.id);
                this.queryTree();
            } else {
                this.addEditDialogForm.brandId = null;
            }
            console.log(this.addEditDialogForm);
            this.$refs['addEditDialogForm'].validateField('brandId');
        },
        brandEmpty() {
            this.brandId = null;
            this.addEditDialogForm.brandId = null;
            this.$refs['addEditDialogForm'].validateField('brandId');
        },
    },
    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;
    }

    ::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>
