<template>
    <awsui-layout>
        <awsui-main>
            <awsui-dialog
                    v-loading="loading"
                    element-loading-text="加载中"
                    :border=false
                    :title=title
                    :visible.sync="dialogVisible"
                    width="400px"
                    :close-on-click-modal=false
                    :before-close="handleClose">
                <!--awsui-dialog标签中的内容都可以自行去控制-->
                <div class="text-general-color">
                    <awsui-form ref="form" :model="form" label-position="top" style="padding:0 5px">
                        <div class="awsui-form-item">
                            <label class="awsui-form-item__label">成员</label>
                            <div v-if="isOlderVersion" class="awsui-form-item__content">
                                <awsui-select filterable v-model="form.userArr" :options="form.userOpts" multiple size="large" key="user"></awsui-select>
                            </div>
                            <div v-else>
                              <div v-loading="userLoading" element-loading-text="拼命加载中">
                                <div style="height: 200px;overflow: auto;border: 1px solid #f2f2f2;">
                                  <div class="tree">
                                    <el-tree
                                      ref="tree"
                                      :props="treeProps"
                                      :show-checkbox="multiple"
                                      :expand-on-click-node=false
                                      :check-strictly=true
                                      :highlight-current=true
                                      @node-click="openNode"
                                      @node-expand="expandNode"
                                      @node-collapse="closeNode"
                                      node-key="id"
                                      lazy
                                      :load="loadNode">
                                        <span slot-scope="{node, data}">
                                          <i class="awsui-iconfont tree-content-icon tree-content-icon-padding" :style="{'color': node.data.icon.color}" v-html="node.data.icon.icon"></i>
                                          <span>{{node.label}}</span>
                                        </span>
                                    </el-tree>
                                  </div>
                                </div>
                              </div>
                            </div>
                        </div>
                        <div class="awsui-form-item">
                            <label class="awsui-form-item__label">角色</label>
                            <label class="awsui-form-item__label text-linker-color" style="cursor: pointer;" @click="createRole">无满足角色，去添加</label>
                            <div class="awsui-form-item__content">
                                <awsui-select filterable v-model="form.roleId" :options="form.roleOpts" size="large" key="role"></awsui-select>
                            </div>
                        </div>
                    </awsui-form>
                </div>
                <span slot="footer" class="dialog-footer">
                    <awsui-button :disabled="buttonDisabled" class="button-general-color" type="primary" @click="submit">确定</awsui-button>
                    <awsui-button @click="cancel">取消</awsui-button>
                </span>
            </awsui-dialog>
            <role-update
                    ref="roleUpdate"
                    :visible.sync="roleUpdate.visible"
                    :teamId="teamId"
                    :roleId="roleUpdate.roleId"
                    v-on:cancel="roleUpdate.visible = false"
                    v-on:getResult="updateRoleDone"/>
        </awsui-main>
    </awsui-layout>
</template>

