<template>
    <validation-observer ref="newTeam">
    <awsui-layout id="update">
        <awsui-dialog
                v-loading="loading"
                element-loading-text="加载中"
                :title=title
                :visible.sync="dialogVisible"
                :width="width"
                :height=height
                :border=false
                :close-on-click-modal=false
                :before-close="handleClose">
            <!--awsui-dialog标签中的内容都可以自行去控制-->
            <div>
                <el-steps :active="stepActive" align-center>
                    <el-step title="小组信息"></el-step>
                    <el-step title="小组管理员"></el-step>
                    <el-step title="小组权限"></el-step>
                </el-steps>
                <div style="width: 524px;height: 260px;border: 1px solid #e9e9e9;padding: 10px 10px 10px 15px;">
                    <div v-if="stepActive == 1" style="position: relative;padding: 12px 0;">
                        <awsui-form ref="infoForm" :model="baseInfo.form" :rules="baseInfo.rules" label-width="100px" label-position="top">
                            <div v-if="isloaded">
                                <awsui-icon-picker class="icon-team-div" :defaultOptions="iconPickerOptions" :value="{icon:baseInfo.form.teamLogo.code, color:baseInfo.form.teamLogo.color}" @change="changeIcon"></awsui-icon-picker>
                            </div>
                            <awsui-row>
                                <awsui-col :span="18">
                                    <awsui-form-item label="名称" required>
                                        <validation-provider rules="required|teamName_formatCheck|maxLength:36"
                                                             v-slot="{classes,errors}">
                                            <awsui-input placeholder="请输入名称" v-model="baseInfo.form.teamName"></awsui-input>
                                            <div :class="classes">{{ errors[0] }}</div>
                                        </validation-provider>
                                    </awsui-form-item>
                                </awsui-col>
                            </awsui-row>
                            <awsui-row>
                                <awsui-col :span="18">
                                    <awsui-form-item label="工作网络" required>
                                        <validation-provider rules="required|teamName_formatCheck|maxLength:36"
                                                             v-slot="{classes,errors}">
                                            <awsui-select
                                                    filterable
                                                    allow-create
                                                    default-first-option
                                                    placeholder="请选择/输入工作网络"
                                                    v-model="baseInfo.form.category"
                                                    :options="baseInfo.form.categoryOpts"
                                                    @change="changeCategory"
                                            >
                                            </awsui-select>
                                            <div :class="classes">{{ errors[0] }}</div>
                                        </validation-provider>
                                    </awsui-form-item>
                                </awsui-col>
                            </awsui-row>
                            <awsui-row>
                                <awsui-col :span="24">
                                    <awsui-form-item label="简介">
                                        <validation-provider rules="maxLength:255"
                                                             v-slot="{classes,errors}">
                                            <awsui-input v-model="baseInfo.form.teamDesc"  type="textarea" placeholder="请输入简介"></awsui-input>
                                            <div :class="classes">{{ errors[0] }}</div>
                                        </validation-provider>
                                    </awsui-form-item>
                                </awsui-col>
                            </awsui-row>
                        </awsui-form>
                    </div>
                    <div v-if="stepActive == 2" v-loading="adminUserInfo.loading">
                        <div style="height: 270px;overflow:auto;">
                            <el-tree
                                    key="userTree"
                                    ref="userTree"
                                    :props="adminUserInfo.treeProps"
                                    :default-checked-keys="adminUserInfo.value"
                                    :expand-on-click-node=false
                                    :highlight-current=true
                                    empty-text=""
                                    @node-click="openUserNode"
                                    @node-expand="expandUserNode"
                                    @node-collapse="closeUserNode"
                                    @check-change="checkedUserNode"
                                    check-strictly
                                    :show-checkbox=true
                                    node-key="id"
                                    lazy
                                    :load="loadUserNode">
                                <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 v-if="stepActive == 3" v-loading="permInfo.loading">
                        <el-select
                                style="width: 100%;"
                                v-model="permInfo.ws.value"
                                filterable
                                default-first-option
                                size="small"
                                placeholder="请选择资产库"
                                @change="changeWs">
                            <el-option
                                    v-for="item in permInfo.ws.options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                        <div style="height: 238px;overflow: auto;">
                            <el-tree v-if="permInfo.ws.value != ''"
                                     key="repositoryTree"
                                     ref="repositoryTree"
                                     :props="permInfo.tree.props"
                                     :default-checked-keys="permInfo.tree.value"
                                     :expand-on-click-node=false
                                     :highlight-current=true
                                     empty-text=""
                                     @node-click="openNode"
                                     @node-expand="expandNode"
                                     @node-collapse="closeNode"
                                     @check-change="checkedNode"
                                     check-strictly
                                     show-checkbox
                                     node-key="versionId"
                                     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.data.name}}</span>
                                    </span>
                            </el-tree>
                        </div>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <awsui-button v-show="stepActive == 2 || stepActive == 3" class="button-general-color-reverse" @click="function(){stepActive--}">上一步</awsui-button>
                <awsui-button v-show="stepActive == 1 || stepActive == 2" class="button-general-color" type="primary" @click="next">下一步</awsui-button>
                <awsui-button v-show="stepActive == 3" class="button-general-color" type="primary" @click="submit">确定</awsui-button>
            </span>
        </awsui-dialog>
    </awsui-layout>
    </validation-observer>
