let form, layer, combotree, dtree;
let objParam;
let dataObj = null;
let selectDtreeObj = null;
function getData() {
    if (Number(objParam.type) === 0) {
        $("#form").removeAttr("style");
        $("#form2").remove();
        $("#form3").remove();
        $("#form4").remove();
        $("#form5").remove();
        getProList();
        // getLeaderList();
    } else if (Number(objParam.type) === 1) {
        $("#form").remove();
        $("#form2").removeAttr("style");
        $("#form3").remove();
        $("#form4").remove();
        $("#form5").remove();
        getOutSourceSelected();
    } else if (Number(objParam.type) === 2) {
        $("#form").remove();
        $("#form2").remove();
        $("#form3").removeAttr("style");
        $("#form4").remove();
        $("#form5").remove();
        let html = setFormHtml(1);
        $("#addType").remove();
        $("#dataSource").append(html);
        getPersonLibary();
        layui.form.render();
    } else if (Number(objParam.type) === 3) {
        $("#form").remove();
        $("#form2").remove();
        $("#form3").remove();
        $("#form4").removeAttr("style");
        $("#form5").remove();
        getDataDetails();
    } else if (Number(objParam.type) === 4) {
        $("#form").remove();
        $("#form2").remove();
        $("#form3").remove();
        $("#form4").remove();
        $("#form5").removeAttr("style");
    }
}

function setParams(obj) {
    objParam = JSON.parse(obj);
    layui
        .extend({
            dtree: `${ctxPath}/statics/layui/layui_ext/dtree/dtree`, // {/}的意思即代表采用自有路径，即不跟随 base 路径
        })
        .use(["dtree", "form", "layer"], function () {
            form = layui.form;
            layer = layui.layer;
            dtree = layui.dtree;

            form.verify({
                idCard: function (value, item) {
                    if (value) {
                        let pass =
                            /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/;
                        let flag = pass.test(value);
                        if (!flag) {
                            return "身份证号码格式不正确";
                        }
                    }
                },
                phone: function (value, item) {
                    if (value) {
                        let pass = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
                        let flag = pass.test(value);
                        if (!flag) {
                            return "联系电话格式不正确";
                        }
                    }
                },
            });
            form.on("submit(formData)", function (data) {
                submitApply(data);
            });
            form.render();
            getData();
        });
}

// 项目下拉选
function getProList() {
    dtree.render({
        elem: "#proId",
        url: `${ctxPath}` + "/organizational/getDeptSelected",
        dataFormat: "list", //配置data的风格为list
    });
    dtree.on("node('proId')", function (obj) {
        if (obj.param.parentId == "0") {
            layer.msg("请选择项目，不能选择总公司");
            return;
        }
        selectDtreeObj = {
            id: obj.param.nodeId,
            lkId: obj.param.nodeId,
            name: obj.param.context,
            title: obj.param.context,
            level: obj.param.level,
            parentId: obj.param.parentId,
            tableSource: "pm_dept",
        };
    });
}

// 负责人下拉选
function getLeaderList() {
    $.ajax({
        url: `${ctxPath}` + "/organizational/getLeaderSelect",
        type: "post",
        data: {},
        dataType: "JSON",
        success: function (result) {
            if (result.res === 1) {
                setSelectValue(result.obj, "personInChargeId", "id", "name");
            }
        },
    });
}

// 外包商下拉选
function getOutSourceSelected() {
    $.ajax({
        url: `${ctxPath}` + "/organizational/getOutSourceSelected",
        type: "post",
        data: { id: objParam.id ? objParam.id : null },
        dataType: "JSON",
        success: function (result) {
            if (result.res === 1) {
                setSelectValue(result.obj, "subId", "lkId", "name");
            }
        },
    });
}

// 退场人员下拉选
function getPersonLibary(type) {
    $.ajax({
        url: `${ctxPath}` + "/organizational/getAddUserSelected",
        type: "post",
        data: { id: objParam.id, isAdd: objParam.type === 2 ? 1 : null },
        dataType: "JSON",
        success: function (result) {
            // console.error(result)
            if (result.res === 1) {
                setSelectValue(result.obj, "leaderId", "idCard", "userName");
                if (objParam.type === 3) {
                    $("#leaderId").val(dataObj.idCard);
                    layui.form.render();
                }
            }
        },
    });
}

// 班组详情
function getDataDetails() {
    $.ajax({
        url: `${ctxPath}` + "/organizational/getDataDetails",
        type: "post",
        data: { id: objParam.id },
        dataType: "JSON",
        success: function (result) {
            console.error(result);
            if (result.res === 1) {
                setFormData(result.obj);
                dataObj = result.obj;
            }
        },
    });

    // 表单赋值
    function setFormData(obj) {
        let dataSource = obj.dataSource;
        $('input[name="dataSource"][value="' + dataSource + '"]').prop(
            "checked",
            true
        );
        if (dataSource === "1") {
            // 人员库选择
            let html = setFormHtml(1);
            $("#addType").remove();
            $("#dataSource").append(html);
            getPersonLibary();
        } else if (dataSource === "2") {
            let html = setFormHtml(2);
            $("#chooseLibary").remove();
            $("#dataSource").append(html);
        }
        form.val("formInfo", obj);
        layui.form.render();
    }
}

