<!--
 * @Author: your name
 * @Date: 2020-10-22 18:26:27
 * @LastEditTime: 2021-05-21 13:31:31
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \WEB\userCenter\src\views\system\users\popups\AddOrEditUserInfo.vue
-->
<template>
    <div class="alert-body__main_content">
        <zz-form :cols="formCols" :data="formData" :rules="formRules" :errors="formErrors" labelWidth="120" ref="form">
            <el-input slot="password" type="password" v-model="formData.password"></el-input>
            <el-input slot="passwordOK" type="password" v-model="formData.passwordOK"></el-input>
            <el-select slot="status" v-model="formData.enableState">
                <el-option v-for="(item, index) in allStatus" :key="index" :label="item.label" :value="item.id">{{ item.label }}</el-option>
            </el-select>
            <el-input slot="roleId" v-if="noAllRoleId" v-model="formData.roleName" disabled></el-input>
            <el-select v-else slot="roleId" v-model="formData.roleId">
                <el-option
                    v-show="item.roleState"
                    v-for="(item, index) in allRoleId"
                    :key="index"
                    :label="item.roleName"
                    :value="item.id"
                    >{{ item.roleName }}</el-option
                >
            </el-select>
            <el-select slot="userType" v-model="formData.userType">
                <el-option v-for="(item, index) in allUserType" :key="index" :label="item.dictValue" :value="item.dictCode">{{
                    item.dictValue
                }}</el-option>
            </el-select>
            <select-tree
                :props="defaultProps"
                slot="companyOrgId"
                class="new-select-tree"
                selectTreeTitle="组织机构"
                width="320"
                treeWidth="320"
                :options="organListCompany"
                @selected="selectedcompanyOrgId"
                v-model="formData.companyOrgId"
                :labelModel="formData.companyOrgName"
            />
            <select-tree
                :props="defaultProps"
                slot="deptOrgId"
                class="new-select-tree"
                selectTreeTitle="组织机构"
                width="320"
                treeWidth="320"
                :options="organListdepartment"
                @selected="selecteddeptOrgId"
                v-model="formData.deptOrgId"
            />
            <div class="imgdis-div" slot="companylogo" v-show="formData.photo">
                <i class="el-icon-delete" @click="delformphoto"></i>
                <img :src="envConfig.baseImgApi + formData.photo" alt="" width="60" height="60" />
            </div>
            <el-upload
                v-show="!formData.photo"
                :headers="token"
                ref="uploaduserlogo"
                class="mini-upload"
                slot="companylogo"
                limit="1"
                action="/sc-user-center/user/addUserPhoto"
                list-type="picture-card"
                :on-success="uploadsuccess"
                :auto-upload="true"
                name="avatarfile"
            >
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{ file }">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                        <!-- <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                            <i class="el-icon-zoom-in"></i>
                        </span> -->
                        <!-- <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                            <i class="el-icon-download"></i>
                        </span> -->
                        <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                            <i class="el-icon-delete"></i>
                        </span>
                    </span>
                </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
        </zz-form>
    </div>
</template>
<script>
import envConfig from '@/config';
// import SelectTree from '@/components/common/SelectTree.vue';