</template>

<script>
    import awsuiAxios from "../../awsuiAxios"
    export default {
        name: "CooperationUpdate",
        props: {
            visible: {
                type: Boolean,
                default: false
            },
            teamId: {// 小组ID
                type: String,
                default: ''
            },
            title: {// 标题
                type: String,
                default: '新建'
            }
        },
        data() {
            return {
                dialogVisible: false,
                loading: false,
                width: '600px',
                height: '350px',

                addressType: 'user',
                baseInfo: {// 基本信息
                    form: {
                        teamName: '',
                        category: '',
                        categoryOpts: [],
                        teamDesc: '',
                        teamLogo: {
                            color: '',
                            code: ''
                        }
                    },
                    rules: {
                        category: [
                            { required: true, message: '[工作网络]不允许为空', trigger: 'blur' },
                        ],
                        teamName: [
                            { required: true, message: '[名称]不允许为空', trigger: 'blur' },
                        ]
                    }

                },
                adminUserInfo: {// 管理员信息
                    value: [],
                    treeProps: {
                        label: 'name',
                        isLeaf: 'leaf'
                    },
                    loading: false,
                },
                permInfo: {// 权限信息
                    loading: false,
                    ws: {
                        value: '',
                        options: []
                    },
                    tree: {
                        props: {
                            children: 'children',
                            label: 'label',
                            isLeaf: 'leaf'
                        },
                        value: []
                    }
                },
                stepActive: 1,
                isloaded: false,
                iconPickerOptions: {
                    type: "background", //必传，type为"background"时，改变背景颜色，图标颜色固定，type为"icon"时改变图标颜色，背景颜色固定
                    fatherWidth: 70, //非必传，展示区域宽高，type为"background"时代表外层圆形直径，type为"icon"时代表外层正方形宽高，如不传分别默认80px和30px
                    iconFontSize: 52, //非必传，展示区域iconfont字体大小，如不传分别默认30px和16px
                    colorList: ["#dc4f39", "#ff9421", "#009b52", "#3383da", "#009688", "#6600d5", "#0b0e7b", "#666666", "#e6e8ea"], //必传，颜色可选项数组
                    iconfontArray: window.iconfontArray, //必传，iconfont可选项数组
                }
            };
        },
        mounted() {
        },
        methods: {
            changeCategory(val) {// 变更分类
               this.baseInfo.form.category = val;
            },
            initData() {// 初始化查询
                const that = this;
                // axios查询，新建返回分类，资产库列表，修改返回所有信息
                that.loading = true;
                const data = {
                    url:'jd',
                    data:{
                        cmd: 'com.actionsoft.apps.coe.pal.cooperation_team_create_or_update_data_query',
                        teamId: that.teamId
                    }
                };
                awsuiAxios.post(data).then(function (ro) {
                    if (ro.result == 'ok') {
                        const data = ro.data;
                        that.baseInfo.form.teamName = data.teamName;
                        that.baseInfo.form.category = data.category;
                        that.baseInfo.form.categoryOpts = data.categoryArr;
                        that.baseInfo.form.teamDesc = data.teamDesc;
                        that.baseInfo.form.teamLogo = data.teamLogo;
                        that.isloaded = true;
                        that.adminUserInfo.value = data.admins;
                        that.permInfo.ws.value = data.wsId;
                        that.permInfo.ws.options = data.wsArr;
                        that.permInfo.tree.value = data.repositorys;
                    } else {
                        that.$message.error(ro.msg);
                    }
                    that.loading = false;
                }).catch(error=>{
                    console.log(error);
                    that.loading = false;
                })
            },
            next() {
                const that = this;
                if (this.stepActive == 1) {
                    this.$refs.newTeam.validate().then(valid => {
                        if (!valid) {
                            return
                        }
                        this.stepActive++;
                    });
                } else if (this.stepActive == 2) {
                    if (that.adminUserInfo.value.length == 0) {
                        that.$message('未选择任何管理员，保存时默认' + (that.teamId == '' ? '创建' : '修改') + '人为管理员');
                    }
                    this.stepActive++;
                }
            },
            clearAllData() {// 清空数据
                const that = this;
                that.baseInfo.form.teamName = '';
                that.baseInfo.form.category = '';
                that.baseInfo.form.teamDesc = '';
                that.baseInfo.form.teamLogo = {};
                that.adminUserInfo.value = [];
                that.permInfo.ws.value = '';
                that.permInfo.ws.options = [];
                that.permInfo.tree.value = [];
                that.stepActive = 1;
                that.isloaded = false;
            },
            handleClose(done) {
                this.closeDlalog('cancel');
                done();
            },
            cancel() {
                this.closeDlalog('cancel');
            },
            submit() {
                const wsId = this.permInfo.ws.value;
                if (wsId == '') {
                    this.$message({message: '请先创建资产库再进行小组创建',type: 'warning'});
                    return;
                }
                this.closeDlalog('save');
            },
            closeDlalog(type) {// 取消/确定之后的关闭
                const that = this;
                if (type == 'save') {
                    const teamId = that.teamId;
                    const teamName = that.baseInfo.form.teamName;
                    const category = that.baseInfo.form.category;
                    const teamDesc = that.baseInfo.form.teamDesc;
                    const teamLogo = that.baseInfo.form.teamLogo;
                    const admins = that.adminUserInfo.value;
                    const wsId = that.permInfo.ws.value;
                    const repositorys = that.permInfo.tree.value;
                    const data = {
                        teamId: teamId,
                        teamName: teamName,
                        category: category,
                        teamDesc: teamDesc,
                        teamLogo: teamLogo,
                        admins: admins,
                        wsId: wsId,
                        repositorys: repositorys
                    };
                    // 保存
                    that.loading = true;
                    const params = {
                        url:'jd',
                        data:{
                            cmd: 'com.actionsoft.apps.coe.pal.cooperation_team_create_or_update_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.error(ro.msg);
                        }

                    }).catch(error=>{
                        console.log(error);
                        that.loading = false;
                    })
                } else {
                    that.$emit('cancel');
                    that.dialogVisible = false;
                    // 清空所有数据
                    that.clearAllData();
                }
            },
            /**********设置管理员*************/
            openUserNode(obj, node, tree) {// 打开一只模型文件

            },
            loadUserNode(node, resolve) {// `动态`加载
                const that = this;
                that.adminUserInfo.loading = true;
                const data = {
                  url:'jd',
                  data:{
                    cmd: 'com.actionsoft.apps.coe.pal_bpm_org_address_component_subjson',
                    addressType: that.addressType,
                    pid: '',
                    highSecurityFilter: ''
                  }
                };
                if (node.level === 0) {
                    // 获取根目录
                    data.data.parentType = '';
                } else {
                    // 获取其他目录
                    data.data.pid = node.data.id;
                    data.data.parentType = node.data.type;
                }
                // 查询数据
                awsuiAxios.post(data).then(function (ro) {
                    // 设置是否可选中
                    const isDept = that.addressType.indexOf('department') > -1;
                    const isUser = that.addressType.indexOf('user') > -1;
                    const isRole = that.addressType.indexOf('role') > -1;
                    for (let i = 0; i < ro.data.length; i++) {
                        const curr = ro.data[i];
                        if (curr.type == 'company') {
                            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 (curr.type == 'user') {
                                curr.leaf = true;
                            }
                        }
                    }
                    resolve(ro.data);
                    that.adminUserInfo.loading = false;
                    if (node.level == 0 && ro.data.length > 0) {
                        const tree = that.$refs.userTree;
                        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);
                })
            },
            expandUserNode(obj, node, tree) {// 展开节点

            },
            closeUserNode(obj, node, tree) {// 关闭时清空，下次展开重新请求动态加载
                node.childNodes = [];
                node.loaded = false;
            },
            checkedUserNode(data, checked, subChecked) {// 节点选中事件
                // 获取所有子节点
                const that = this;
                const currUserId = data.id;
                if (checked) {// 选中
                    const userIds = that.adminUserInfo.value;
                    if (userIds.indexOf(currUserId) == -1) {
                        userIds.push(currUserId);
                    }
                } else {// 取消选中
                    const userIds = that.adminUserInfo.value;
                    const tempArr = [];
                    for (let i = 0; i < userIds.length; i++) {
                        if (userIds[i] != currUserId) {
                            tempArr.push(userIds[i]);
                        }
                    }
                    that.adminUserInfo.value = tempArr;
                }
            },
            /************资产库权限设置**************/
            changeWs(targetWsId) {// 变更资产库
                const that = this;
                that.permInfo.ws.value = '';
                that.permInfo.tree.value;
                that.$nextTick(function () {
                    that.permInfo.ws.value = targetWsId;
                })
            },
            openNode(obj, node, tree) {// 点击数

            },
            loadNode(node, resolve) {
                const that = this;
                that.permInfo.loading = true;
                const data = {
                    url:'jd',
                    data:{
                    }
                };
                data.data.wsId = that.permInfo.ws.value;
                data.data.teamId = '';
                data.data.cmd = 'com.actionsoft.apps.coe.pal_processlevel_tree_data';
                if (node.level === 0) {
                    // 获取根目录
                    data.data.pid = '';
                } else {
                    // 获取其他目录
                    data.data.pid = node.data.id;
                }
                // 查询数据
                awsuiAxios.post(data).then(function (ro) {
                    // 根节点设置只读
                    for (let i = 0; i < ro.data.length; i++) {
                        if (ro.data[i].id.length < 36) {
                            ro.data[i].disabled = true;
                        }
                    }
                    resolve(ro.data);
                    that.permInfo.loading = false;
                    if (node.level == 0 && ro.data.length > 0) {
                        const tree = that.$refs.repositoryTree;
                        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);
                })
            },
            expandNode(obj, node, tree) {// 展开节点

            },
            closeNode(obj, node, tree) {// 关闭时清空，下次展开重新请求动态加载
                node.childNodes = [];
                node.loaded = false;
            },
            checkedNode(data, checked, subChecked) {// 节点选中事件
                // 获取所有子节点
                const that = this;
                const params = {
                    url:'jd',
                    data:{
                        cmd: 'com.actionsoft.apps.coe.pal_publish_publishgroup_repository_data_query',
                        wsId: that.permInfo.ws.value,
                        pid: data.id,
                    }
                };
                awsuiAxios.post(params).then(function (ro) {
                    const childVerIds = ro.data;
                    const currVerId = data.versionId;
                    if (checked) {// 选中
                        const checkedVerIds = that.permInfo.tree.value;
                        if (checkedVerIds.indexOf(currVerId) == -1) {
                            checkedVerIds.push(currVerId);
                        }
                        for (let i = 0; i < childVerIds.length; i++) {
                            if (checkedVerIds.indexOf(childVerIds[i]) == -1) {
                                checkedVerIds.push(childVerIds[i]);
                            }
                        }
                        that.$refs.repositoryTree.setCheckedKeys(checkedVerIds);
                    } else {// 取消选中
                        const checkedVerIds = that.permInfo.tree.value;
                        const tempArr = [];
                        for (let i = 0; i < checkedVerIds.length; i++) {
                            if (checkedVerIds[i] != currVerId && childVerIds.indexOf(checkedVerIds[i]) == -1) {
                                tempArr.push(checkedVerIds[i]);
                            }
                        }
                        that.permInfo.tree.value = tempArr;
                        that.$refs.repositoryTree.setCheckedKeys([]);
                    }
                }).catch(error=>{
                    console.log(error);
                })
            },
            changeIcon(icon) {
                this.baseInfo.form.teamLogo.code = icon.icon;
                this.baseInfo.form.teamLogo.color = icon.color;
            }
        },
        watch: {
            visible(val) {
                this.dialogVisible = val;
                if (val) {// 打开
                    this.initData();
                } else {// 关闭
                }
            }
        }
    }
</script>

<style scoped>
    #update >>> .el-step__title {
        font-size: 12px;
    }
    #update >>> .awsui-icon-picker-box1 {
        border-radius: 15%;
    }
    .icon-team-div {
        height: 70px;
        width: 70px;
        line-height: 70px;
        display: inline-block;
        position:absolute;
        z-index: 2;
        right: 30px;
        top: 50px;
    }
    .icon-team {
        color: white;
        font-size: 52px;
    }
</style>