function setSelectValue(list, selectName, code, nameCode) {
    let html = '<option value="">请选择</option>';
    if (list && list.length > 0) {
        $.each(list, function (index, item) {
            html +=
                "<option value='" +
                item[code] +
                "' item='" +
                JSON.stringify(item) +
                "'>" +
                item[nameCode] +
                "</option>";
        });
    }
    $("#" + selectName)
        .empty()
        .append(html);
    layui.form.render();
}

function saveData2() {
    $("#formSubmit").trigger("click");
}

// 提交
function submitApply(data) {
    let loadingMsg = layer.msg("正在提交保存,请稍等...", {
        icon: 16,
        shade: 0.01,
        time: "0",
    });
    let item = {};
    let url = `${ctxPath}` + "/organizational/addData";
    if (Number(objParam.type) === 0) {
        // 项目
        if (selectDtreeObj == null) {
            layer.msg("请选择项目");
            return;
        }
        item = {
            ...selectDtreeObj,
            parentId: objParam.id,
            level: 3,
            tableSource: "pm_dept",
            // userId : data.field.personInChargeId,
            userId: "",
            userName: $("#personInChargeId").val(),
        };
    } else if (Number(objParam.type) === 1) {
        // 外包商
        item = JSON.parse($("#subId").find("option:checked").attr("item"));
        item.level = 4;
        item.parentId = objParam.id;
        item.tableSource = "project_assignment";
        item.lkId = $("#subId").val();
    } else if (Number(objParam.type) === 2) {
        // 新增班长
        item = Object.assign({}, data.field);
        item.name = data.field.name;
        item.userName = $("#userNameNew").val();
        item.level = 5;
        item.parentId = objParam.id;
        item.tableSource = "pm_dept";
    } else if (Number(objParam.type) === 3) {
        // 更换班组长
        url = `${ctxPath}` + "/organizational/updateLeader";
        item = Object.assign({}, data.field);
        item.name = data.field.name;
        item.level = 5;
        item.parentId = objParam.id;
        item.id = dataObj.id;
    } else if (Number(objParam.type) === 4) {
        // 新增事业部/职能部门
        item = Object.assign({}, data.field);
        item.level = 2;
        item.parentId = objParam.id;
        url = `${ctxPath}` + "/organizational/addDept";
    }
    $.ajax({
        url: url,
        type: "POST",
        data: JSON.stringify(item),
        dataType: "json",
        contentType: "application/json",
        beforeSend: function () {
            $(".save").addClass("layui-btn-disabled").attr("disabled", true);
            $(".cancel").addClass("layui-btn-disabled").attr("disabled", true);
        },
        success: function (result) {
            layer.close(loadingMsg); // 关闭提示层
            $(".save")
                .removeClass("layui-btn-disabled")
                .attr("disabled", false);
            $(".cancel")
                .removeClass("layui-btn-disabled")
                .attr("disabled", false);
            console.error(result);
            if (result.res === 1) {
                parent.layer.msg(result.obj, { icon: 1 });
                closePage(1);
            } else {
                layer.msg(result.resMsg, { icon: 2 });
            }
        },
        error: function (result) {
            layer.close(loadingMsg); // 关闭提示层
            layer.msg("服务异常，请稍后重试", {
                icon: 16,
                scrollbar: false,
                time: 2000,
            });
            $(".save")
                .removeClass("layui-btn-disabled")
                .attr("disabled", false);
            $(".cancel")
                .removeClass("layui-btn-disabled")
                .attr("disabled", false);
        },
    });
}

// 关闭页面
function closePage(type) {
    let index = parent.layer.getFrameIndex(window.name); // 先得到当前 iframe层的索引
    if (type === 1) {
        window.parent.reloadTreeTable();
    }
    parent.layer.close(index); // 再执行关闭
}

function showPersonPage() {
    let layerIndex = layer.open({
        type: 2,
        title: "人员库",
        shade: 0.3,
        area: ["98%", "98%"],
        scrollbar: true,
        btn: ["确定"],
        move: true,
        anim: 2,
        shadeClose: false,
        content: `./teamPerson.html`,
        success: function (layero, index) {},
        yes: function (index, layero) {
            //提交子页面时执行
            // 获取弹出层中的form表单元素
            var formSubmit = layer.getChildFrame("form", index);
            // 查找class样式为submitBtn的按钮
            let submited = formSubmit.find("button.subBtn");
            // 触发点击事件，会对表单进行验证，验证成功则提交表单，失败则返回错误信息
            submited.click();
        },
        end: function () {
            let data = localStorage.getItem("teamPersonSelect");
            if (data) {
                let obj = JSON.parse(data);
                //根据 name属性 赋值
                $("#userName").val(obj[0].name);
                $("#idCard").val(obj[0].idCard);
                $("#userPhone").val(obj[0].phone);
                $("#sex")
                    .find(
                        'option[value="' + (obj[0].sex === "男" ? 1 : 2) + '"]'
                    )
                    .attr("selected", true);
                layui.form.render();
                localStorage.removeItem("teamPersonSelect");
            }
        },
    });
}
