define(['jquery', 'vue', 'layer', 'vant'], function ($, Vue, layer, vant) {
    Vue.use(vant)
    return Vue.component('process-engine-toolbar-v2', {
        template: '<div class="process_engine_toolbar">\
        <!--<van-sticky :offset-top="94">\
            <van-tabbar v-model="active" :fixed="false" v-if="currentActivity.returns && currentActivity.returns.length>0"\
                @change="onTabChange">\
              <van-tabbar-item icon="home-o" name="处理" @click="openActionPanel">\
                <template #icon>\
                    <van-icon class-prefix="iconfont icon" name="xiayigechuliren" slot="icon"/>\
                </template>\
              处理</van-tabbar-item>\
              <van-tabbar-item icon="search" name="退回" @click="openReturnPanel">\
                <template #icon>\
                    <van-icon class-prefix="iconfont icon" name="chehui" slot="icon"/>\
                </template>\
              退回</van-tabbar-item>\
            </van-tabbar>\
        </van-sticky>-->\
        <!--处理-->\
        <div v-if="pendingActivities && pendingActivities.length>0">\
            <!-- 流程拓展组件-->\
            <keep-alive>\
                <component :is="actionExtendControl" ref="actionExtendControl"></component>\
            </keep-alive>\
            <!-- 流程拓展组件-->\
            <!--处理意见-->\
            <template v-if="currentAction.commentRequired != null">\
                <!-- 常用处理意见-->\
                <van-cell-group>\
                    <van-cell class="comemnt_container">\
                        <template #title>\
                            <van-button color="#1989fa" plain style="height: 0.8rem;" @click="showComment=true">选择处理意见\
                            </van-button>\
                        </template>\
                    </van-cell>\
                </van-cell-group>\
                <van-cell-group>\
                    <van-field\
                            v-model="comment"\
                            rows="2"\
                            autosize\
                            type="textarea"\
                            maxlength="500"\
                            placeholder="请输入意见"\
                            show-word-limit\
                    ></van-field>\
                </van-cell-group>\
            </template>\
            <!-- 选择下一步处理活动-->\
            <van-cell-group>\
                <van-cell title="下一步"\
                          is-link\
                          arrow-direction="down"\
                          :value="currentAction.name"\
                          @click="onShowActionsPicker"></van-cell>\
            </van-cell-group>\
            <!-- 选人组件 -->\
            <template v-if="currentActivity.actions.length > 1||additionalControl != \'\'">\
                <!--<p class="process_step_title" style="">选择下一步处理人</p>-->\
                <component :is="additionalControl" :description="peacDescription" ref="additionalControl"></component>\
            </template>\
            <!-- 无需选择处理人 -->\
            <van-cell v-if="currentActivity.actions.length > 1&&additionalControl == \'\'">\
                <template slot="title">\
                    <span style="text-align: left;">\
                      <p style="font-weight: bold;">下一步处理人</p>\
                      <p style="font-weight: lighter;">{{currentAction.description}}无需选择处理人</p>\
                    </span>\
                </template>\
                <template slot="right-icon">\
                    <div class="flex" style="align-items: center;">\
                        <span class="round_block">无</span>\
                    </div>\
                </template>\
            </van-cell>\
            <div class="process_btn_container">\
                <van-button block color="#009ace" class="process_btn" @click="onAction">提交</van-button>\
                <van-button block color="#cc1300" class="process_btn" @click="openReturnPanel" v-if="currentActivity.returns && currentActivity.returns.length>0">退回</van-button>\
            </div>\
        </div>\
        <!--退回-->\
        <!--<div v-show="currentActivity.returns && currentActivity.returns.length>0 && active == \'退回\'">\
            <keep-alive>\
                <component :is="returnExtendControl" :pass=false ref="returnExtendControl"></component>\
            </keep-alive>\
            &lt;!&ndash;退回至&ndash;&gt;\
            <van-cell-group>\
                <van-cell title="退回至"\
                          is-link\
                          arrow-direction="down"\
                          :value="returnToRuntimeActivityName"\
                          @click="onShowReturnsPicker"></van-cell>\
            </van-cell-group>\
            &lt;!&ndash; 常用处理意见&ndash;&gt;\
            <van-cell-group>\
                <van-cell class="comemnt_container">\
                    <template #title>\
                        <van-button color="#1989fa" plain style="height: 0.8rem;" @click="showComment=true">选择处理意见\
                        </van-button>\
                    </template>\
                </van-cell>\
            </van-cell-group>\
            &lt;!&ndash;处理意见&ndash;&gt;\
            <van-cell-group>\
                <van-field\
                        v-model="returnComment"\
                        rows="2"\
                        autosize\
                        type="textarea"\
                        maxlength="500"\
                        placeholder="请输入意见"\
                        show-word-limit\
                ></van-field>\
            </van-cell-group>\
            <div class="process_btn_container">\
                <van-button block color="#1989fa" class="process_btn" @click="onRetrunAction">确定退回</van-button>\
            </div>\
        </div>-->\
        <!--处理活动步骤-->\
        <van-popup v-model="actionsPicker" round position="bottom">\
            <van-picker\
                    show-toolbar\
                    value-key="name"\
                    :columns="currentActivity.actions"\
                    @cancel="actionsPicker = false"\
                    @confirm="selectAction"\
            ></van-picker>\
        </van-popup>\
        <!--常用意见-->\
        <van-popup v-model="showComment" round position="bottom">\
            <van-picker\
                    show-toolbar\
                    value-key="comment"\
                    :columns="comments"\
                    @cancel="showComment = false"\
                    @confirm="selectComment"\
            ></van-picker>\
        </van-popup>\
        <!--退回至-->\
        <van-popup v-model="showReturnPicker" round position="bottom">\
            <van-picker\
                    show-toolbar\
                    :columns="currentActivity.returns"\
                    @cancel="showReturnPicker = false"\
                    @confirm="selectReturns"\
            >\
                <template #option="{actorName, activityName}">\
                    {{actorName == ""?"":actorName + "："}}{{activityName}}\
                </template>\
            </van-picker>\
        </van-popup>\
    </div>',
        props: {
            beforeProcess: {type: Function, default: undefined},          //打开流程操作弹窗前事件
        },
        data: function () {
            return {
                showNextActivity: false,        //流程处理步骤选择弹窗
                showReturn: false,            //流程退回步骤弹窗
                // showTakeBack: false,              //流程撤回步骤弹窗
                showHistory: false,             //流程历史弹窗

                canAction: true,                //可以调用处理流程接口-防止重复点击
                showHandleProcess: false, // 处理流程
                title: '提交',
                actionsPicker: false, // 选择处理当前流程
                showReturnPicker: false, // 退回动作
                // showRecallPicker: false, // 撤回动作
                showComment: false, // 常用处理意见


                deploySid: '',                                   //部署流程标识符
                runtimeProcessId: '',                            //运行时流程Id，流程未启动时为空
                pendingActivities: [],                           //需处理的活动，同一个处理人可能有多个需处理的活动
                currentActivity: {actions: [], returns: []},     //选择的处理活动
                currentAction: {},                               //当前处理动作
                // takeBacks: [],                                   //可撤回至的活动
                returnToRuntimeActivityId: '',                   //选择的要退回至的活动
                returnToRuntimeActivityName: '',                 //选择的要退回至的活动名
                // takeBackToRuntimeActivityId: '',                 //选择的要撤回至的活动
                actionExtendControl: '',                         //处理时扩展组件标识
                returnExtendControl: '',                         //退回时扩展组件标识
                additionalControl: '',                           //附加组件标识
                deliverControl: '',                              //转交组件标识
                //处理意见
                comments: [],                                    //常用意见，包括系统和用户自定义
                comment: '同意',                                     //处理意见，处理、转交、退回、撤回时共用
                saveComment: false,                              //是否设为常用意见
                //由调用页面设置的各类参数
                additionalControlParams: {},                     //附加组件参数对象
                actionSwitchParams: {},                          //处理动作开关参数对象
                deliverControlParams: undefined,                 //转交组件参数对象

                active: '处理'
            }
        },
        computed: {
            peacDescription: function () {
                return this.currentAction.description == '' ? '已选择人员' : this.currentAction.description;
            }
        },
        watch: {},
        created: function () {
        },
        mounted: function () {
        },
        methods: {
            //选择常用意见
            selectComment: function (value) {
                this.comment = value.comment
                this.showComment = false
            },

            //region 处理
            //展示下一步处理动作
            onShowActionsPicker() {
                if (this.currentActivity.actions.length > 1) this.actionsPicker = true;
                else vant.Toast("无更多处理动作");
            },
            onClickBack() {
                this.showNextActivity = false   //流程处理步骤选择弹窗
                this.showReturn = false         //流程退回步骤弹窗
                // this.showTakeBack = false       //流程撤回步骤弹窗
                this.$refs.processEngineHistoryExtendV2.showHistory = false        //流程历史弹窗
               // this.loadProcess();
            },
            onShowReturnsPicker() {
                if (this.currentActivity.returns.length > 1) this.showReturnPicker = true
                else vant.Toast("无更多退回动作");
            },

            // 选择的要退回至的活动
            selectReturns(value, index) {
                this.returnToRuntimeActivityId = value.returnToRuntimeActivityId
                this.returnToRuntimeActivityName = (value.actorName == "" ? "" : value.actorName + "：") + value.activityName
                this.showReturnPicker = false
            },

            // 左侧按钮添加图标
            itemAddClass: function (item) {
                if (item.name == '审批')
                    return 'review';
                else if (item.name == '转交')
                    return 'transfer';
                else if (item.name == '会签')
                    return 'countersign';
                else
                    return 'internal_countersign'
            },
            //初始化流程组件，发起状态
            initProcess: function (pendingData) {
                //console.log(pendingData);
                this.deploySid = pendingData.deploySid;
                //this.runtimeProcessId = pendingData.runtimeProcessId;   //初始化时runtimeProcessId为空
                this.pendingActivities = pendingData.pendingActivities;
                this.takeBacks = pendingData.takeBacks;
                this.selectActivity();
                this.loadComments();
                if (this.pendingActivities && this.pendingActivities.length > 0) {
                    this.openActionPanel()
                }
            },
            //初始化流程组件，处理状态
            loadProcess: function (pendingData) {
                //console.log(pendingData);
                this.deploySid = pendingData.deploySid;
                this.runtimeProcessId = pendingData.runtimeProcessId;
                this.pendingActivities = pendingData.pendingActivities;
                this.takeBacks = pendingData.takeBacks;
                this.selectActivity();
                this.loadComments();
                if (this.pendingActivities && this.pendingActivities.length > 0) {
                    this.openActionPanel()
                }
            },
            //设置附加组件参数
            setAdditionalControlParams: function (name, value) {
                Vue.set(this.additionalControlParams, name, value);
            },
            //设置处理动作开关参数
            setActionSwitchParams: function (name, value) {
                Vue.set(this.actionSwitchParams, name, value);
            },
            //设置转交组件参数
            setDeliverControlParams: function (value) {
                this.deliverControlParams = value;
            },
            //取当前处理活动，可用于判断当前所处流程
            getActivity: function () {
                return this.currentActivity;
            },
            //切换处理活动
            selectActivity: function (event) {
                var index = 0;  //默认选择第一个处理活动显示系统活动
                if (event != undefined) {
                    index = event.target.selectedIndex;
                    //event.target.options.selectedIndex;
                }
                if (this.pendingActivities.length > 0) {
                    this.currentActivity = this.pendingActivities[index];
                } else {
                    this.currentActivity = {actions: [], returns: []};
                }
                //切换处理活动后回调事件
                this.$emit("activity-change", this.currentActivity);
            },
            //切换处理动作
            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.actionsPicker = false
            },

            // 处理
            showActionPanel(){
                if (this.currentActivity.returns && this.currentActivity.returns.length>0) {
                    return  this.active === '处理'
                }  else {
                    return  this.pendingActivities.length > 0
                }
            },
            //处理
            openActionPanel() {
                if (this.beforeProcess != undefined) {
                    if (!this.beforeProcess('action')) {
                        return;
                    }
                }
                //打开处理窗口时初始化选中的动作
                var that = this;
                var valid = false;
                var firstAction = undefined;
                $.each(this.currentActivity.actions,
                    function (index, item) {
                        if (!item.switchable || String(that.actionSwitchParams[item.switchParam]) == 'true') {
                            if (!firstAction) {
                                firstAction = item;
                            }
                            if (item.nextActivityId == that.currentAction.nextActivityId) {
                                valid = true;
                                return false; //break
                            }
                        }
                    });
                if (!valid)
                    this.currentAction = firstAction;
                if (this.currentAction == undefined) {
                    vant.Toast('未找到可执行的处理动作。');
                    return;
                }
                //打开处理窗口时绑定附加组件
                this.additionalControl = this.currentAction.additionalControl;
                //设置附加组件参数
                if (this.additionalControl != '' && this.currentAction.additionalControlParam != ''
                    && this.additionalControlParams.hasOwnProperty(this.currentAction.additionalControlParam)) {
                    this.$nextTick(function () {
                        if (that.$refs.additionalControl.setParams) {
                            that.$refs.additionalControl.setParams(that.additionalControlParams[that.currentAction.additionalControlParam]);
                        }
                    });
                }
                //打开处理窗口时绑定扩展组件
                this.actionExtendControl = this.currentActivity.extendControl;
                // 打开处理窗口
                this.showNextActivity = true
            },

            onAction() {
                if (!this.canAction) return
                this.canAction = false
                //验证附加组件值
                var additionalControlValue = undefined;
                if (this.$refs.additionalControl != undefined) {
                    if (this.$refs.additionalControl.verifyValue != undefined) {
                        if (!this.$refs.additionalControl.verifyValue()) {
                            this.canAction = true
                            return;
                        }
                    }
                    additionalControlValue = this.$refs.additionalControl.getValue();
                }
                //验证处理意见
                // if (this.currentAction.commentRequired) {
                    if ($.trim(this.comment) == '') {
                        vant.Dialog.alert({
                            title: '提示',
                            message: '请输入' + this.currentAction.commentLabel + '。',
                        }).then(() => {
                            // on close
                        });
                        this.canAction = true
                        return;
                    }
                // }
                //取扩展组件值
                var extendControlValue = undefined;
                if (this.$refs.actionExtendControl != undefined) {
                    if (this.$refs.actionExtendControl.verifyValue != undefined) {
                        if (!this.$refs.actionExtendControl.verifyValue()){
                            this.canAction = true
                            return;
                        }
                    }
                    extendControlValue = this.$refs.actionExtendControl.getValue();
                }
                if (this.runtimeProcessId) {
                    //流程处理数据
                    var data = {
                        runtimeProcessId: this.runtimeProcessId,
                        currentActivityId: this.currentActivity.id,
                        nextActivityId: this.currentAction.nextActivityId,
                        additionalControlValue: JSON.stringify(additionalControlValue),
                        extendControlValue: JSON.stringify(extendControlValue),
                        comment: this.comment,
                        saveComment: this.saveComment,
                        currentActivityName: this.currentActivity.name,
                    };
                    this.$emit('process-action', data);
                } else {
                    //流程启动数据
                    var data = {
                        deploySid: this.deploySid,
                        currentActivityId: this.currentActivity.id,
                        nextActivityId: this.currentAction.nextActivityId,
                        additionalControlValue: JSON.stringify(additionalControlValue),
                        extendControlValue: JSON.stringify(extendControlValue),
                        comment: this.comment,
                        saveComment: this.saveComment
                    };
                    this.$emit('process-start', data);
                }
                this.canAction = true
               //  this.loadProcess();
                this.comment = '';      //处理后清空意
                this.showNextActivity = false //关闭弹窗

            },


            //退回
            openReturnPanel: function () {
                if (this.beforeProcess != undefined) {
                    if (!this.beforeProcess('return')) {
                        return;
                    }
                }
                //打开退回窗口时初始化选中的退回选项
                var that = this;
                var valid = false;
                if (this.returnToRuntimeActivityId) {
                    $.each(this.currentActivity.returns,
                        function (index, item) {
                            if (item.returnToRuntimeActivityId == that.returnToRuntimeActivityId) {
                                valid = true;
                                return false; //break
                            }
                        });
                }
                if (!valid) {
                    let currentReturn = this.currentActivity.returns[0]
                    this.returnToRuntimeActivityId = currentReturn.returnToRuntimeActivityId;
                    this.returnToRuntimeActivityName = (currentReturn.actorName == "" ? "" : currentReturn.actorName + "：") + currentReturn.activityName
                }
                //打开退回窗口时绑定扩展组件
                this.returnExtendControl = this.currentActivity.extendControl;
                this.showReturn = true
                this.onRetrunAction()
            },
            // 退回动作
            onRetrunAction() {
                if ($.trim(this.comment) == '') {
                    vant.Dialog.alert({
                        title: '提示',
                        message: '请输入' + this.currentAction.commentLabel + '。',
                    }).then(() => {
                        // on close
                    });
                    return;
                }
                //取扩展组件值
                var extendControlValue = undefined;
                if (this.$refs.returnExtendControl != undefined) {
                    if (this.$refs.returnExtendControl.verifyValue != undefined) {
                        if (!this.$refs.returnExtendControl.verifyValue())
                            return;
                    }
                    extendControlValue = this.$refs.returnExtendControl.getValue();
                }
                //流程退回数据
                var data = {
                    runtimeProcessId: this.runtimeProcessId,
                    runtimeActivityId: this.currentActivity.runtimeActivityId,
                    returnToRuntimeActivityId: this.returnToRuntimeActivityId,
                    extendControlValue: JSON.stringify(extendControlValue),
                    comment: this.comment,
                    saveComment: this.saveComment
                };
                this.$emit('process-return', data);
                this.comment = '';      //退回后清空意见
            },

            //加载常用意见
            loadComments: function () {
                var that = this;
                var userId=''
                $.ajax({
                    url: getContextPath() + '/auth/current-user',
                    type: "get",
                    async:false,
                    success: function (data) {
                        userId = data.data.id;
                    }
                });
                $.ajax({
                    type: 'GET',
                    url: processEngineServer + '/api/runtime/comments/'+userId,
                    success: function (data) {
                        that.comments = data.data;
                    }
                });
            },
            //选择常用意见
            // selectComment: function (event) {
            //     this.comment = event.target.value;
            //     event.target.selectedIndex = 0;
            // },
            onTabChange(){
                //this.comment = ''
            }
        }
    })
})
