/* * 版 本 PIT-ADMS V7.0.3 敏捷开发框架
 * Copyright (c) 2013-2018 Hexagon PPM
 * 创建人：chenkai
 * 日  期：2021-03-24
 * 描  述：通用选择人员
 */

var callType = request('callType');//1：流程界面直接选人，2：弹框中再选人
var textEleId = request('textEleId');//用户名称元素Id
var valueEleId = request('valueEleId');//用户Id元素Id
var mobileEleId = request('mobileEleId');//手机号码元素Id
var ProjectId = request('ProjectId');//项目ID
var isMult = request('isMult');//是否多选1多选 0单选，默认多选
var treeData = [];//已经选择的用户 需要父级界面定义一个用户defaultSelectUser 多个用英文逗号分开
var acceptClick;//结束回调方法;

//局部事件
var refreshGirdData;
var Select;

var bootstrap = function ($, learun) {
    "use strict";
    var companyId = '';
    var page = {
        init: function () {
            if (callType != "1" && callType != "2") {
                learun.alert.error("callType参数异常");
                return false;
            }
            page.bind();
        },
        bind: function () {
            var initUserString;

            if (callType == "1") {
                if ($(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('iframe')[0]) {
                    initUserString = $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('iframe')[0].contentWindow.defaultSelectUser;
                } else {
                    initUserString = $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.defaultSelectUser;
                }
            } else if (callType == "2") {
                initUserString = parent.$("#" + top.layer_form.name + "")[0].contentWindow.defaultSelectUser;//获取父窗口选中已经保存或选择的人员
            }
            if (initUserString) {
                if (initUserString.length > 0) {
                    //treeData = retreeData;
                    //通过接口获取
                    learun.httpAsync('GET', top.$.rootUrl + '/LR_OrganizationModule/User/GetEntityListByUserIds', { keyValue: initUserString }, function (data) {
                        if (!!data) {
                            $.each(data, function (id, item) {
                                treeData.push({ id: item.F_UserId, text: item.F_RealName });
                            });
                            //绑定已经选择的用户
                            $('#userTree').lrtree({
                                data: treeData
                            });
                        }
                    });
                }
            }
            page.initGrid();

            //单位选择下拉框
            $('#company_select').lrselect({
                // 字段
                value: "F_CompanyId",
                text: "F_FullName",
                title: "F_FullName",
                //type: 'multiple',
                // 展开最大高度
                maxHeight: 200,
                // 是否允许搜索
                allowSearch: true,
                // 访问数据接口地址
                url: top.$.rootUrl + '/LR_OrganizationModule/Company/GetList',
                // 访问数据接口参数
                param: null,
                select: function (item) {
                    if (!item || item.value == '-1') {
                        companyId = '';
                    }
                    else {
                        companyId = item.F_CompanyId;
                    }
                    page.search({ companyId: companyId });
                }
            });

            // 查询
            $('#btn_Search').on('click', function () {
                var keyword = $('#txt_Keyword').val();
                page.search({ keyword: keyword, companyId: companyId });
            });
        },
        //初始化用户列表
        initGrid: function () {
            $('#gridtable').jfGrid({
                url: top.$.rootUrl + '/LR_OrganizationModule/User/GetCommonSelectUsers',
                headData: [
                    {
                        label: "选择", name: "F_UserId", index: "IsCheck", width: 60, align: "center", frozen: true,
                        formatter: function (cellvalue, row, op, $cell) {
                            var rowindex = parseInt($cell.attr('rowindex'));
                            return "<input value='" + row.F_RealName + "' title='" + row.F_RealName + "'  id='" + row.F_UserId + "' name='myname' type='checkbox' style='cursor: pointer;margin-top: 8px;' onclick='Select(\"" + rowindex + "\",\"" + row.F_UserId + "\",\"" + row.F_RealName + "\",\"" + row.F_Mobile + "\")'>";
                        }
                    },
                    { label: '账号', name: 'F_Account', width: 150, align: 'center', frozen: true },
                    { label: '姓名', name: 'F_RealName', width: 100, align: 'center', frozen: true },
                    { name: '' }
                ],
                isPage: true,
                reloadSelected: true,
                mainId: 'F_UserId',
                onRenderComplete: function (data) {
                    //默认已经选中的用户
                    var obj = document.getElementsByName("myname");
                    for (var i = 0; i < obj.length; i++) {
                        if (treeData.length > 0) {
                            var temp = treeData.find(function (x) {
                                return x.id === obj[i].id
                            });
                            if (temp != undefined && temp != "") {
                                obj[i].checked = true;
                            } else {
                                obj[i].checked = false;
                            }
                        }
                    }
                },
            });
            page.search();
        },
        //查询
        search: function (param) {
            param = param || {};
            param.ProjectId = ProjectId;
            $('#gridtable').jfGridSet('reload', { queryJson: JSON.stringify(param) });
        }
    };
    //刷新列表
    refreshGirdData = function () {
        $('#gridtable').jfGridSet('reload');
    };
    //选中用户
    Select = function (rowindex, userId, userName, mobile) {
        var tempdata = {
            id: userId,
            text: userName,
            title: userName,
            mobile: mobile,
            parentId: 0,
            showcheck: false,
            ChildNodes: null,
            isSelectUser: true
        };
        var obj = $('#gridtable').context.getElementsByName("myname");
        for (var i = 0; i < obj.length; i++) {
            if (userId == obj[i].id && obj[i].checked) {
                treeData.push(tempdata);
            } else if (userId == obj[i].id && obj[i].checked == false) {
                for (var j = 0; j < treeData.length; j++) {
                    if (treeData[j].id == userId) {
                        treeData.splice(j, 1);
                    }
                }
            }
        }
        $('#userTree').lrtree({
            data: treeData
        });
    };
    //选中用户点击确定
    acceptClick = function (callBack) {
        var userlistselected = [];
        var UserIds = "";
        var UserNames = "";
        var Mobiles = "";
        if (treeData.length == 0) {
            learun.alert.error("至少选择一位人员");
            return false;
        } else if (isMult == "0" && treeData.length > 1) {
            learun.alert.error("有且只能选择一位人员");
            return false;
        }
        else {
            for (var j = 0; j < treeData.length; j++) {
                userlistselected.push(treeData[j].id);
                UserNames += treeData[j].text + ',';
                UserIds += treeData[j].id + ',';
                Mobiles += treeData[j].mobile + ',';
            }
            if (UserNames) {
                UserNames = UserNames.substring(0, UserNames.lastIndexOf(','));
            }
            if (UserIds) {
                UserIds = UserIds.substring(0, UserIds.lastIndexOf(','));
            }
            if (Mobiles) {
                Mobiles = Mobiles.substring(0, Mobiles.lastIndexOf(','));
            }
            if (callType == "1") {
                if ($(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('iframe')[0]) {
                    if (valueEleId != "" && $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('iframe')[0].contentWindow.$('#' + valueEleId)) {
                        $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('iframe')[0].contentWindow.$('#' + valueEleId).val(UserIds);
                    }
                    if (textEleId != "" && $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('iframe')[0].contentWindow.$('#' + textEleId)) {
                        $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('iframe')[0].contentWindow.$('#' + textEleId).val(UserNames);
                    }
                    $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('iframe')[0].contentWindow.defaultSelectUser = UserIds;
                } else {
                    if (valueEleId != "" && $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('#' + valueEleId)) {
                        $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('#' + valueEleId).val(UserIds);
                    }
                    if (textEleId != "" && $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('#' + textEleId)) {
                        $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.$('#' + textEleId).val(UserNames);
                    }
                    $(parent.document).find("li .lr-frame-iframe,.active")[3].contentWindow.defaultSelectUser = UserIds;
                }
            } else if (callType == "2") {
                if (valueEleId != "" && parent.$("#" + top.layer_form.name + "")[0].contentWindow.$('#' + valueEleId)) {
                    parent.$("#" + top.layer_form.name + "")[0].contentWindow.$('#' + valueEleId).val(UserIds);//回写用户ID到父级窗口
                }
                if (textEleId != "" && parent.$("#" + top.layer_form.name + "")[0].contentWindow.$('#' + textEleId)) {
                    parent.$("#" + top.layer_form.name + "")[0].contentWindow.$('#' + textEleId).val(UserNames);//回写用户名称到父级窗口
                }
                if (mobileEleId != "" && parent.$("#" + top.layer_form.name + "")[0].contentWindow.$('#' + mobileEleId)) {
                    parent.$("#" + top.layer_form.name + "")[0].contentWindow.$('#' + mobileEleId).val(Mobiles);//回写手机号码到父级窗口
                }
                
                parent.$("#" + top.layer_form.name + "")[0].contentWindow.defaultSelectUser = UserIds;//回写已选择用户tree到父级窗口
            }
            learun.layerClose(window.name);

            // 保存成功后才回调
            if (!!callBack) {
                callBack();
            }
        }
    }
    page.init();
}

//左侧树删除
function Del(id) {
    for (var j = 0; j < treeData.length; j++) {
        if (treeData[j].id == id) {
            treeData.splice(j, 1);
        }
    }
    var obj = $('#gridtable').context.getElementsByName("myname");
    for (var i = 0; i < obj.length; i++) {
        if (id == obj[i].id && obj[i].checked) {
            obj[i].checked = false;
        }
    }
    $('#userTree').lrtree({
        data: treeData
    });
}