<template>
    <el-tabs v-loading="loadingEur" elemeur-loading-text="正在读取数据..." type="border-card" v-model="activeName">
        <el-tab-pane label="基本信息" name="基本信息">
            <el-form :model="data" ref="form" :rules="rules" label-position='top'>
                <el-row>
                    <el-col :span='8'>
                        <el-form-item label="登录账号" prop="userId">
                            <el-input v-model="data.userId" maxlength='32'></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span='8'>
                        <el-form-item label="用户名称" prop="userName">
                            <el-input v-model="data.userName" maxlength='32'></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span='8'>
                        <el-form-item label="隶属机构" prop='orgId'>
                            <Selector v-model="data.orgId" :init-label="data.orgName" :clearable="true" label-key="label" value-key="id"
                                      placeholder="隶属组织机构">
                                <SelectorTree tree-key="orgTree" searchField="ORG_NAME" rootLabel="海关"></SelectorTree>
                            </Selector>
                        </el-form-item>
                    </el-col>
                    <el-col :span='8'>
                        <el-form-item label="性别" prop="userGend">
                            <el-radio-group v-model="data.userGend" class="border-bottom">
                                <el-radio label="1">男</el-radio>
                                <el-radio label="0">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span='8'>
                        <el-form-item label="邮箱" prop="userEMail">
                            <el-input v-model="data.userEMail" maxlength='32'></el-input>
                        </el-form-item>
                    </el-col>
                  <el-col :span='8'>
                    <el-form-item label="电话号码" prop="userMobl">
                      <el-input v-model="data.userMobl" maxlength='16'></el-input>
                    </el-form-item>
                  </el-col>

                </el-row>
              <el-row>
                <el-col :span='8'>
                  <el-form-item prop="openEMail" label="邮件通知">
                    <el-radio-group v-model="data.openEMail" class="border-bottom">
                      <el-radio label="1">开启</el-radio>
                      <el-radio label="0">关闭</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span='8'>
                  <el-form-item prop="openMobl" label="短信通知">
                    <el-radio-group v-model="data.openMobl" class="border-bottom">
                      <el-radio label="1">开启</el-radio>
                      <el-radio label="0">关闭</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span='8'>
                  <el-form-item prop="openMobl" label="通话通知">
                    <el-radio-group v-model="data.openSms" class="border-bottom">
                      <el-radio label="1">开启</el-radio>
                      <el-radio label="0">关闭</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
                <el-row>
                  <el-col :span='24'>
                    <el-form-item label="备注" prop="opDesc">
                      <el-input type="textarea" v-model="data.opDesc"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
            </el-form>

            <OptionHistory v-if="data.uuid" :data="data"></OptionHistory>

        </el-tab-pane>
        <el-tab-pane label="角色选择" name="角色选择" v-if="data.orgId && editRole === 'true'">
            <el-tree ref="roleTree" node-key="uuid" :default-checked-keys="data.arrRoles" default-expand-all lazy :load="loadRole"
                     current-node-key="currNode.roleuuid" highlight-current show-checkbox
                     @current-change="currentChangeHandle">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span v-if="data.roleName && data.roleType === '1'">
                        <i class="el-icon-fa el-icon-fa-user-o margin-right-2 font-blue"></i>
                        <span @click="permTreeShow(data.uuid)">{{ data.roleName }}</span>
                    </span>
                    <span v-if="data.roleName && data.roleType === '2'">
                        <i class="el-icon-fa el-icon-fa-folder-open margin-right-2 "/>
                        <span>{{ data.roleName }}</span>
                    </span>
                </span>
            </el-tree>
        </el-tab-pane>

        <el-dialog close-on-press-escape title="角色功能权限" :visible.sync="permTreeDia" width="40%" append-to-body v-draggable>
            <div style="height: 400px;overflow: auto;" v-if="permTreeDia">
                <el-tree v-loading='PtsLoading' ref="permTree" node-key="uuid" :data="permTreeData" highlight-current
                         :props="{label: 'permName', children: 'children'}" :default-expand-all="true"
                         :filter-node-method="filterPerm"></el-tree>
            </div>
        </el-dialog>

    </el-tabs>
</template>
<script>
import UserAPI from "@/api/base/usrm/UserAPI";
import RoleAPI from "@/api/base/usrm/RoleAPI";
import PermApi from "@/api/base/usrm/PermAPI";
import SelectorTree from "@/common/SelectorTree";
import OptionHistory from "@/common/OptionHistory";
import validate from "@/libs/Validate";