export default {
    props: ['params'],
    components: {
        // SelectTree
    },

    data() {
        var validatePassContrast = (rule, value, callback) => {
            if (value == '' || value == null) {
                callback(new Error('请输入密码'));
            } else {
                if (this.formData.password !== value) {
                    callback(new Error('两次密码不一致'));
                }
                callback();
            }
        };
        var validatePass = (rule, value, callback) => {
            if (value == '' || value == null) {
                callback(new Error('请输入密码'));
            } else {
                if (value.length < 6) {
                    callback(new Error('密码位数不得少于6位'));
                }
                callback();
            }
        };

        return {
            token: {
                [localStorage.getItem('SC_token') && 'Authorization']: 'Bearer ' + localStorage.getItem('SC_token')
            },
            isLoginUser: false,
            envConfig: envConfig,
            organList: [
                {
                    id: 1,
                    tenantId: 'string123',
                    orgName: '公司',
                    parentOrgId: 0,
                    orgs: [{ id: 2, tenantId: 'string123', orgName: '部门', parentOrgId: 1, orgs: null, display: true }],
                    display: true
                }
            ],
            organListCompany: [],
            organListdepartment: [],

            defaultProps: {
                value: 'id', // 唯一标识
                label: 'orgName', // 标签显示
                children: 'orgs' // 子级
            },
            formData: {
                companyOrgId: '',
                companyOrgName: '',
                deptOrgId: '',
                deptOrgName: '',
                email: '',
                enableState: '1',
                id: '',
                phone: '',
                password: '',
                passwordOK: '',
                photo: '',
                remark: '',
                roleId: '',
                status: '',
                tenantId: '',
                userType: '',
                username: ''
            },
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            allStatus: [
                {
                    id: '0',
                    label: '停用'
                },
                {
                    id: '1',
                    label: '启用'
                }
            ],
            allRoleId: [],
            noAllRoleId: false,
            noIdInAllRoleId: false,
            allUserType: [],
            formCols: [
                [
                    {
                        label: '所属公司',
                        prop: 'companyOrgId',
                        slot: 'companyOrgId'
                    },
                    {
                        label: '所属部门',
                        prop: 'deptOrgId',
                        slot: 'deptOrgId'
                    },
                    {
                        label: '用户名',
                        prop: 'username',
                        input: true
                    },
                    {
                        label: '手机号码',
                        prop: 'phone',
                        input: true
                    },
                    {
                        label: '密码',
                        prop: 'password',
                        slot: 'password'
                    },
                    {
                        label: '确认密码',
                        prop: 'passwordOK',
                        slot: 'passwordOK'
                    },
                    {
                        label: '状态',
                        prop: 'enableState',
                        slot: 'status'
                    },
                    {
                        label: '角色',
                        prop: 'roleId',
                        slot: 'roleId'
                    },
                    {
                        label: '头像',
                        prop: 'photo',
                        slot: 'companylogo'
                    },
                    {
                        label: '邮箱',
                        prop: 'email',
                        input: true
                    },
                    {
                        label: '用户类型',
                        prop: 'userType',
                        slot: 'userType'
                    },
                    {
                        label: '备注',
                        prop: 'remark',
                        input: true
                    }
                ]
            ],
            formColsEdit: [
                [
                    {
                        label: '用户名',
                        prop: 'username',
                        input: true
                    },
                    {
                        label: '手机号码',
                        prop: 'phone',
                        input: true
                    },
                    {
                        label: '密码',
                        prop: 'password',
                        slot: 'password'
                    },
                    {
                        label: '确认密码',
                        prop: 'passwordOK',
                        slot: 'passwordOK'
                    },
                    {
                        label: '头像',
                        prop: 'photo',
                        slot: 'companylogo'
                    },
                    {
                        label: '邮箱',
                        prop: 'email',
                        input: true
                    },
                    {
                        label: '备注',
                        prop: 'remark',
                        input: true
                    }
                ]
            ],
            formRules: {
                companyOrgId: [this.$valid.selectRequired('所属公司')],
                // deptOrgId: [this.$valid.selectRequired('所属部门')],
                username: [this.$valid.inputRequired('用户名')],
                phone: [this.$valid.patternPhone()],
                password: [{ required: true, validator: validatePass, trigger: 'blur' }],
                passwordOK: [{ required: true, validator: validatePassContrast, trigger: 'blur' }],
                enableState: [this.$valid.inputRequired('状态')],
                userType: [this.$valid.selectRequired('用户类型')]
            },
            formErrors: {}
        };
    },
    watch: {
        'formData.passwordOK'(val) {
            if (this.formData.password !== val) {
            }
        }
    },
    methods: {
        delformphoto() {
            this.formData.photo = '';
            this.$refs.uploaduserlogo.clearFiles();
        },
        getselectAll() {},
        submit() {
            new Promise((resolve) => {
                this.$refs.form.validate(resolve);
            }).then(() => {
                var loading = this.$loading();
                var posturl = '';
                let frData = JSON.parse(JSON.stringify(this.formData));
                if (this.params.todo === 'edit') {
                    posturl = '/user/updateUserById';
                    if (frData.password === '**********' || frData.passwordOK === '**********') {
                        delete frData.password;
                        delete frData.passwordOK;
                    }
                } else {
                    posturl = '/user/addUser';
                }
                this.$http
                    .post(posturl, frData)
                    .then(({ status, data, msg }) => {
                        loading.close();
                        if (0 == status) {
                            if (this.isLoginUser) {
                                this.$store.commit('setcCruUserInfo', this.formData);
                            }
                            this.$message.success(msg);
                            this.params.callback && this.params.callback();
                            this.$emit('close');
                        } else {
                            this.$message.error(msg);
                        }
                    })
                    .catch((err) => {
                        loading.close();
                    });
            });
        },
        handleRemove(file) {
            this.$refs.uploaduserlogo.clearFiles();
        },
        uploadsuccess(response, file, fileList) {
            if (0 === response.status) {
                this.formData.photo = response.data;
            }
        },
        selectedcompanyOrgId(e) {
            this.formData.deptOrgId = '';
            this.formData.deptOrgName = '';
            // 获取 部门树e
            this.$http.postForm('/org/getOrgUserTree', { orgType: 'department', id: e }).then(({ status, data, msg }) => {
                if (status === 0) {
                    // console.log(data);
                    this.organListdepartment = data ? data : [];
                }
            });
        }
    },
    created() {
        this.getselectAll();
        this.formData = JSON.stringify(this.params.data) !== '{}' ? this.params.data : this.formData;

        if (this.params.todo === 'edit') {
            this.$set(this.formData, 'password', '**********');
            this.$set(this.formData, 'passwordOK', '**********');
        }

        this.organList = this.params.organList ? this.params.organList : this.organList;
        this.organListCompany = this.params.organListCompany ? this.params.organListCompany : this.organListCompany;
        this.organListdepartment = this.params.organListdepartment ? this.params.organListdepartment : this.organListdepartment;
        this.allRoleId = this.params.allRoleId ? this.params.allRoleId : this.allRoleId;
        this.allUserType = this.params.allUserType ? this.params.allUserType : this.allUserType;
        this.isLoginUser = this.formData.id == this.$store.getters['getCruUserInfo'].id ? true : false;
        if (this.isLoginUser) {
            this.formCols = this.formColsEdit;
        }
        if (this.allRoleId.length === 0) {
            this.noAllRoleId = true;
        } else {
            // console.log(this.allRoleId);

            this.noIdInAllRoleId = this.allRoleId.every((v, i) => {
                return v.id !== this.formData.roleId;
            });
            // console.log(this.noIdInAllRoleId);
            if (this.noIdInAllRoleId) {
                this.allRoleId.push({
                    id: this.formData.roleId,
                    roleName: this.formData.roleName
                });
            }
        }
    }
};
</script>


<style lang='scss' scoped>
</style>

<style lang="scss">
.mini-upload .el-upload-list--picture-card .el-upload-list__item {
    width: 60px;
    height: 60px;
}
.mini-upload .el-upload--picture-card {
    width: 60px;
    height: 60px;
    line-height: 60px;
    font-size: 14px;
}
.mini-upload .el-upload--picture-card i {
    font-size: 20px;
}
.imgdis-div {
    width: 60px;
    height: 60px;
    position: relative;
}
.imgdis-div i {
    display: none;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.imgdis-div:hover i {
    display: block;
}
</style>