<script>
    import awsuiAxios from "../../awsuiAxios";
    import RoleUpdate from "../role/RoleUpdate";

    export default {
        name: "MemberAdd",
        components: {RoleUpdate},
        props: {
            visible: {
                type: Boolean,
                default: false
            },
            teamId: {// 小组ID
                type: String,
                default: ''
            },
            title: {// 标题
                type: String,
                default: ''
            }
        },
        data() {
            return {
                dialogVisible: false,
                loading: false,
                buttonDisabled: false,
                form: {
                    userArr: [],
                    userOpts: [],
                    roleId: '',
                    roleOpts: []
                },
                roleUpdate: {
                    visible: false,
                    roleId: '',
                },
                isOlderVersion: true,
                userLoading: false,
                treeProps: {
                  label: 'name',
                  isLeaf: 'leaf'
                },
                multiple:true,
                addressType: 'user',
                highSecurityFilter: 'sysAdmin,auditor' ,// 例如值为sysAdmin,auditor，则开启三员之后该地址簿不显示系统管理员和安全审计员
                pid: '',

            }
        },
        methods: {
            initData() {
                const that = this;
                that.loading = true;
                const params = {
                    url:'jd',
                    data:{
                        cmd: 'com.actionsoft.apps.coe.pal.cooperation_member_add_data_query',
                        teamId: that.teamId
                    }
                };
                // 查询数据
                awsuiAxios.post(params).then(function (ro) {
                    if (ro.result == 'ok') {
                        const data = ro.data;
                        that.form.roleOpts = data.roleOpts;
                        that.form.userOpts = data.userOpts;
                        that.isOlderVersion = data.isOlderVersion;
                    } else {
                        that.$message.error(ro.msg);
                    }
                    that.loading = false;
                }).catch(error=>{
                    console.log(error);
                    that.loading = false;
                })
            },
            clearAllData() {// 清空数据
                const that = this;
                that.form.userArr = [];
                that.form.userOpts = [];
                that.form.roleId = '';
                that.form.roleOpts = [];
                that.buttonDisabled = false;
                if (!that.isOlderVersion){
                  this.$refs.tree.setCheckedNodes([]);
                }
            },
            handleClose(done) {
                this.closeDlalog('cancel');
                done();
            },
            cancel() {
                this.closeDlalog('cancel');
            },
            submit() {
                this.closeDlalog('save');
            },
            closeDlalog(type) {// 取消/确定之后的关闭
                const that = this;
                if (type == 'save') {
                    if (!that.isOlderVersion){
                      let nodes = this.$refs.tree.getCheckedNodes();
                      nodes.forEach((item)=>{
                        if (!that.form.userArr.includes(item.id)){
                          that.form.userArr.push(item.id);
                        }
                      })
                    }
                    if (that.form.userArr.length == 0) {
                        that.$message.error('请选择[成员]');
                        return;
                    }
                    if (that.form.roleId == '') {
                        that.$message.error('请选择[角色]');
                        return;
                    }
                    const data = {
                        teamId: that.teamId,
                        userArr: that.form.userArr,
                        roleId: that.form.roleId
                    };
                    // 保存
                    that.loading = true;
                    that.buttonDisabled = true;
                    const params = {
                        url:'jd',
                        data:{
                            cmd: 'com.actionsoft.apps.coe.pal.cooperation_member_add_data_save',
                            data: JSON.stringify(data)
                        }
                    };
                    awsuiAxios.post(params).then(function (ro) {
                        that.loading = false;
                        if (ro.result == 'ok') {
                            that.$message({
                                message: '添加成功',
                                type: 'success'
                            });
                            that.$emit('getResult', 'ok');
                            that.dialogVisible = false;
                            // 清空所有数据
                            that.clearAllData();
                        } else {
                            that.$message({
                                message: ro.msg,
                                type: 'warning'
                            });
                          that.$emit('cancel');
                          that.dialogVisible = false;
                          // 清空所有数据
                          that.clearAllData();
                        }
                    }).catch(error=>{
                        console.log(error);
                        that.loading = false;
                        that.buttonDisabled = false;
                    })
                } else {
                    that.$emit('cancel');
                    that.dialogVisible = false;
                    // 清空所有数据
                    that.clearAllData();
                }
            },
            createRole() {// 创建角色
                this.roleUpdate.roleId = '';
                this.roleUpdate.visible = true;
            },
            updateRoleDone(result) {// 角色修改完成
                this.roleUpdate.visible = false;
                if (result == 'ok') {
                    this.initData();
                }
            },
            openNode(obj, node, tree) {// 打开一只模型文件

            },
            expandNode(obj, node, tree) {// 展开节点

            },
            closeNode(obj, node, tree) {// 关闭时清空，下次展开重新请求动态加载
              node.childNodes = [];
              node.loaded = false;
            },
            loadNode(node, resolve) {// `动态`加载
              const that = this;
              that.userLoading = true;
              const data = {
                url:'jd',
                data:{
                  cmd: 'com.actionsoft.apps.coe.pal_bpm_org_address_component_subjson',
                  addressType: that.addressType,
                  pid: '',
                  highSecurityFilter: that.highSecurityFilter
                }
              };
              if (node.level === 0) {
                // 获取根目录
                data.data.pid = that.pid;
                data.data.parentType = '';
              } else {
                // 获取其他目录
                data.data.pid = node.data.id;
                data.data.parentType = node.data.type;
              }
              // 查询数据
              awsuiAxios.post(data).then(function (ro) {
                // 设置是否可选中
                if (that.multiple) {// 多选
                  const isDept = that.addressType.indexOf('department') > -1;
                  const isUser = that.addressType.indexOf('user') > -1;
                  const isRole = that.addressType.indexOf('role') > -1;
                  const isPosition = that.addressType.indexOf('position') > -1;
                  for (let i = 0; i < ro.data.length; i++) {
                    const curr = ro.data[i];
                    if (curr.type == 'company' || curr.type == 'roleRoot' || curr.type == 'roleGroup' || curr.type == 'positionRoot' || curr.type == 'positionGroup') {
                      curr.disabled = true;
                    } else {
                      if (isDept && curr.type == 'department') curr.disabled = false;
                      if (!isDept && curr.type == 'department') curr.disabled = true;
                      if (isUser && curr.type == 'user') curr.disabled = false;
                      if (!isUser && curr.type == 'user') curr.disabled = true;
                      if (isRole && curr.type == 'role') curr.disabled = false;
                      if (!isRole && curr.type == 'role') curr.disabled = true;
                      if (isPosition && curr.type == 'position') curr.disabled = false;
                      if (!isPosition && curr.type == 'position') curr.disabled = true;
                    }
                  }
                }
                resolve(ro.data);
                that.userLoading = false;
                if (node.level == 0 && ro.data.length > 0) {
                  const tree = that.$refs.tree;
                  tree.getNode(ro.data[0].id).expand();
                  setTimeout(function(){
                    const childNode = tree.getNode(ro.data[0].id).childNodes[0];
                    if (childNode != null) {
                      childNode.expand();
                    }
                  }, 500);
                }
              }).catch(error=>{
                console.log(error);
              })
            },
        },
        watch: {
            visible(val) {
                this.dialogVisible = val;
                if (val) {// 打开
                    this.initData();
                } else {// 关闭
                }
            }
        }
    }
</script>

<style scoped>

</style>