(function () {
    var processId = '';
    var taskId = '';

    var $header = null;
    var headText = '';

    var fieldMap = {};
    var formMap = {};
    var formDataes;
    var formreq;

    // 流程信息
    var info;
    var schemeObj;
    var currentNode;
    var nodeMap = {};

    var getFormData = function ($page) {
        formDataes = $page.find('#chlidauditcontainer').custmerformGet();
        if (formDataes == null) {
            return false;
        }
        formreq = [];
        for (var id in formDataes) {
            if (!fieldMap[id]) {
                learun.layer.warning('未设置流程表单关联字段！', function () { }, '数字化智慧校园', '关闭');
                return false;
            }
            if (!formMap[id]) {
                formDataes[id][fieldMap[id]] = info.childProcessId;
            }
            var point = {
                schemeInfoId: id,
                processIdName: fieldMap[id],
                formData: JSON.stringify(formDataes[id])
            }

            if (formMap[id]) {
                point.keyValue = info.childProcessId;
            }
            formreq.push(point);

            console.log(point);
        }

        return true;
    };

    var page = {
        init: function ($page, param) {
            var _html = '<div class="lr-form-header-submit" style="display:block;" >提交</div>';
            $header = $page.parents('.f-page').find('.f-page-header');
            $header.append(_html);
            headText = $header.find('.f-page-title').text();

            $page.find('.lr-chlidaudit-page').toptab(['表单信息', '父流程信息']).each(function (index) {
                var $this = $(this);
                switch (index) {
                    case 0:
                        $this.html('<div class="container" id="chlidauditcontainer"></div>');
                        break;
                    case 1:
                        $this.html('<div class="container" id="chlidauditcontainer2"></div>');
                        break;
                }
                $this = null;
            });
            processId = param.processId;
            taskId = param.taskId;
            taskinfo(param);

            // 提交
            $header.find('.lr-form-header-submit').on('tap', function () {
                learun.actionsheet({
                    id: 'chlidaudit1',
                    data: [
                        {
                            text: '创建子流程',
                            group: '1',
                            event: function () {
                                // 获取表单数据
                                if (!getFormData($page)) {
                                    return false;
                                }
                                learun.layer.confirm('是否确认创建子流程？', function (_index) {
                                    if (_index === '1') {
                                        // 创建流程
                                        page.create();
                                    }
                                }, '数字化智慧校园', ['取消', '确定']);
                            }
                        },
                        {
                            text: '保存草稿',
                            mark: true,
                            group: '2',
                            event: function () {
                                // 获取表单数据
                                if (!getFormData($page, true)) {
                                    return false;
                                }
                                // 创建草稿
                                page.saveDraft();

                            }
                        }
                    ],
                    cancel: function () {
                    }
                });
            });
        },
        create: function () {// info加签信息
            var flowreq = {
                code: currentNode.childFlow,
                processId: info.childProcessId,
                parentProcessId: processId,
                parentTaskId: taskId,
                formreq: JSON.stringify(formreq)
            };
            learun.layer.loading(true, "创建子流程中");
            learun.httppost(config.webapi + "learun/adms/newwf/childcreate", flowreq, function (data) {
                learun.layer.loading(false);
                var prepage = learun.nav.getpage('nworkflow/myflow');
                prepage.grid[1].reload();
                learun.nav.closeCurrent();
            });
        },
        saveDraft: function (info, auditers) {// info审核信息
            var flowreq = {
                formreq: JSON.stringify(formreq)
            };
            learun.layer.loading(true, "保存草稿！");
            learun.httppost(config.webapi + "learun/adms/newwf/draft", flowreq, function (data) {
                learun.layer.loading(false);
                learun.nav.closeCurrent();
            });
        },
        destroy: function (pageinfo) {
            $header = null;
        }
    };
    // 流程发起初始化
    function taskinfo(_param) {
        fieldMap = {};
        var req = {
            processId: _param.processId,
            taskId: _param.taskId
        };
        learun.layer.loading(true, "获取流程信息");
        learun.httpget(config.webapi + "learun/adms/newwf/processinfo", req, function (data) {
            if (data) {
                info = data.info;
                schemeObj = JSON.parse(info.Scheme);
                // 获取当前节点
                $.each(schemeObj.nodes, function (_index, _item) {
                    if (_item.id == info.CurrentNodeId) {
                        currentNode = _item;
                    }
                });

                learun.httpget(config.webapi + "learun/adms/newwf/scheme", currentNode.childFlow, function (cdata) {
                    learun.layer.loading(false);
                    if (cdata) {
                        var schemeObj3 = JSON.parse(cdata.F_Content);
                        var ccurrentNode;

                        // 获取开始节点
                        $.each(schemeObj3.nodes, function (_index, _item) {
                            if (_item.type == 'startround') {
                                ccurrentNode = _item;
                                return false;
                            }
                        });
                        var wfForms = ccurrentNode.wfForms;// 表单数据
                        var schemeIds = [];
                        var authorizeFields = [];
                        var formreq = [];

                        // 获取下关联字段
                        $.each(wfForms, function (_index, _item) {
                            if (_item.formId) {
                                fieldMap[_item.formId] = _item.field;
                                schemeIds.push(_item.formId);

                                var point = {
                                    schemeInfoId: _item.formId,
                                    processIdName: _item.field,
                                    keyValue: info.childProcessId,
                                }
                                formreq.push(point);

                                $.each(_item.authorize, function (_jindex, _jitem) {
                                    _jitem.fieldId = _jindex;
                                    authorizeFields.push(_jitem);
                                });
                            }
                        });
                        learun.custmerform.loadScheme(schemeIds, function (scheme) {
                            $('#chlidauditcontainer').custmerform(scheme);
                            // 设置表单的可查看权限
                            $.each(authorizeFields, function (_index, _item) {
                                if (_item.isLook === 0) {
                                    $('#chlidauditcontainer').find('#' + _item.fieldId).parents('.lr-form-row').remove();
                                }
                                else if (_item.isEdit === 0) {
                                    $('#chlidauditcontainer').find('#' + _item.fieldId).parents('.lr-form-row').attr('readonly', 'readonly');
                                }
                            });
                        });

                        formMap = {};
                        // 获取下自定义表单数据
                        learun.httpget(config.webapi + "learun/adms/form/data", formreq, function (data) {
                            if (data) {
                                // 设置自定义表单数据
                                $.each(data, function (_id, _item) {
                                    $.each(_item, function (_j, _jitem) {
                                        if (_jitem.length > 0) {
                                            formMap[_id] = true;
                                        }
                                    });
                                });
                                $('#chlidauditcontainer').custmerformSet(data);
                            }
                        });
                    }
                });
            }
            else {
                learun.layer.loading(false);
            }
        });
        learun.httpget(config.webapi + "learun/adms/newwf/processinfo", {
            processId: _param.processId
        }, function (data) {
            learun.layer.loading(false);
            if (data) {
                var schemeObj2 = JSON.parse(data.info.Scheme);
                // 获取当前节点
                $.each(schemeObj2.nodes, function (_index, _item) {
                    nodeMap[_item.id] = _item;
                });
                // 加载流程信息
                initTimeLine(data.info.TaskLogList);
            }

        });

    }
    function initTimeLine(flowHistory) {
        var nodelist = [];
        learun.clientdata.getAll('department', {
            callback: function (departmentMap) {
                learun.clientdata.getAll('user', {
                    callback: function (userMap) {
                        for (var i = 0, l = flowHistory.length; i < l; i++) {
                            var item = flowHistory[i];
                            var name = (item.F_CreateUserName || '系统处理') + '：';
                            if (item.F_CreateUserId && userMap[item.F_CreateUserId]) {
                                var _department = departmentMap[userMap[item.F_CreateUserId].departmentId];
                                if (_department) {
                                    name = '【' + _department.name + '】' + name;
                                }
                            }
                            var content = item.F_OperationName;
                            if (item.F_Des) {
                                content += '【审批意见】' + item.F_Des;
                            }
                            var nodeName = '';
                            if (item.F_NodeId && nodeMap[item.F_NodeId]) {
                                nodeName = nodeMap[item.F_NodeId].name;
                            }

                            var point = {
                                title: item.F_NodeName || nodeName,
                                people: name,
                                content: content,
                                time: item.F_CreateDate
                            };

                            nodelist.push(point);
                        }
                        $('#chlidauditcontainer2').ftimeline(nodelist);
                    }
                });
            }
        });
    }
    return page;
})();