<template>
    <el-dialog
            title="生成端到端流程图"
            height="350px"
            width="800px"
            :visible.sync="dialogVisible"
            :border="false">
        <div class="sub-process-dialog-content" style="margin: 25px 25px;">
            <el-form label-width="95px" label-position="left">
                <el-form-item label="位置" required>
                    <el-input disabled v-model="subProcessForm.position.label" size="small">
                        <template slot="append">
                            <el-popover ref="positionPopover" placement="bottom" trigger="click" width="600" @show="positionPopoverShowEvent" @hide="positionPopoverHideEvent">
                                <div style="height: 200px; overflow: auto;">
                                    <el-tree
                                            v-if="subProcessForm.position.showTree"
                                            @node-collapse="closePositionNode"
                                            @node-click="positionTreeNodeClickEvent"
                                            ref="positionTree"
                                            node-key="id"
                                            lazy
                                            :highlight-current="true"
                                            :expand-on-click-node="false"
                                            :load="loadPositionTreeNode"
                                            :props="treeProps">
                                    <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 :style="{'font-weight': data.id.length < 36 ? '600' : ''}">{{node.label}}</span>
                                    </span>
                                    </el-tree>
                                </div>
                                <span slot="reference" style="cursor: pointer;"><i class="awsui-iconfont">&#xe632;</i></span>
                            </el-popover>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="子流程选择" required>
                    <el-popover ref="subProcessPopover" placement="bottom" trigger="click" width="600" @show="processPopoverShowEvent" @hide="processPopoverHideEvent">
                        <div class="sub-process-tree-box" style="height: 300px; overflow: auto;">
                            <el-tree
                                    v-if="subProcessForm.showProcessTree"
                                    ref="subProcessModelTree"
                                    @node-collapse="closeSubProcessNode"
                                    node-key="id"
                                    lazy
                                    show-checkbox
                                    :load="loadModelTreeNode"
                                    @check="modeTreeNodeCheck"
                                    :default-checked-keys="subProcessForm.defaultProcessCheckedKeys"
                                    :props="treeProps">
                                <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 :style="{'font-weight': data.id.length < 36 ? '600' : ''}">{{node.label}}</span>
                                </span>
                            </el-tree>
                        </div>
                        <div slot="reference" style="width: 100%;height: 65px;border: 1px solid #dcdfe6;cursor: pointer;display: inline-flex;align-items: center;flex-wrap: wrap;overflow: auto;">
                            <div>
                                <el-tag style="margin: 5px;"  v-for="tag in subProcessForm.processTags" :key="tag.value">{{ tag.label }}</el-tag>
                            </div>
                        </div>
                    </el-popover>
                </el-form-item>
                <el-form-item label="排布方式" required>
                    <el-radio-group v-model="subProcessForm.direction">
                        <el-radio v-for="item in subProcessForm.directionOpts" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="模型名称" required>
                    <el-input v-model="subProcessForm.modelName" size="small"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
            <awsui-button type="primary" @click="generateSubProcessModel">确定</awsui-button>
            <awsui-button @click="close">取 消</awsui-button>
        </div>
    </el-dialog>