let dafaultData = {
    uuid: "",
    userName: "",
    userCode: "",
    userId: "",
    userStat: "",
    userAddr: "",
    userEMail: "",
    userGend: "1",
    userMobl: "",
    openMobl: '0',
    openSms: '0',
    openEMail: '0',
    orgId: "",
    arrRoles: [],
    userType: "",
    userArea: "",
    userCertType: "",
    userCertNo: "",
    opDesc: "",
};
export default {
    components: {SelectorTree, OptionHistory},
    props: {
        uuid: "",
        userType: {type: String, default: ''},
        editRole: {type: String, default: "true"},
    },
    data() {
        return {
            activeName: '基本信息',
            permTreeData: [],
            PtsLoading: false,
            permTreeDia: false,
            options: [
                {value: 5, label: "生效"},
                {value: 6, label: "锁定"},
                {value: 9, label: "注销"}
            ],
            currParentNode: {},
            currNode: {},
            loadingEur: false,
            data: Object.assign({}, dafaultData),
            rules: {
                userId: [
                    {required: true, message: "请输入用户登录账号"},
                    {min: 1, max: 50, message: "长度在 1 到 50 个字符以内", trigger: "blur"}
                ],
                userName: [{required: true, message: "请输入用户名称"}],
                orgId: [{required: true, message: "请选择隶属机构"}],
                graUser: [{required: true, message: "请选择是否为分级管理员"}]
            }
        };
    },
    mounted() {
        this.loadInfo(this.uuid);
        // 读取系统菜单
        PermApi.loadPermTree().then(data => {
            this.permTreeData = data;
        });
        if(this.userType) {
            this.data.userType = this.userType;
        }
    },
    watch: {
        "data.orgId"(val) {
            this.getTreeListen(val);
        },
        'data.openMobl'(nv) {
            if (nv === '1') {
                if (validate.mobile(this.data.userMobl)) {
                    this.data.openMobl = '1';
                } else {
                    this.data.openMobl = '0';
                    this.$message.info('无法开启通话提醒,请检查电话号码格式')
                }
            }
        },
        'data.openSms'(nv) {
            if (nv === '1') {
                if (validate.mobile(this.data.userMobl)) {
                    this.data.openSms = '1';
                } else {
                    this.data.openSms = '0';
                    this.$message.info('无法开启短信提醒,请检查电话号码格式')
                }
            }
        },
        'data.openEMail'(nv) {
            if (nv === '1') {
                if (validate.email(this.data.userEMail)) {
                    this.data.openEMail = '1';
                } else {
                    this.data.openEMail = '0';
                    this.$message.info('无法开启邮件提醒,请检查邮箱格式')
                }
            }
        },
    },
    methods: {
        async permTreeShow(uuid) {
            try {
                this.permTreeDia = true;
                this.PtsLoading = true;
                let resp = await RoleAPI.loadRoleEditInfo(uuid);
                // 在功能页上回显数据
                this.$refs.permTree.setCheckedKeys([]);
                this.$refs.permTree.filter(resp.permIds);
                // resp.permIds.forEach(uuid => {
                //     this.$refs.permTree.setChecked(uuid, true, false);
                // });
            } finally {
                this.PtsLoading = false;
            }
        },
        filterPerm(value, data) {
            return value.findIndex(v => v === data.uuid) > -1;
        },

        // 提交表单数据
        submitForm(data) {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.data.arrRoles = this.$refs.roleTree.getCheckedKeys(); // 将树选择的节点数组放到表单中
                    this.data.userType = this.userType || this.data.userType;
                    this.$emit("submit", this.data);
                } else {
                    return false;
                }
            });
        },
        expandAll() {
            let expandFn = (element, expand) => {
                element.childNodes.forEach(element => {
                    element.expand(() => {
                        expandFn(element);
                    });
                }, this);
            };
            expandFn(this.$refs.roleTree.root);
        },
        // 监听角色树判断
        getTreeListen(orgId) {
            if (this.$refs.roleTree) {
                this.$refs.roleTree.root.loaded = false;
                this.$refs.roleTree.root.expand();
            }
        },
        loadRole(node, resolve) {
            if (node.level === 0) {
                RoleAPI.getCopyRoleTree(this.data.orgId).then(resp => {
                    resp.data && resolve(resp.data);
                });
            } else {
                RoleAPI.getRoleChildren(node.data.uuid).then(resp => {
                    // if (node.data && node.data.roleName && node.data.roleType === '2' && resp.data.length === 0) {
                    //     console.log(node);
                    //     this.$set(node, 'disabled', true);
                    //     console.log(node);
                    //     // node.disabled = true;
                    // }
                    resp.data && resolve(resp.data);
                });
            }
        },
        async loadInfo(uuid) {
            if (uuid) {
                try {
                    this.loadingEur = true;
                    let resp = await UserAPI.getUser(uuid);
                    this.data = Object.assign({}, resp.data.data);
                } finally {
                    this.loadingEur = false;
                }
            } else {
                if (this.data.orgId) {
                    this.getTreeListen(this.data.orgId);
                }
            }
        },

        currentChangeHandle(data, node) {
            console.log(data, node);
        }
    }
};
</script>
