<template>
    <el-dialog
            v-loading="loading"
            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">
                        <div class="sub-process-tree-box" style="height: 300px; overflow: auto;">
                          <el-input
                              size="small"
                              placeholder="输入关键字进行过滤"
                              v-model="processTreeNodeFilterText">
                          </el-input>
                            <el-tree
                                    ref="subProcessModelTree"
                                    @node-collapse="closeSubProcessNode"
                                    node-key="id"
                                    lazy
                                    show-checkbox
                                    :load="loadModelTreeNode"
                                    @check="modeTreeNodeCheck"
                                    :default-checked-keys="subProcessForm.defaultProcessCheckedKeys"
                                    :filter-node-method="filterProcessTreeNode"
                                    :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.level">
                        <el-radio v-for="item in subProcessForm.levelOpts" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
                    </el-radio-group>
                </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="submit">确定</awsui-button>
            <awsui-button @click="close">取 消</awsui-button>
        </div>
        <!-- 关于选择的子流程是否是独立的校验提示 -->
        <el-dialog
                v-loading="loadingPre"
                :visible.sync="generatePreHandleData.independentDlgVisible" width="700px"
                :show-close="false"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                append-to-body>
            <div>
                <div v-if="generatePreHandleData.independentNodeVos.length">
                    <div style="width: 100%;height: 125px;display: inline-flex;flex-wrap: wrap;overflow: auto; border: 1px solid #efefef;">
                        <el-tag style="margin: 5px;" v-for="tag in generatePreHandleData.independentNodeVos" :key="tag.id">{{ tag.name }}</el-tag>
                    </div>
                    <p style="margin: 10px 0;text-indent: 2em;">
                        <span style="color: red;">*</span>
                        以上的子流程，既不存在上游流程也不存在下游流程，同时也不是其它流程的上游流程或下游流程。
                        因此，如果想继续生成总图并同时保留以上子流程的话，请取消本次操作，并为以上子流程补充上游流程或下游流程。 如果想继续生成总图且不想保留以上子流程的话，请选择跳过。
                    </p>
                </div>
                <div v-if="generatePreHandleData.leadAndRearNotInRange.length">
                    <div style="width: 100%;height: 125px;display: inline-flex;flex-wrap: wrap;overflow: auto; border: 1px solid #efefef;">
                        <el-tag style="margin: 5px;" v-for="tag in generatePreHandleData.leadAndRearNotInRange" :key="tag.id">
                          <span style="color: #e65e20;">{{ tag.name }}</span><span>为（{{ tag.relationName }}）的{{ tag.typeName }}</span>
                        </el-tag>
                    </div>
                    <p style="margin: 10px 0;text-indent: 2em;">
                        <span style="color: red;">*</span>
                        以上标红的子流程，是括号中流程的上游流程或者下游流程，但是其不在勾选的子流程范围之内。
                        因此，如果想继续生成总图并想在生成的总图中有所体现的话，请取消本次操作，并勾选以上子流程。
                        如果想继续生成总图的话，请选择跳过，但是在生成的总图中并不会体现。
                    </p>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <awsui-button type="primary" @click="jumpOverIndependent">跳过</awsui-button>
                <awsui-button @click="closeGeneratePreDlg">取 消</awsui-button>
            </div>
        </el-dialog>
    </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,
                    level: 'process', // 流程级别 process 活动级别 activity
                    levelOpts: [{value: 'process', label: '流程级别'},{value: 'activity', label: '活动级别'}]
                },
                treeProps: {
                    label: 'name',
                    isLeaf: 'leaf'
                },
                processTreeNodeFilterText: '',
                generatePreHandleData: {
                    independentDlgVisible: false,
                    independentNodeVos: [],
                    leadAndRearNotInRange: []
                },
                loading: false,
                loadingPre: false
            }
        },
        methods: {
            filterProcessTreeNode(value, data) {
              if (!value) return true;
              return data.name.indexOf(value) !== -1;
            },
            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;
                            this.subProcessForm.position.locationId = ro.data.locationId;
                        }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([]);
                }
            },
            closeGeneratePreDlg(){
                this.generatePreHandleData.independentDlgVisible = false;
                this.generatePreHandleData.independentNodeVos = [];
                this.generatePreHandleData.leadAndRearNotInRange = [];
            },
            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;
            },
            submit(){
                this.generatePreHandle();
            },
            // 跳过
            jumpOverIndependent(){
                let independentNodeArr = [];
                this.generatePreHandleData.independentNodeVos.forEach(node => {
                  independentNodeArr.push(node.id);
                });
                this.generateSubProcessModel(independentNodeArr);
            },
            // 预处理 检验是否有独立的子流程
            generatePreHandle(){
                this.loadingPre = true;
                const param = {
                    url: 'jd',
                    data: {
                        cmd: 'com.actionsoft.apps.coe.method.process.subprocess.independent_node_pre_handle',
                        processIdJsonArr: JSON.stringify(this.subProcessForm.processList),
                    }
                }
                awsuiAxios.post(param)
                    .then(ro => {
                        if (ro.result == 'ok'){
                            this.loadingPre = false;
                            if (ro.data.independentNodeVos.length || ro.data.leadAndRearNotInRange.length){
                                this.generatePreHandleData.independentDlgVisible = true;
                                this.generatePreHandleData.independentNodeVos = ro.data.independentNodeVos;
                                this.generatePreHandleData.leadAndRearNotInRange = ro.data.leadAndRearNotInRange;
                            }else {
                                this.generateSubProcessModel([]);
                            }
                        }else if (ro.result == 'error'){
                            this.$message({type: 'error', message: ro.msg});
                        }
                    })
                    .catch(err => {
                        console.log(err)
                    });
            },
            // 生成端到端总图
            generateSubProcessModel(independentNodeArr){
                // console.log('执行参数',this.subProcessForm);
                if (!this.subProcessForm.processList.length){
                    this.$message({type: 'warning', message: '请选择子流程'});
                    return;
                }
                if (!this.subProcessForm.modelName){
                    this.$message({type: 'warning', message: '请填写模型名称'});
                    return;
                }
                this.loading = true;
                this.generatePreHandleData.independentDlgVisible = false;
                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,
                      level: this.subProcessForm.level,
                      modelName: this.subProcessForm.modelName,
                      excludeProcessIdArr: JSON.stringify(independentNodeArr)
                    }
                }
                awsuiAxios.post(param)
                  .then(ro => {
                    // console.log(ro);
                    if (ro.result == 'ok'){
                      this.close();
                      this.closeGeneratePreDlg();
                      this.loading = false;
                      this.$message({type: 'success', message: '总图生成成功'});
                    }else if (ro.result === 'error'){
                      this.$message({type: 'error', message: ro.msg});
                    }
                  })
                  .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 = [];
                    that.subProcessForm.defaultProcessCheckedKeys = [];
                    that.subProcessForm.processList = [];
                    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 = [];
                          that.subProcessForm.defaultProcessCheckedKeys = [];
                          that.subProcessForm.processList = [];
                          that.subProcessForm.processTags = ro.data;
                          that.subProcessForm.processTags.forEach(tag => {
                              that.subProcessForm.processList.push(tag.value);
                              that.subProcessForm.defaultProcessCheckedKeys.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.processList.push(tag.value);
                            this.subProcessForm.defaultProcessCheckedKeys.push(tag.value);
                        });
                        console.log('this.subProcessForm.processList',this.subProcessForm.processList)
                    }
                    this.initData();
                }
            },
            processTreeNodeFilterText(val){
              this.$refs.subProcessModelTree.filter(val);
            }
        }
    }
</script>

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