var OaNodeManageCtrl = ['$scope', '$modal', '$timeout', '$translate', function ($scope, $modal, $timeout, $translate) {
    var opts = {
        template: 'editor-app/configuration/properties/oa-node-manage-popup.html?version=' + Date.now(),
        backdrop: 'static',
        keyboard: false,
        scope: $scope
    };
    $modal(opts);
}];

var OaNodeManagePopupCtrl = ['$scope', '$timeout', '$http', function ($scope, $timeout, $http) {
    // console.log($scope.editor);
    // console.log($scope.editor.modelMetaData.model.childShapes);
    // console.log($scope.stencilItemGroups)
    // 获取流程中的配置
    var selection = $scope.editor.selection[0];
    var modelJson = $scope.editor.getJSON();
    // console.log(modelJson);
    var childShapes = modelJson.childShapes;

    // 关联到的属性
    var multiInstanceType = $scope.selectedItem.properties[7];
    var multiInstanceCollection = $scope.selectedItem.properties[9];
    var multiInstanceVariable = $scope.selectedItem.properties[10];
    var multiInstanceCondition = $scope.selectedItem.properties[11];
    var assigneeProperty = $scope.selectedItem.properties[13];
    var taskListenerProperty = $scope.selectedItem.properties[16];

    // 初始化
    var startNode;
    var CANDIDATES_COLLECTION = '${candidates}';
    var MULTI_INSTANCE_COLLECTION = '${assigneeList}';
    var MULTI_INSTANCE_VARIABLE = 'assignee';
    var MULTI_ASSIGNEE_USER = '${assignee}';
    var NR_OF_COMPLETED_INSTANCES = 'nrOfCompletedInstances';
    var NR_OF_INSTANCES = 'nrOfInstances';
    var ASSIGNEE_USER = '${assigneeUser}';
    var START_ASSIGNEE_USER = '${startAssigneeUser}';

    $scope.oaNodeManage = {
        assignee: {
            nodeType: 'normal',
            assigneeCount: 'single',
            assignee: '',
            assigneeName: '',
            candidates: '',
            candidateNames: '',
            multipleType: 'parallel',
            completeCondition: 'allPass',
            completeCount: 1,
            multipleAssignees: '',
            multipleAssigneeNames: '',
            assigneeType: 'appoint',
            autoAssignType: 'scope',
            departmentType: 'appoint',
            departments: '',
            departmentNames: '',
            roles: '',
            roleNames: '',
            positions: '',
            positionNames: '',
            quickAssignee: 'starter',
            previousNStep: 1
        },
        formId: '',
        formFields: [],
        formButton: {
            btnAttachment: 0,
            btnGoBack: 0,
            btnForcedEnd: 0,
            btnCc: 0,
            btnPrint: 0,
            btnTransfer: 0
        },
        oaUserTaskListeners: []
    }

    // 添加用户任务监听器
    function addOaUserTaskListener(event, className, expression, delegateExpression) {
        var implementation = '';
        if (className) {
            implementation = className;
        } else if (expression) {
            implementation = expression;
        } else if (delegateExpression) {
            implementation = delegateExpression;
        }
        $scope.oaNodeManage.oaUserTaskListeners.push({
            event: event,
            implementation: implementation,
            className: className ? className : '',
            expression: expression ? expression : '',
            delegateExpression: delegateExpression ? delegateExpression : ''
        });
    }

    /**
     * 判断监听器是否存在
     * @param event
     * @param className
     */
    function isListenerExist(event, className) {
        for (var i = 0, item; item = $scope.oaNodeManage.oaUserTaskListeners[i++];) {
            if (item.event == event && item.className == className) {
                return true;
            }
        }
        return false;
    }

    $scope.addOaUserTaskCreateListener = function () {
        var event = 'create',
            className = '',
            expression = '',
            delegateExpression = '${oaUserTaskCreateListener}';
        if (isListenerExist(event, className)) {
            top.dialog.msg('监听器已经存在');
            return;
        }
        addOaUserTaskListener(event, className, expression, delegateExpression);
    }
    $scope.addOaUserTaskAssignmentListener = function () {
        var event = 'assignment',
            className = '',
            expression = '',
            delegateExpression = '${oaUserTaskAssignmentListener}';
        if (isListenerExist(event, className)) {
            top.dialog.msg('监听器已经存在');
            return;
        }
        addOaUserTaskListener(event, className, expression, delegateExpression);
    }
    $scope.addOaUserTaskCompleteListener = function () {
        var event = 'complete',
            className = '',
            expression = '',
            delegateExpression = '${oaUserTaskCompleteListener}';
        if (isListenerExist(event, className)) {
            top.dialog.msg('监听器已经存在');
            return;
        }
        addOaUserTaskListener(event, className, expression, delegateExpression);
    }
    $scope.addOaUserTaskDeleteListener = function () {
        var event = 'delete',
            className = '',
            expression = '',
            delegateExpression = '${oaUserTaskDeleteListener}';
        if (isListenerExist(event, className)) {
            top.dialog.msg('监听器已经存在');
            return;
        }
        addOaUserTaskListener(event, className, expression, delegateExpression);
    }
    // 上移用户任务监听器
    $scope.moveOaUserTaskListenerUp = function (index) {
        var prevIndex = index - 1;
        var temp = $scope.oaNodeManage.oaUserTaskListeners[index];
        $scope.oaNodeManage.oaUserTaskListeners.splice(index, 1);
        $timeout(function () {
            $scope.oaNodeManage.oaUserTaskListeners.splice(prevIndex, 0, temp);
        }, 10);
    }
    // 下移用户任务监听器
    $scope.moveOaUserTaskListenerDown = function (index) {
        var nextIndex = index + 1;
        var temp = $scope.oaNodeManage.oaUserTaskListeners[index];
        $scope.oaNodeManage.oaUserTaskListeners.splice(index, 1);
        $timeout(function () {
            $scope.oaNodeManage.oaUserTaskListeners.splice(nextIndex, 0, temp);
        }, 10);
    }
    // 删除用户任务监听器
    $scope.deleteOaUserTaskListener = function (index) {
        $scope.oaNodeManage.oaUserTaskListeners.splice(index, 1);
    }

    $scope.checkCompleteCount = function () {
        var assignee = $scope.oaNodeManage.assignee;
        if (!assignee.completeCount) {
            assignee.completeCount = 1;
            return;
        }
        if (assignee.completeCount < 1) {
            assignee.completeCount = 1;
        }
    }

    $scope.checkPreviousNStep = function () {
        var assignee = $scope.oaNodeManage.assignee;
        if (!assignee.previousNStep) {
            assignee.previousNStep = 1;
            return;
        }
        if (assignee.previousNStep < 1) {
            assignee.previousNStep = 1;
        }
    }

    // 选择用户
    $scope.selectAssignee = function () {
        var assignee = $scope.oaNodeManage.assignee;
        top.dialog.dialogData.selectedUserIds = assignee.assignee;
        top.dialog.open({
            url: top.restAjax.path('route/department/user/select-user', []),
            title: '选择代理人【单选】',
            width: '500px',
            height: '500px',
            closeBtn: 0,
            onClose: function () {
                var selectedUsers = top.dialog.dialogData.selectedDepartmentUsers;
                // 这里写处理逻辑
                if (selectedUsers && selectedUsers.length > 0) {
                    if (selectedUsers.length > 1) {
                        top.dialog.msg('只能选择一位代理人');
                        return;
                    }
                    assignee.assignee = selectedUsers[0].userId;
                    assignee.assigneeName = selectedUsers[0].userName;
                } else {
                    assignee.assignee = '';
                    assignee.assigneeName = '';
                }
                top.dialog.dialogData.selectedDepartmentUsers = [];
                $scope.$apply();
            }
        })
    }
    // 选择候选人
    $scope.selectCandidates = function () {
        var assignee = $scope.oaNodeManage.assignee;
        top.dialog.dialogData.selectedUserIds = assignee.candidates ? assignee.candidates.replace(/,/g, '_') : '';
        top.dialog.open({
            url: top.restAjax.path('route/department/user/select-user', []),
            title: '选择候选人【多选】',
            width: '500px',
            height: '500px',
            closeBtn: 0,
            onClose: function () {
                var selectedUsers = top.dialog.dialogData.selectedDepartmentUsers;
                // 这里写处理逻辑
                if (selectedUsers && selectedUsers.length > 0) {
                    var candidates = '';
                    var candidateNames = '';
                    for (var i = 0, item; item = selectedUsers[i++];) {
                        if (candidates.length) {
                            candidates += ',';
                            candidateNames += ',';
                        }
                        candidates += item.userId;
                        candidateNames += item.userName;
                    }
                    assignee.candidates = candidates;
                    assignee.candidateNames = candidateNames;
                } else {
                    assignee.candidates = '';
                    assignee.candidateNames = '';
                }
                top.dialog.dialogData.selectedDepartmentUsers = [];
                $scope.$apply();
            }
        })
    }
    // 选择多实例代理人
    $scope.selectMultipleAssignee = function () {
        var assignee = $scope.oaNodeManage.assignee;
        top.dialog.dialogData.selectedUserIds = assignee.multipleAssignees ? assignee.multipleAssignees.replace(/,/g, '_') : '';
        top.dialog.open({
            url: top.restAjax.path('route/department/user/select-user', []),
            title: '选择多实例代理人【多选】',
            width: '500px',
            height: '500px',
            closeBtn: 0,
            onClose: function () {
                var selectedUsers = top.dialog.dialogData.selectedDepartmentUsers;
                // 这里写处理逻辑
                if (selectedUsers && selectedUsers.length > 0) {
                    var multipleAssignees = '';
                    var multipleAssigneeNames = '';
                    for (var i = 0, item; item = selectedUsers[i++];) {
                        if (multipleAssignees.length) {
                            multipleAssignees += ',';
                            multipleAssigneeNames += ',';
                        }
                        multipleAssignees += item.userId;
                        multipleAssigneeNames += item.userName;
                    }
                    assignee.multipleAssignees = multipleAssignees;
                    assignee.multipleAssigneeNames = multipleAssigneeNames;
                } else {
                    assignee.multipleAssignees = '';
                    assignee.multipleAssigneeNames = '';
                }
                top.dialog.dialogData.selectedDepartmentUsers = [];
                $scope.$apply();
            }
        })
    }
    // 选择部门
    $scope.selectDepartments = function () {
        var assignee = $scope.oaNodeManage.assignee;
        top.dialog.dialogData.checkedDepartmentIds = !assignee.departments ? [] : assignee.departments.split(',');
        top.dialog.open({
            url: top.restAjax.path('route/department/list-tree-check', []),
            title: '选择组织部门【多选】',
            width: '400px',
            height: '400px',
            onClose: function () {
                var checkedDepartmentNodes = top.dialog.dialogData.checkedDepartmentNodes;
                if (checkedDepartmentNodes && checkedDepartmentNodes.length > 0) {
                    var departments = '';
                    var departmentNames = '';
                    for (var i = 0, item; item = checkedDepartmentNodes[i++];) {
                        if (departments.length > 0) {
                            departments += ',';
                            departmentNames += ',';
                        }
                        departments += item.id;
                        departmentNames += item.name;
                    }
                    assignee.departments = departments;
                    assignee.departmentNames = departmentNames;
                } else {
                    assignee.departments = '';
                    assignee.departmentNames = '';
                }
                top.dialog.dialogData.checkedDepartmentNodes = [];
                $scope.$apply();
            }
        });
    }
    // 选择角色
    $scope.selectRoles = function () {
        var assignee = $scope.oaNodeManage.assignee;
        top.dialog.dialogData.checkedRoleIds = !assignee.roles ? [] : assignee.roles.split(',');
        top.dialog.open({
            url: top.restAjax.path('route/role/list-tree-check', []),
            title: '选择角色【多选】',
            width: '400px',
            height: '400px',
            onClose: function () {
                var checkedRoleNodes = top.dialog.dialogData.checkedRoleNodes;
                if (checkedRoleNodes && checkedRoleNodes.length > 0) {
                    var roles = '';
                    var roleNames = '';
                    for (var i = 0, item; item = checkedRoleNodes[i++];) {
                        if (roles.length > 0) {
                            roles += ',';
                            roleNames += ',';
                        }
                        roles += item.id;
                        roleNames += item.name;
                    }
                    assignee.roles = roles;
                    assignee.roleNames = roleNames;
                } else {
                    assignee.roles = '';
                    assignee.roleNames = '';
                }
                top.dialog.dialogData.checkedRoleNodes = [];
                $scope.$apply();
            }
        });
    }
    // 选择职位
    $scope.selectPositions = function () {
        var assignee = $scope.oaNodeManage.assignee;
        top.dialog.dialogData.checkedPositionIds = !assignee.positions ? [] : assignee.positions.split(',');
        top.dialog.open({
            url: top.restAjax.path('route/position/list-tree-check', []),
            title: '选择职位【多选】',
            width: '400px',
            height: '400px',
            onClose: function () {
                var checkedPositionNodes = top.dialog.dialogData.checkedPositionNodes;
                if (checkedPositionNodes && checkedPositionNodes.length > 0) {
                    var positions = '';
                    var positionNames = '';
                    for (var i = 0, item; item = checkedPositionNodes[i++];) {
                        if (positions.length > 0) {
                            positions += ',';
                            positionNames += ',';
                        }
                        positions += item.id;
                        positionNames += item.name;
                    }
                    assignee.positions = positions;
                    assignee.positionNames = positionNames;
                } else {
                    assignee.positions = '';
                    assignee.positionNames = '';
                }
                top.dialog.dialogData.checkedPositionNodes = [];
                $scope.$apply();
            }
        });
    }

    // 更新代理人与候选人信息
    function updateAssignment() {
        // 更新手动指定单选代理人
        function updateStartAssignee() {
            assigneeProperty.value = {};
            assigneeProperty.value.assignment = {
                assignee: START_ASSIGNEE_USER,
                candidateUsers: []
            }
            $scope.updatePropertyInModel(assigneeProperty);
        }

        // 更新手动指定单选代理人
        function updateAssignee() {
            assigneeProperty.value = {};
            assigneeProperty.value.assignment = {
                assignee: ASSIGNEE_USER,
                candidateUsers: []
            }
            $scope.updatePropertyInModel(assigneeProperty);
        }

        // 多实例代理人变量
        function updateMultipleAssignee() {
            assigneeProperty.value = {};
            assigneeProperty.value.assignment = {
                assignee: MULTI_ASSIGNEE_USER,
                candidateUsers: []
            }
            $scope.updatePropertyInModel(assigneeProperty);
        }

        /**
         * 更新多实例
         */
        function updateMultipleInstance() {
            $scope.updatePropertyInModel(multiInstanceType);
            $scope.updatePropertyInModel(multiInstanceCollection);
            $scope.updatePropertyInModel(multiInstanceVariable);
            $scope.updatePropertyInModel(multiInstanceCondition);
        }

        /**
         * 更新并行
         */
        function updateParallel() {
            multiInstanceType.value = $scope.oaNodeManage.assignee.multipleType;
            multiInstanceCollection.value = MULTI_INSTANCE_COLLECTION;
            multiInstanceVariable.value = MULTI_INSTANCE_VARIABLE;
            if (assignee.completeCondition === 'allPass') {
                // 全部通过
                multiInstanceCondition.value = '${' + NR_OF_COMPLETED_INSTANCES + ' == ' + NR_OF_INSTANCES + '}'
            } else if (assignee.completeCondition === 'singlePass') {
                // 单人通过
                multiInstanceCondition.value = '${' + NR_OF_COMPLETED_INSTANCES + ' >= 1}'
            } else if (assignee.completeCondition === 'customPass') {
                // 通过多少人
                multiInstanceCondition.value = '${' + NR_OF_COMPLETED_INSTANCES + ' >= ' + assignee.completeCount + '}'
            } else {
                top.dialog.msg('多实例(完成)通过条件错误');
                return;
            }
            updateMultipleInstance();
        }

        /**
         * 更新串行
         */
        function updateSequential() {
            multiInstanceType.value = $scope.oaNodeManage.assignee.multipleType;
            multiInstanceCollection.value = MULTI_INSTANCE_COLLECTION;
            multiInstanceVariable.value = MULTI_INSTANCE_VARIABLE;
            multiInstanceCondition.value = '';
            updateMultipleInstance();
        }


        /**
         * 清空代理人候选人
         */
        function clearAssigneeAndCandidate() {
            assigneeProperty.value = {};
            $scope.updatePropertyInModel(assigneeProperty);
        }

        /**
         * 清空多实例配置
         */
        function clearMultipleInstance() {
            multiInstanceType.value = '';
            multiInstanceCollection.value = '';
            multiInstanceVariable.value = '';
            multiInstanceCondition.value = '';
            updateMultipleInstance();
        }

        var assignee = $scope.oaNodeManage.assignee;
        if ($scope.isFirstUserTask) {
            updateStartAssignee();
            return;
        }
        // 普通节点
        if (assignee.nodeType === 'normal') {
            // 清空多实例选项
            clearMultipleInstance();
            // 手动指定
            if (assignee.assigneeType === 'appoint') {
                // 单选
                if (assignee.assigneeCount === 'single') {
                    updateAssignee();
                    return;
                }
                // 多选
                if (assignee.assigneeCount === 'candidate') {
                    updateAssignee();
                    return;
                }
                return;
            }
            // 自动获取
            if (assignee.assigneeType === 'auto') {
                if (assignee.quickAssignee === 'starter') {
                    updateAssignee();
                    return;
                }
                updateAssignee();
                return;
            }
            if (assignee.assigneeType === 'form') {
                updateAssignee()
            }
            return;
        }

        if (assignee.nodeType === 'multiple') {
            // 清空代理人选项
            clearAssigneeAndCandidate();
            updateMultipleAssignee();
            // 并行
            if (assignee.multipleType === 'parallel') {
                updateParallel();
                return;
            }
            if (assignee.multipleType === 'sequential') {
                updateSequential();
                return;
            }
        }

    }

    /**
     * 更新任务监听器列表
     */
    function updateTaskListener() {
        taskListenerProperty.value = {}
        taskListenerProperty.value.taskListeners = $scope.oaNodeManage.oaUserTaskListeners;
        $scope.updatePropertyInModel(taskListenerProperty);
    }

    // Click handler for save button
    $scope.save = function () {
        var assignee = $scope.oaNodeManage.assignee;
        // 验证输入内容是否设置
        if (assignee.nodeType === 'normal') {
            if (assignee.assigneeType === 'appoint') {
                if (assignee.assigneeCount === 'single') {
                    if (!assignee.assignee) {
                        top.dialog.msg('请选择代理人');
                        return;
                    }
                }
                if (assignee.assigneeCount === 'candidate') {
                    if (!assignee.candidates) {
                        top.dialog.msg('请选择候选人');
                        return;
                    }
                }
            }
        }
        if (assignee.nodeType === 'multiple') {
            if (assignee.multipleType === 'parallel') {
                if (assignee.completeCondition === 'customPass') {
                    if (!assignee.completeCount) {
                        top.dialog.msg('请输入完成条件中的通过人数');
                        return;
                    }
                }
            }
            if (assignee.assigneeType === 'appoint') {
                if (!assignee.multipleAssignees) {
                    top.dialog.msg('请选择（多实例）代理人');
                    return;
                }
            }
        }
        if (assignee.assigneeType === 'auto') {
            if (assignee.autoAssignType === 'scope') {
                if (assignee.departmentType === 'appoint') {
                    if (!assignee.departments && !assignee.roles && !assignee.positions) {
                        top.dialog.msg('请选择部门、角色、职位中的至少一个类型');
                        return;
                    }
                }
                if (assignee.departmentType === 'belong') {
                    if (!assignee.roles && !assignee.positions) {
                        top.dialog.msg('请选择角色、职位中的至少一个类型');
                        return;
                    }
                }
            }
            if (assignee.autoAssignType === 'quick') {
                if (assignee.quickAssignee === 'previousNStepAssigneeSubordinatePosition') {
                    if (!assignee.previousNStep) {
                        top.dialog.msg('请确认获取前哪一步的代理人');
                        return;
                    }
                }
            }
        }
        if (assignee.assigneeType === 'form') {
            if (!assignee.assignee) {
                top.dialog.msg('请输入表单代理人表单字段名')
                return;
            }
            if (!(/[\w\d\_]+/g.test(assignee.assignee))) {
                top.dialog.msg('代理人表单字段名只能是 字母、数字、下划线 的组合');
                return;
            }
            assignee.assigneeName = ''
        }

        $scope.property.value = {};
        $scope.property.value = $scope.oaNodeManage;
        $scope.updatePropertyInModel($scope.property);

        updateAssignment();
        updateTaskListener();

        $scope.close();
    };

    $scope.cancel = function () {
        $scope.close();
    };

    // Close button handler
    $scope.close = function () {
        assigneeProperty.mode = 'read';
        taskListenerProperty.mode = 'read';
        $scope.property.mode = 'read';

        $scope.$hide();
    };

    // function initOaNodeManage() {
    if ($scope.property.value) {
        $scope.oaNodeManage = EDITOR.UTIL.deepClone($scope.property.value);
    }
    // }

    // 初始化开始节点
    function initStartNode() {
        for (var i = 0, node; node = childShapes[i++];) {
            if (node.stencil.id == 'StartNoneEvent') {
                startNode = node;
                break;
            }
        }
        if (!startNode) {
            top.dialog.msg('未找到开始节点，无法设置OA节点');
            $scope.close();
            return;
        }
        if (startNode.outgoing.length != 1) {
            top.dialog.msg('流程绘制错误，开始节点后只能有一个UserTask');
            $scope.close();
            return;
        }
    }

    // 是否是第一个开始节点
    function initOaNodeManage() {
        var firstUserTaskResourceId;
        for (var i = 0, node; node = childShapes[i++];) {
            if (node.stencil.id != 'SequenceFlow') {
                continue;
            }
            if (startNode.outgoing[0].resourceId == node.resourceId) {
                firstUserTaskResourceId = node.outgoing[0].resourceId;
                break;
            }
        }
        if (!firstUserTaskResourceId) {
            top.dialog.msg('流程绘制错误，开始节点后没有连线的UserTask');
            $scope.close();
            return;
        }
        // 赋值
        if ($scope.property.value) {
            $scope.oaNodeManage = EDITOR.UTIL.deepClone($scope.property.value);
        }
        $scope.isFirstUserTask = firstUserTaskResourceId == selection.resourceId;
        if ($scope.isFirstUserTask) {
            $scope.oaNodeManage.assignee.nodeType = 'normal';
            $scope.oaNodeManage.assignee.assigneeType = 'auto';
            $scope.oaNodeManage.assignee.autoAssignType = 'quick';
            $scope.oaNodeManage.assignee.quickAssignee = 'starter';
            return;
        }
    }

    // 初始化form表单ID
    function initFormId(callback) {
        $scope.oaNodeManage.formId = startNode.properties.formkeydefinition;
        if (!$scope.oaNodeManage.formId) {
            top.dialog.msg('开始节点未绑定表单，无法设置OA节点');
            $timeout(function () {
                $scope.close();
            }, 10)
            return;
        }
        callback();
    }

    // 初始化form表单
    function initFormField() {
        $http.get('api/form-field/list/form-id/' + $scope.oaNodeManage.formId).then(function (response) {
            var formFields = [];
            for (var i = 0, formField; formField = response.data[i++];) {
                var isVisible = true;
                var isEditable = true;
                var editHistory = 'noRecord';
                var autoBackFill = 'noBackFill';
                for (var j = 0, item; item = $scope.oaNodeManage.formFields[j++];) {
                    if (formField.fieldId === item.fieldId) {
                        isVisible = item.isVisible;
                        isEditable = item.isEditable;
                        editHistory = item.editHistory;
                        autoBackFill = item.autoBackFill;
                    }
                }
                formFields.push({
                    fieldId: formField.fieldId,
                    fieldName: formField.fieldName,
                    fieldExplain: formField.fieldExplain,
                    fieldTag: formField.fieldTag,
                    fieldType: formField.fieldType,
                    isVisible: isVisible,
                    isEditable: isEditable,
                    editHistory: editHistory,
                    autoBackFill: autoBackFill
                })
            }
            $scope.oaNodeManage.formFields = formFields;
        }, function (response) {
            top.dialog.msg(response.data.msg);
        })
    }

    // 初始化
    (function () {
        initStartNode();
        initOaNodeManage();
        initFormId(function () {
            initFormField();
        });
    })();

}];