//流程引擎组件
define(['jquery', 'vue', 'layer', 'process-engine-debug'], function ($, Vue, layer) {
    return Vue.component('process-engine-toolbar', {
        template: '<span style="color: #333333;font-weight: normal;font-size: 14px;text-align: left;">\
            <template v-if="runtimeProcessId">\
                <select class="form_control" style="width: auto; display: inline-block;"\
                    @change="selectActivity($event)" v-if="pendingActivities.length > 1">\
                    <option value="" v-for="item in pendingActivities">{{item.name}}</option>\
                </select>\
                <button type="button" class="btn btn_primary" @click="openActionPanel(true)" v-if="pendingActivities.length>0"><i class="iconfont icon-next"></i>提交下一步处理</button>\
                <button type="button" class="btn btn_primary" v-if="currentActivity.allowDeliver&&currentActivity.deliverControl!=\'\'" @click="openDeliverPanel"><i class="iconfont icon-zhuanjiao"></i>转交</button>\
                <button type="button" class="btn btn_primary" v-if="currentActivity.returns.length > 0" @click="openReturnPanel"><i class="iconfont icon-back"></i>退回</button>\
                <button type="button" class="btn btn_primary" v-if="takeBacks.length > 0" @click="openTakeBackPanel"><i class="iconfont icon-chehui"></i>撤回</button>\
                <button type="button" class="btn btn_primary" v-if="showHistory" @click="openHistoryPanel"><i class="iconfont icon-lishi"></i>审批历史</button>\
                <button type="button" class="btn btn_primary" @click="openRuntimeDiagram"><i class="iconfont icon-process"></i>流程图</button>\
            </template>\
            <template v-if="!runtimeProcessId&&allowStart">\
                <button type="button" class="btn btn_primary" @click="openActionPanel(true)" v-if="pendingActivities.length>0"><i class="iconfont icon-next"></i>提交下一步处理</button>\
                <button type="button" class="btn btn_primary" @click="openDeployDiagram"><i class="iconfont icon-process"></i>流程图</button>\
            </template>\
            <process-engine-debug v-if="debug" @set-debug-data="setDebugData"></process-engine-debug>\
            <!--流程处理面板-->\
            <div class="block_container" id="processEngineActionPanel" style="display: none;">\
                <div class="content" v-if="(currentActivity.actions != undefined && currentActivity.actions.length > 1) || additionalControl != \'\'||extendControl!=\'\'"  style="padding: 14px 10px 0;">\
                    <keep-alive>\
                        <component :is="extendControl" ref="extendControl" style="padding-bottom: 10px;"></component>\
                    </keep-alive>\
                    <div class="peac_column peac_column_action" v-if="currentActivity.actions.length > 1||additionalControl != \'\'">\
                        <div class="peac_action_item" v-bind:class="{ \'peac_action_item_selected\': item.nextActivityId == currentAction.nextActivityId }"\
                         v-for="(item, index) in currentActivity.actions" @click="selectAction(item)">\
                            <i :class="itemAddClass(item)"></i>{{item.name}}\
                         </div>\
                    </div>\
                    <div class="peac_column peac_component" v-if="currentActivity.actions.length > 1||additionalControl != \'\'">\
                        <keep-alive>\
                            <component :is="additionalControl" :description="peacDescription" ref="additionalControl"></component>\
                        </keep-alive>\
                        <div class="peac_component_empty" v-if="currentActivity.actions.length > 1&&additionalControl == \'\'">{{currentAction.description}} 无需选择处理人。</div>\
                    </div>\
                    <br class="clear_both">\
                </div>\
                <div class="content" v-if="currentAction.commentRequired != null" style="padding: 10px 10px 0;">\
                    <div class="form_group">\
                        <div class="comment_toolbar">\
                            <span>请输入常用意见</span>\
                            <button type="button" class="btn btn_agree" @click="quickComment">同意</button>\
                            <select class="form_control"\
                                @change="selectComment($event)">\
                                <option value="">常用处理意见</option>\
                                <option :value="item.comment" v-for="item in comments">{{item.comment}}</option>\
                            </select>\
                            <label>\
                                <input type="checkbox" v-model="saveComment"> 保存为常用意见\
                            </label>\
                            <button type="button" class="btn btn_info" @click="openCommentPanel">编辑常用意见</button>\
                            <br class="clear_both">\
                        </div>\
                        <textarea class="form_control comment_textarea" rows="3" v-model="comment" placeholder="请在此输入意见!" style=""></textarea>\
                    </div>\
                </div>\
                <div class="peac_tips" v-if="currentActivity.actions.length == 1 && additionalControl == \'\' && currentAction.commentRequired == null">\
                    确定提交流程吗？\
                </div>\
            </div>\
            <!--流程转交-->\
            <div id="processEngineDeliverPanel" style="display: none; margin: 10px; color: #333333;font-weight: normal;">\
                <div>\
                    <keep-alive>\
                        <component :is="deliverControl" ref="deliverControl"></component>\
                    </keep-alive>\
                    <br class="clear_both">\
                </div>\
                <div class="comment_toolbar" style="margin-top: 10px;">\
                    <span>请输入常用意见</span>\
                    <button type="button" class="btn btn_agree" @click="quickComment">同意</button>\
                    <select class="form_control" @change="selectComment($event)">\
                        <option value="">常用处理意见</option>\
                        <option :value="item.comment" v-for="item in comments">{{item.comment}}</option>\
                    </select>\
                    <label>\
                        <input type="checkbox" v-model="saveComment"> 保存为常用意见\
                    </label>\
                    <button type="button" class="btn btn_info" @click="openCommentPanel">编辑常用意见</button>\
                    <br class="clear_both">\
                </div>\
                <textarea class="form_control comment_textarea" rows="3" v-model="comment" placeholder="请在此输入意见!"></textarea>\
            </div>\
            <!--流程退回面板-->\
            <div id="processEngineReturnPanel" style="display: none; margin: 10px; color: #333333;font-weight: normal;">\
                <keep-alive>\
                    <component :is="extendControl" :pass=false ref="extendControlReturn"></component>\
                </keep-alive>\
                <label style="line-height: 24px;">退回至</label>\
                <select class="form_control" v-model="returnToRuntimeActivityId">\
                    <option :value="item.returnToRuntimeActivityId" v-for="item in currentActivity.returns">\
                        {{item.actorName == ""?"":item.actorName + "："}}{{item.activityName}}\
                    </option>\
                </select>\
                <div v-if="currentAction.commentRequired != null">\
                    <div class="comment_toolbar" style="margin-top: 10px;">\
                        <span>请输入常用意见</span>\
                        <button type="button" class="btn btn_agree" @click="quickComment(false)">不同意</button>\
                        <select class="form_control" @change="selectComment($event)">\
                            <option value="">常用处理意见</option>\
                            <option :value="item.comment" v-for="item in comments">{{item.comment}}</option>\
                        </select>\
                        <label>\
                            <input type="checkbox" v-model="saveComment"> 保存为常用意见 \
                        </label>\
                        <button type="button" class="btn btn_info" @click="openCommentPanel">编辑常用意见</button>\
                        <br class="clear_both">\
                    </div>\
                    <textarea class="form_control comment_textarea" rows="3" v-model="comment" placeholder="请在此输入意见!"></textarea>\
                </div>\
            </div>\
            <!--流程撤回面板-->\
            <div id="processEngineTakeBackPanel" style="display: none; margin: 10px; color: #333333;font-weight: normal;">\
                <label style="line-height: 24px;">撤回至</label>\
                <select class="form_control" style="width: 100%;" v-model="takeBackToRuntimeActivityId">\
                    <option :value="item.takeBackToRuntimeActivityId" v-for="item in takeBacks">\
                        {{item.activityName}}\
                    </option>\
                </select>\
                <div class="comment_toolbar" style="margin-top: 10px;">\
                    <span>请输入常用意见</span>\
                    <button type="button" class="btn btn_agree" @click="quickComment">同意</button>\
                    <select class="form_control" @change="selectComment($event)">\
                        <option value="">常用处理意见</option>\
                        <option :value="item.comment" v-for="item in comments">{{item.comment}}</option>\
                    </select>\
                    <label>\
                        <input type="checkbox" v-model="saveComment"> 保存为常用意见 \
                    </label>\
                    <button type="button" class="btn btn_info" @click="openCommentPanel">编辑常用意见</button>\
                    <br class="clear_both">\
                </div>\
                <textarea class="form_control comment_textarea" rows="3" v-model="comment" placeholder="请在此输入意见!"></textarea>\
            </div>\
            <!--审批历史面板-->\
            <div id="processEngineHistoryPanel" style="display: none; margin: 10px; color: #333333;font-weight: normal;">\
                <process-engine-history-extend :historiesExtend="historiesExtend"></process-engine-history-extend>\
            </div>\
            <!--常用意见管理面板-->\
            <div id="processEngineCommentPanel" style="display: none; margin: 10px; color: #333333;font-weight: normal;">\
                <table class="table_list table_striped table_hover text_center">\
                    <thead><tr>\
                        <th>常用意见</th>\
                        <th>操作</th>\
                    </tr></thead>\
                    <tbody><tr v-for="(item, index) in comments" v-if="!item.system">\
                        <td class="text-left">{{item.comment}}</td>\
                        <td>\
                            <i title="删除" class="iconfont icon-delete tooltip" type="danger" @click="deleteComment(item)"></i>\
                        </td>\
                    </tr></tbody>\
                </table>\
            </div>\
        </span>',
        props: {
            deploySid: {required: true},                        //部署流程标识符
            domainId: {default: ''},                            //领域对象id
            domainData: {default: undefined},                   //领域对象数据
            beforeActionVerify: {type: Function, default: undefined}, //流程处理前校验事件
            beforeAction: {type: Function, default: undefined}, //流程处理前事件
            afterAction: {type: Function, default: undefined},  //流程处理后事件
            beforeReturn: {type: Function, default: undefined}, //流程退回前事件
            afterReturn: {type: Function, default: undefined},  //流程退回后事件
            beforeTakeBack: {type: Function, default: undefined},  //流程撤回后事件
            afterTakeBack: {type: Function, default: undefined},  //流程撤回后事件
            beforeDeliver: {type: Function, default: undefined}, //流程转交前事件
            afterDeliver: {type: Function, default: undefined},  //流程转交后事件
            hiddenWhenNoDomain: {default: true},                //没有domainId时隐藏
            showHistory: {default: false},                      //是否显示审批历史按钮
            hideTakeBack: {default: false},                      //是否显示撤回历史
            debug: {default: false},                            //调试模式，显示调试按钮
            allowStart: {default: true},                        //流程未启动时是否允许启动流程
            additionalControlParams: {
                default: function () {
                    return {};
                }
            }       //附加组件参数
        },
        data: function () {
            return {
                autoLoad: false,                                //当属性发生变化时是否自动重新加载流程数据
                innerDomainId: '',                              //领域对象id，组件内部数据
                innerDomainData: undefined,                     //领域对象数据，组件内部数据
                //流程初始化数据
                actor: '',                                      //当前处理人标识
                actorName: '',                                  //当前处理人名称
                runtimeProcessId: '',                           //运行时流程Id，流程未启动时为空
                pendingActivities: [],                          //需处理的活动，同一个人可能有多个要处理的活动
                takeBacks: [],                                  //可撤回至活动
                currentActivity: {actions: [], returns: []},    //当前操作针对的活动
                extendControl: '',                              //扩展组件标识
                currentAction: {},                              //当前处理动作
                additionalControl: '',                          //附件组件
                deliverControl: '',                             //转交组件标识
                comment: '',                                    //处理意见，处理和退回时公用
                //常用意见
                comments: {},                                   //常用意见，包括系统和用户自定义
                saveComment: false,                             //设为常用意见
                //流程退回数据
                returnToRuntimeActivityId: '',                  //要退回至的活动
                takeBackToRuntimeActivityId: '',                //要撤回至的活动
                historiesExtend: {},                            //审批历史，带扩展信息
                //待办
                todoDocumentType: '',
                todoTitle: '',
                todoUrl: '',
                todoSubcategory:'0',
                //被代理的人['id1::name1','id2::name2']
                principals: []
            }
        },
        computed: {
            peacDescription: function () {
                return this.currentAction.description == '' ? '已选择人员' : this.currentAction.description;
            }
        },
        watch: {
            deploySid: function (newValue, oldValue) {
                if (this.autoLoad)
                    this.loadProcess();
            },
            domainId: function (newValue, oldValue) {
                this.innerDomainId = newValue;
                if (this.autoLoad)
                    this.loadProcess();
            },
            domainData: function (newValue, oldValue) {
                this.innerDomainData = newValue;
            }
        },
        created: function () {
            this.innerDomainId = this.domainId;
            this.innerDomainData = this.domainData;

            //获取当前用户
            var that = this;
           /* $.ajax({
                type: 'GET',
                url: '/auth/current-actor',
                success: function (data) {
                    that.actor = data.data.id;
                    that.actorName = data.data.name;
                    if (data.data.departmentName)
                        that.actorName = that.actorName + '（' + data.data.departmentName + '）';
                    that.autoLoad = true;     //组件创建后激活自动加载
                    that.loadProcess();
                }
            });*/
            var that =this;
            $.ajax({
                url: currentLoginUser,
                type: "get",
                success: function (data) {
                    that.actor = data.data.accountId;
                    that.actorName = data.data.chineseName;//流程开始后，取当前处理人的中文名
                    //取常用意见
                    $.ajax({
                        type: 'GET',
                        url: processEngineServer + '/api/runtime/comments/' + that.actor,
                        success: function (data) {
                            that.comments = data.data;
                        }
                    });

                    //加载可处理活动
                    if (!that.hiddenWhenNoDomain || that.innerDomainId != '') {
                        that.loadProcess();
                    }
                }
            });
        },
        mounted: function () {
        },
        methods: {
            // 左侧按钮添加图标
            itemAddClass: function (item) {
                if (item.name == '审批')
                    return 'review';
                else if (item.name == '转交')
                    return 'transfer';
                else if (item.name == '会签')
                    return 'countersign';
                else
                    return 'internal_countersign'
            },
            //取当前处理活动
            getActivity: function () {
                return this.currentActivity;
            },
            //设置domainId
            setDomainId: function (domainId) {
                this.innerDomainId = domainId;
                if (this.autoLoad)
                    this.loadProcess();
            },
            //设置domainData
            setDomainData: function (domainData) {
                this.innerDomainData = domainData;
            },
            //加载流程
            loadProcess: function () {
                var that = this;
                //取常用意见
                $.ajax({
                    type: 'GET',
                    url: processEngineServer + '/api/runtime/comments/' + that.actor,
                    success: function (data) {
                        that.comments = data.data;
                    }
                });
                $.ajax({
                    type: 'POST',
                    url: processEngineServer + '/api/runtime/pending',
                    data: {deploySid: that.deploySid, actor: that.actor, domainId: that.innerDomainId},
                    success: function (data) {
                        //console.log(data)
                        if (!data.isSuccess) return;
                        that.runtimeProcessId = data.data.runtimeProcessId;
                        that.pendingActivities = data.data.pendingActivities;
                        that.selectActivity();  //选择处理活动
                        that.takeBacks = data.data.takeBacks;
                        if (that.takeBacks.length > 0)
                            //默认选中第一个能撤回的步骤
                            that.takeBackToRuntimeActivityId = that.takeBacks[0].takeBackToRuntimeActivityId;
                    }
                });
            },
            //切换处理活动
            selectActivity: function (event) {
                var index = 0;  //默认选择第一个处理活动
                if (event != undefined) {
                    index = event.target.selectedIndex;
                }
                if (this.pendingActivities.length > 0) {
                    this.currentActivity = this.pendingActivities[index];
                    //选择第一个处理动作，此时不设置组件名
                    this.currentAction = this.currentActivity.actions[0];
                    //选择第一个退回
                    if (this.currentActivity.returns.length > 0)
                        this.returnToRuntimeActivityId = this.currentActivity.returns[0].returnToRuntimeActivityId;
                    else
                        this.returnToRuntimeActivityId = '';
                } else {
                    this.currentActivity = {actions: [], returns: []};
                    //this.currentRuntimeProcessId = '';
                    this.currentAction = {};
                    //this.nextActivityId = '';
                    this.returnToRuntimeActivityId = '';
                }
                //切换处理活动后回调事件
                this.$emit("activity-change", this.currentActivity);
                this.$emit("action-change", this.currentAction);
            },
            //切换处理动作
            selectAction: function (action) {
                this.currentAction = action;
                //切换处理动作时切换组件
                this.additionalControl = action.additionalControl;
                //当有附加组件时，且需要为附加组件设置参数，且提供了对应的参数值，为附加组件设置参数值
                if (action.additionalControl != '' && action.additionalControlParam != ''
                    && this.additionalControlParams.hasOwnProperty(action.additionalControlParam)) {
                    var that = this;
                    //切换附加组件需在nextTick中$refs才能获取组件实例
                    this.$nextTick(function () {
                        //当附加组件有setParams方法时为附加组件设置参数值
                        if (that.$refs.additionalControl.setParams) {
                            that.$refs.additionalControl.setParams(that.additionalControlParams[action.additionalControlParam]);
                        }
                    });
                }
                //切换处理活动后回调事件
                this.$emit("action-change", this.currentAction);
            },
            //设置附件组件参数
            setAdditionalControlParams: function (name, value) {
                Vue.set(this.additionalControlParams, name, value);
            },
            /**
             * 处理
             * @param needBeforeActionVerify 是否需要流程前校验：true->需要校验
             */
            openActionPanel: function (needBeforeActionVerify) {
                var that = this;

                //打开处理窗口时绑定组件
                this.additionalControl = this.currentAction.additionalControl;
                this.$nextTick(function () {
                    if (this.currentAction.additionalControlParam != '' && this.additionalControlParams.hasOwnProperty(this.currentAction.additionalControlParam)
                        && this.$refs.additionalControl.setParams)
                        this.$refs.additionalControl.setParams(this.additionalControlParams[this.currentAction.additionalControlParam]);
                })
                //流程前校验事件
                if (needBeforeActionVerify && that.beforeActionVerify != undefined) {
                    try {
                        if (!that.beforeActionVerify()) {
                            //beforeActionVerify方法返回false时停止执行，不显示弹窗
                            return;
                        }
                    } catch (err) {
                        console.log(err);
                        //beforeActionVerify方法发生异常时停止执行，不显示弹窗
                        return;
                    }
                }
                //打开处理窗口时绑定扩展组件
                this.extendControl = this.currentActivity.extendControl;
                //防止多次点击提交
                var disableAction = false;
                this.$nextTick(function () {
                    layer.open({
                        type: 1,
                        area: '686px',
                        title: that.currentActivity.name,
                        btn: ['确定', '取消'],
                        btnAlign: 'c',
                        content: $('#processEngineActionPanel'),
                        yes: function (index, layero) {
                            if (disableAction) {
                                return;
                            }
                            //防止二次提交
                            disableAction = true;
                            var nextActivityId = that.currentAction.nextActivityId;
                            //验证附加组件
                            var additionalControlValue = undefined;
                            if (that.$refs.additionalControl != undefined) {
                                if (that.$refs.additionalControl.verifyValue != undefined) {
                                    if (!that.$refs.additionalControl.verifyValue()) {
                                        disableAction = false;
                                        return;
                                    }
                                }
                                additionalControlValue = that.$refs.additionalControl.getValue();
                            }
                            //验证处理意见
                            if (that.currentAction.commentRequired) {
                                if ($.trim(that.comment) == '') {
                                    disableAction = false;
                                    // alert('请输入' + that.currentAction.commentLabel + '。');
                                    layer.confirm('请输入' + that.currentAction.commentLabel + '。',
                                        {title:'提示',btn: ['确定'],closeBtn: 0},
                                        function(index){
                                            layer.close(index);
                                        });
                                    return;
                                }
                            }
                            //取扩展组件值
                            var extendControlValue = undefined;
                            if (that.$refs.extendControl != undefined) {
                                if (that.$refs.extendControl.verifyValue != undefined) {
                                    if (!that.$refs.extendControl.verifyValue()) {
                                        disableAction = false;
                                        return;
                                    }
                                }
                                extendControlValue = that.$refs.extendControl.getValue();
                            }
                            that.autoLoad = false;  //停止自动加载
                            //流程前事件
                            if (that.beforeAction != undefined) {
                                try {
                                    if (!that.beforeAction()) {
                                        layer.close(index);     //beforeAction方法返回false时停止执行，关闭弹窗
                                        return;
                                    }
                                } catch (err) {
                                    console.log(err);
                                    layer.close(index);     //beforeAction方法发生异常时停止执行，关闭弹窗
                                    return;
                                }
                            }
                            //流程提交数据
                            try {
                                //获取代理人
                                //if (additionalControlValue)
                                    //additionalControlValue = that.getAgent("", additionalControlValue);
                                var data = {
                                    actor: that.actor,
                                    actorName: that.actorName,
                                    domainId: that.innerDomainId,
                                    currentActivityId: that.currentActivity.id,
                                    nextActivityId: nextActivityId,     //that.currentAction.nextActivityId
                                    additionalControlValue: JSON.stringify(additionalControlValue),
                                    extendControlValue: JSON.stringify(extendControlValue),
                                    comment: that.comment,
                                    domainData: JSON.stringify(that.innerDomainData),
                                    saveComment: that.saveComment
                                };
                                var runtimeProcess = undefined;
                                if (that.runtimeProcessId == '') {
                                    data.deploySid = that.deploySid;
                                    //发起流程
                                    $.ajax({
                                        async: false,
                                        type: 'POST',
                                        url: processEngineServer + '/api/runtime/start',
                                        data: data,
                                        success: function (data) {
                                            if (!data.isSuccess)
                                                layer.msg(data.message);
                                            runtimeProcess = data.data;
                                        }
                                    });
                                } else {
                                    data.runtimeProcessId = that.runtimeProcessId;
                                    //处理流程
                                    $.ajax({
                                        async: false,
                                        type: 'POST',
                                        url: processEngineServer + '/api/runtime/action',
                                        data: data,
                                        success: function (data) {
                                            if (!data.isSuccess)
                                                layer.msg(data.message);
                                            runtimeProcess = data.data;
                                        }
                                    });
                                }
                            } catch (err) {
                                disableAction = false;
                                console.log(err);
                                if (!runtimeProcess && that.runtimeProcessId) {
                                    $.ajax({
                                        type: 'GET',
                                        async: false,
                                        url: processEngineServer + '/api/runtime-process/' + that.runtimeProcessId,
                                        success: function (data) {
                                            runtimeProcess = data.data;
                                        }
                                    });
                                }
                                that.syncTodo(runtimeProcess);
                                throw err;
                            }
                            //同步待办，防止afterAction方法中跳转到其他页面，在afterAction方法前执行
                            that.syncTodo(runtimeProcess);
                            //流程后事件
                            if (that.afterAction != undefined) {
                                that.afterAction(runtimeProcess.finished, runtimeProcess.stage, data);
                            }
                            that.comment = '';      //处理后清空意见
                            layer.close(index);     //关闭弹窗
                            that.loadProcess();     //重新加载流程
                            that.autoLoad = true;   //启用自动加载
                        }
                    });
                })

            },
            //转交
            openDeliverPanel: function () {
                //打开转交窗口时绑定组件
                this.deliverControl = this.currentActivity.deliverControl;
                var that = this;
                this.$nextTick(function () {
                    layer.open({
                        type: 1,
                        area: '686px',
                        title: '流程转交',
                        content: $('#processEngineDeliverPanel'),
                        btn: ['确定', '取消'],
                        btnAlign: 'c',
                        yes: function (index, layero) {
                            //验证转交组件
                            if (that.$refs.deliverControl != undefined) {
                                if (that.$refs.deliverControl.verifyValue != undefined) {
                                    if (!that.$refs.deliverControl.verifyValue())
                                        return;
                                }
                                that.deliverControlValue = that.$refs.deliverControl.getValue();
                            }
                            //验证转交意见，必填
                            if ($.trim(that.comment) == '') {
                                // alert('请输入转交说明。');
                                layer.confirm('请输入转交说明。',
                                    {title:'提示',btn: ['确定'],closeBtn: 0},
                                    function(index){
                                        layer.close(index);
                                    });
                                return;
                            }
                            that.autoLoad = false;  //停止自动加载
                            //流程转交前事件
                            if (that.beforeDeliver != undefined) {
                                try {
                                    if (!that.beforeDeliver()) {
                                        layer.close(index);     //beforeDeliver方法返回false时停止执行，关闭弹窗
                                        return;
                                    }
                                } catch (err) {
                                    console.log(err);
                                    layer.close(index);     //beforeDeliver方法发生异常时停止执行，关闭弹窗
                                    return;
                                }
                            }
                            //获取代理人
                            if (that.deliverControlValue)
                             //   that.deliverControlValue = that.getAgent(that.currentActivity.runtimeActivityId, that.deliverControlValue);
                            //流程转交数据
                            var data = {
                                runtimeProcessId: that.runtimeProcessId,
                                runtimeActivityId: that.currentActivity.runtimeActivityId,
                                actor: that.actor,
                                deliverActor: that.deliverControlValue,
                                comment: that.comment,
                                saveComment: that.saveComment
                            };
                            var runtimeProcess = undefined;
                            try {
                                //转交流程
                                $.ajax({
                                    async: false,
                                    type: 'POST',
                                    url: processEngineServer + '/api/runtime/deliver',
                                    data: data,
                                    success: function (data) {
                                        runtimeProcess = data.data;
                                    }
                                });
                            } catch (err) {
                                console.log(err);
                                if (!runtimeProcess && that.runtimeProcessId) {
                                    $.ajax({
                                        type: 'GET',
                                        async: false,
                                        url: processEngineServer + '/api/runtime-process/' + that.runtimeProcessId,
                                        success: function (data) {
                                            runtimeProcess = data.data;
                                        }
                                    });
                                }
                                that.syncTodo(runtimeProcess);
                                throw err;
                            }
                            //同步待办
                            that.syncTodo(runtimeProcess);
                            //流程转交后事件
                            if (that.afterDeliver != undefined) {
                                that.afterDeliver(runtimeProcess.stage, data);
                            }
                            that.comment = '';      //转交后清空意见
                            layer.close(index);     //关闭弹窗
                            that.loadProcess();     //重新加载流程
                            that.autoLoad = true;   //启用自动加载
                        }
                    });
                })

            },
            //退回
            openReturnPanel: function () {
                var that = this;
                //打开退回窗口时绑定扩展组件
                this.extendControl = this.currentActivity.extendControl;
                //防止多次点击提交
                var disableReturn = false;
                this.$nextTick(function () {
                    layer.open({
                        type: 1,
                        area: '686px',
                        title: '流程退回',
                        content: $('#processEngineReturnPanel'),
                        btn: ['确定退回', '取消'],
                        btnAlign: 'c',
                        yes: function (index, layero) {
                            if (disableReturn) {
                                return;
                            }
                            disableReturn = true;
                            //验证处理意见
                            if (that.currentAction.commentRequired) {
                                if ($.trim(that.comment) == '') {
                                    // alert('请输入' + that.currentAction.commentLabel + '。');
                                    disableReturn = false;
                                    layer.confirm('请输入' + that.currentAction.commentLabel + '。',
                                        {title:'提示',btn: ['确定'],closeBtn: 0 },
                                        function(index){
                                            layer.close(index);
                                        });
                                    return;
                                }
                            }
                            //取扩展组件值
                            var extendControlValue = undefined;
                            if (that.$refs.extendControlReturn != undefined) {
                                if (that.$refs.extendControlReturn.verifyValue != undefined) {
                                    if (!that.$refs.extendControlReturn.verifyValue()) {
                                        disableReturn = false;
                                        return;
                                    }
                                }
                                extendControlValue = that.$refs.extendControlReturn.getValue();
                            }

                            var returnTo = that.currentActivity.returns.filter(function (item) {
                                return item.returnToRuntimeActivityId == that.returnToRuntimeActivityId;
                            });
                            var returnToActivitySid = '';
                            if (returnTo.length > 0) {
                                returnToActivitySid = returnTo[0].activitySid;
                            }
                            that.autoLoad = false;  //停止自动加载
                            //流程退回前事件
                            if (that.beforeReturn != undefined) {
                                try {
                                    if (!that.beforeReturn(returnToActivitySid)) {
                                        layer.close(index);     //beforeReturn方法返回false时停止执行，关闭弹窗
                                        return;
                                    }
                                } catch (err) {
                                    console.log(err);
                                    layer.close(index);     //beforeReturn方法发生异常时停止执行，关闭弹窗
                                    return;
                                }
                            }
                            //流程退回数据
                            var data = {
                                runtimeProcessId: that.runtimeProcessId,
                                runtimeActivityId: that.currentActivity.runtimeActivityId,
                                returnToRuntimeActivityId: that.returnToRuntimeActivityId,
                                extendControlValue: JSON.stringify(extendControlValue),
                                actor: that.actor,      //退回时无需actorName
                                comment: that.comment,
                                saveComment: that.saveComment
                            };
                            var runtimeProcess = undefined;
                            //退回流程
                            try {
                                $.ajax({
                                    async: false,
                                    type: 'POST',
                                    url: processEngineServer + '/api/runtime/return',
                                    data: data,
                                    success: function (data) {
                                        runtimeProcess = data.data;
                                    }
                                });
                            } catch (err) {
                                disableReturn = false;
                                if (!runtimeProcess && that.runtimeProcessId) {
                                    $.ajax({
                                        type: 'GET',
                                        async: false,
                                        url: processEngineServer + '/api/runtime-process/' + that.runtimeProcessId,
                                        success: function (data) {
                                            runtimeProcess = data.data;
                                        }
                                    });
                                }
                                that.syncTodo(runtimeProcess);
                                throw err;
                            }
                            //根据流程生成或处理待办
                            that.syncTodo(runtimeProcess);
                            //流程退回后事件
                            if (that.afterReturn != undefined) {
                                that.afterReturn(runtimeProcess.finished, runtimeProcess.stage, returnToActivitySid);
                            }

                            that.comment = '';      //退回后清空意见
                            layer.close(index);     //关闭弹窗
                            that.loadProcess();     //重新加载流程
                            that.autoLoad = true;   //启用自动加载
                        }
                    });
                })

            },
            //撤回
            openTakeBackPanel: function () {
                var that = this;
                //防止多次点击提交
                var disableTakeBack = false;
                this.$nextTick(function () {
                    layer.open({
                        type: 1,
                        area: '686px',
                        title: '流程撤回',
                        content: $('#processEngineTakeBackPanel'),
                        btn: ['确定撤回', '取消'],
                        btnAlign: 'c',
                        yes: function (index, layero) {
                            if (disableTakeBack) {
                                return;
                            }
                            disableTakeBack = true;
                            if ($.trim(that.comment) == '') {
                                // alert('请输入撤回说明。');
                                disableTakeBack = false;
                                layer.confirm('请输入撤回说明。',
                                    {title:'提示',btn: ['确定'],closeBtn: 0 },
                                    function(index){
                                        layer.close(index);
                                    });
                                return;
                            }

                            var takeBackTo = that.takeBacks.filter(function (item) {
                                return item.takeBackToRuntimeActivityId == that.takeBackToRuntimeActivityId;
                            });
                            that.autoLoad = false;  //停止自动加载
                            //流程撤回前事件
                            if (that.beforeTakeBack != undefined) {
                                try {
                                    if (!that.beforeTakeBack()) {
                                        layer.close(index);     //beforeTakeBack方法返回false时停止执行，关闭弹窗
                                        return;
                                    }
                                } catch (err) {
                                    console.log(err);
                                    layer.close(index);     //beforeTakeBack方法发生异常时停止执行，关闭弹窗
                                    return;
                                }
                            }

                            //流程撤回数据
                            var data = {
                                runtimeProcessId: that.runtimeProcessId,
                                takeBackToRuntimeActivityId: that.takeBackToRuntimeActivityId,
                                actor: that.actor,
                                comment: that.comment,
                                saveComment: that.saveComment
                            };
                            var runtimeProcess = undefined;
                            //撤回流程
                            $.ajax({
                                async: false,
                                type: 'POST',
                                url: processEngineServer + '/api/runtime/takeback',
                                data: data,
                                success: function (data) {
                                    runtimeProcess = data.data;
                                }
                            });
                            //根据流程生成或处理待办
                            that.syncTodo(runtimeProcess, true);
                            //流程撤回后事件
                            if (that.afterTakeBack != undefined) {
                                that.afterTakeBack(runtimeProcess.stage);
                            }
                            that.comment = '';      //撤回后清空意见
                            layer.close(index);     //关闭弹窗
                            that.loadProcess();     //重新加载流程
                            that.autoLoad = true;   //启用自动加载
                        }
                    });
                })

            },
            //审流程历史
            openHistoryPanel: function () {
                var that = this;
                $.ajax({
                    type: 'GET',
                    url: processEngineServer + '/api/runtime/history/extend',
                    data: {runtimeProcessId: that.runtimeProcessId, hideTakeBack: that.hideTakeBack},
                    success: function (data) {
                        if (!data.isSuccess) return;
                        that.historiesExtend = data.data;
                        layer.open({
                            type: 1,
                            area: ['700px', '450px'],
                            title: '审批历史',
                            content: $('#processEngineHistoryPanel'),
                            btn: ['关闭'],
                            btnAlign: 'c',
                            yes: function (index, layero) {
                                layer.close(index);
                            }
                        });
                    }
                });
            },
            //选择常用意见
            selectComment: function (event) {
                this.comment = event.target.value;
                event.target.selectedIndex = 0;
            },
            //管理常用意见
            openCommentPanel: function () {
                layer.open({
                    type: 1,
                    area: ['500px', '450px'],
                    title: '管理自定义常用意见',
                    content: $('#processEngineCommentPanel'),
                    btn: ['确定'],
                    btnAlign: 'c',
                    yes: function (index, layero) {
                        layer.close(index);
                    }
                });
            },
            //删除常用意见
            deleteComment: function (item) {
                var that = this;
                if (confirm('确认删除常用意见“' + item.comment + '”吗？')) {
                    $.ajax({
                        type: 'POST',
                        url: processEngineServer + '/api/runtime/comments/remove',
                        data: {actor: that.actor, comment: item.comment},
                        success: function (data) {
                        }
                    });
                    this.comments = $.grep(this.comments, function (e) {
                        return e.comment != item.comment;
                    })
                }
            },
            // 快捷意见
            quickComment: function (type) {
                if (type == false)
                    this.comment = "不同意。";
                else
                    this.comment = "同意。";
            },
            //显示运行时流程图
            openRuntimeDiagram: function () {
                window.open('../../pages/process-engine/diagram.html?runtimeProcessId=' + this.runtimeProcessId);
            },
            //显示部署流程图
            openDeployDiagram: function () {
                window.open('../../pages/process-engine/diagram.html?deploySid=' + this.deploySid);
            },
            //调试组件加载调试数据
            setDebugData: function (pendingActivities) {
                this.pendingActivities = pendingActivities;
                this.selectActivity();
            },
            //设置待办参数
            setTodoParams: function (documentType, title, url,todoSubcategory) {
                this.todoDocumentType = documentType;
                this.todoTitle = title;
                this.todoUrl = url;
                this.todoSubcategory = todoSubcategory;
            },

            //设置待办参数
            setComment: function (comment) {
                this.comment = "[" + comment + "]" + this.comment;
            },
            //获取待处理人设置的代理人
            /*getAgent: function (runtimeActivityId, selectActor) {
                var that = this;
                if (typeof selectActor === 'string') {
                    var actor = selectActor;
                    var userId = selectActor.split('::')[0];
                    var userName = selectActor.split('::')[1];
                    $.ajax({
                        url: '/api-coop/agent/query/' + userId,
                        type: 'GET',
                        async: false,
                        success: function (res) {
                            if (res.data.userId) {
                                that.principals.push(runtimeActivityId + "::" + actor);
                                actor = res.data.agent + '::' + res.data.agentName + '（代 ' + userName + '）';
                            }
                        }
                    });
                    return actor;
                }
                if (Object.prototype.toString.call(selectActor) == "[object Array]") {
                    if (selectActor.length < 0)
                        return selectActor;
                    var actors = [];
                    for (var i = 0; i < selectActor.length; i++) {
                        var actor = selectActor[i];
                        var userId = actor.split('::')[0];
                        var userName = actor.split('::')[1];
                        $.ajax({
                            url: '/api-coop/agent/query/' + userId,
                            type: 'GET',
                            async: false,
                            success: function (res) {
                                if (res.data.userId) {
                                    that.principals.push(runtimeActivityId + "::" + actor);
                                    actor = res.data.agent + '::' + res.data.agentName + '（代 ' + userName + '）';
                                    actors.push(actor);
                                }
                                actors.push(actor);
                            }
                        });
                    }
                    return actors;
                }
            },*/
            //同步待办
            syncTodo: function (runtimeProcess, takeBack) {
                //根据流程生成或处理待办，业务系统自行设置待办传参
                $.ajax({
                    async: false,
                    type: 'POST',
                    url: '../../v1/api/todo/sync/' + runtimeProcess.id,
                    contentType: 'application/json',
                    data: JSON.stringify({
                        documentType: this.todoDocumentType,
                        title: this.todoTitle,
                        url: this.todoUrl,
                        todoSubcategory: this.todoSubcategory,
                        takeBack: takeBack,
                        runtimeProcess: runtimeProcess,
                        principals: this.principals  //被代理的人，发送已办
                    }),
                    success: function (data) {
                        console.log('同步流程代办');
                    }
                });
            }
        }
    });
});