</template>

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

    export default {
        name: "SubProcess",
        props: {
            visible: {
                type: Boolean,
                default: false
            },
            defaultTags: {
                type: Array,
                default: null
            },
        },
        data(){
            return {
                dialogVisible: false,
                subProcessForm: {
                    position: {
                        path: '',
                        label: '',
                        showTree: false,
                        locationId: '',
                    },
                    processList: [],
                    processTags: [],
                    defaultProcessCheckedKeys: [],
                    showProcessTree: false,
                    direction: 'vertically',
                    directionOpts: [{value: 'vertically', label: '纵向排布'},{value: 'horizontal', label: '横向排布'}],
                    modelName: '',
                    popoverVisible: false
                },
                treeProps: {
                    label: 'name',
                    isLeaf: 'leaf'
                },
            }
        },
        methods: {
            initData(){
                // 获取位置根目录
                const param = {
                    url: 'jd',
                    data: {
                        cmd: 'com.actionsoft.apps.coe.method.process.subprocess.init_data',
                    }
                }
                awsuiAxios.post(param)
                    .then(ro => {
                        if (ro.result === 'ok') {
                            // console.log('initData', ro);
                            this.subProcessForm.position.label = ro.data.dirRootName;
                            this.subProcessForm.position.path = ro.data.dirRootPath;
                        }else if (ro.result === 'error') {
                            this.$message({type: 'error', message: ro.msg});
                            this.$emit('getResult');
                        }
                    })
                    .catch(err => {
                        console.log(err);
                    });
            },
            close(){
                this.$emit('getResult');
                this.clearData();
                // 子流程树节点所选清空
                if (this.$refs.subProcessModelTree) {
                    this.$refs.subProcessModelTree.setCheckedKeys([]);
                }
            },
            closeAdapter(done) {
                this.close();
                done();
            },
            clearData(){
                this.dialogVisible = false;
                this.subProcessForm.processTags = [];
                this.subProcessForm.processList = [];
                this.subProcessForm.modelName = '';
                this.subProcessForm.popoverVisible = false;
                this.subProcessForm.position.label = '';
                this.subProcessForm.position.showTree = false;
                this.subProcessForm.position.locationId = '';
                this.subProcessForm.defaultProcessCheckedKeys = [];
                this.subProcessForm.showProcessTree = false;
            },
            // 生成端到端总图
            generateSubProcessModel(){
                console.log('执行参数',this.subProcessForm);
                const param = {
                    url: 'jd',
                    data: {
                      cmd: 'com.actionsoft.apps.coe.method.process.subprocess.generator_end_to_end_model',
                      processIdJsonArr: JSON.stringify(this.subProcessForm.processList),
                      locationId: this.subProcessForm.position.locationId,
                      direction: this.subProcessForm.direction,
                      modelName: this.subProcessForm.modelName
                    }
                }
                awsuiAxios.post(param)
                  .then(ro => {
                    console.log(ro);
                    if (ro.result == 'ok'){
                      this.close();
                      this.$message({type: 'success', message: '第一个阶段图形节点分布测试成功'});
                    }else if (ro.result === 'error'){
                      this.$message({type: 'error', message: '发生了什么'});
                    }
                  })
                  .catch(err => {
                    console.log(err);
                  });
            },
            // 加载子流程节点树
            loadModelTreeNode(node, resolve){
                const that = this;
                const param = {
                    url: 'jd',
                    data: {
                        cmd: 'com.actionsoft.apps.coe.method.process.subprocess.find_tree_node',
                        wsId: that.$store.getters.getWsIdFn,
                        teamId: that.$store.getters.getTeamIdFn,
                        createUsers: JSON.stringify(that.$store.getters.getCreateUsers),
                        orgIds: JSON.stringify(that.$store.getters.getOrgIds),
                        methodIds: JSON.stringify(that.$store.getters.getMethodIds),
                        pid: ''
                    }
                };
                if (node.level !== 0){
                    param.data.pid = node.data.id;
                }
                awsuiAxios.post(param)
                    .then(ro => {
                        if (ro.result === 'ok') {
                            resolve(ro.data);
                            const tree = that.$refs.subProcessModelTree;
                            if (ro.data.length){
                                tree.getNode(ro.data[0].id).expand();
                                setTimeout(() => {
                                    let childNode = tree.getNode(ro.data[0].id).childNodes[0];
                                    if (childNode != null) {
                                        childNode.expand();
                                    }
                                }, 500);
                            }
                        }
                    })
                    .catch(err => {
                        console.log(err);
                    });
            },
            modeTreeNodeCheck(data, obj){
                const that = this;
                if (!obj.checkedKeys.length) {
                    // 当前树没有选中的节点 对应的tag数组清空
                    that.subProcessForm.processTags = [];
                    return;
                }
                // 调接口查询当前选中节点的所有子节点
                const param = {
                    url: 'jd',
                    data: {
                        cmd: 'com.actionsoft.apps.coe.method.process.subprocess.find_tree_child_node_all',
                        nodeKeyJsonArr: JSON.stringify(obj.checkedKeys)
                    }
                };
                awsuiAxios.post(param)
                    .then(ro => {
                        if (ro.result === 'ok') {
                            // console.log('节点选中接口',ro.data);
                            that.subProcessForm.processTags = ro.data;
                            that.subProcessForm.processTags.forEach(tag => {
                                that.subProcessForm.processList.push(tag.value);
                            });
                        }
                    })
                    .catch(err => {
                        that.$message({type: 'error', message: err.msg});
                    });
            },
            // 关闭时清空，下次展开重新请求动态加载
            closeSubProcessNode(obj, node, tree) {
                node.childNodes = [];
                node.loaded = false;
            },
            // 加载指定位置节点树
            loadPositionTreeNode(node, resolve){
                const that = this;
                const param = {
                    url: 'jd',
                    data: {
                        cmd: 'com.actionsoft.apps.coe.method.process.subprocess.construct_position_tree',
                        wsId: that.$store.getters.getWsIdFn,
                        teamId: that.$store.getters.getTeamIdFn,
                        pid: '',
                    }
                };
                if (node.level !== 0){
                    param.data.pid = node.data.id;
                }
                awsuiAxios.post(param)
                    .then(ro => {
                        if (ro.result === 'ok') {
                            resolve(ro.data);
                            const tree = that.$refs.positionTree;
                            if (ro.data.length){
                                tree.getNode(ro.data[0].id).expand();
                                setTimeout(() => {
                                    let childNode = tree.getNode(ro.data[0].id).childNodes[0];
                                    if (childNode != null) {
                                        childNode.expand();
                                    }
                                }, 500);
                            }
                        }
                    })
                    .catch(err => {
                        console.log(err);
                    });
            },
            closePositionNode(obj, node, tree){
                node.childNodes = [];
                node.loaded = false;
            },
            positionTreeNodeClickEvent(data, node, obj){
                if (node.data.id === this.subProcessForm.position.path.split("/")[0]){
                    return;
                }
                let tempNode = null;
                let pathIds = [];
                let pathNames = [];
                for (let i = 0; i < node.level; i++) {
                    if (tempNode == null){
                        pathIds.push(node.data.id);
                        pathNames.push(node.data.name);
                        tempNode = node;
                    }else {
                        tempNode = tempNode.parent;
                        pathIds.push(tempNode.data.id);
                        pathNames.push(tempNode.data.name);
                    }
                }
                this.subProcessForm.position.label = pathNames.reverse().join("/");
                this.subProcessForm.position.path = pathIds.reverse().join("/");

                this.subProcessForm.position.locationId = node.data.id;

                this.$refs.positionPopover.doClose();
            },
            processPopoverShowEvent(){
                this.subProcessForm.showProcessTree = true;
            },
            processPopoverHideEvent(){
                this.subProcessForm.showProcessTree = false;
            },
            positionPopoverShowEvent(){
                this.subProcessForm.position.showTree = true;
            },
            positionPopoverHideEvent(){
                this.subProcessForm.position.showTree = false;
            }
        },
        watch: {
            visible(val) {
                this.dialogVisible = val;
                if (val) {
                    // 从更多icon进来则将上一界面选中的文件默认添加
                    if (this.defaultTags != null) {
                        this.subProcessForm.processTags = [...this.defaultTags];
                        this.defaultTags.forEach(tag => {
                            this.subProcessForm.defaultProcessCheckedKeys.push(tag.value);
                        });
                    }
                    this.initData();
                }
            }
        }
    }
</script>

<style scoped>
    /deep/ .el-dialog__body {
        padding: 10px 20px;
    }
</style>