var _person = {}
var _hrOrgUnit = {}
var _HRBizDefine = [] // 用户设置的变动操作

var isSameDatePersonChange = null
//是否一天多次变动 是，最后工作日等于离职日期；
//false：根据 isDefaultSameday判断最后工作日和离职日期是否同一天
var isDefaultSameday = null
//最后工作日和离职日期是否同一天（ true：同一天；false：最后工作日是离职日期前一天）
var isResignNextMonth = null
_this.pageinit = function () {
  initHeader()
  checkIsExistResignBill()
  // getExistResignBillInfo()
  // $("#btnAddnew").hide()
  // mbos('editgrid1').addEntry()
  if (requestParam.operateState === "ADDNEW") {
    mbos('editgrid1').addEntry()
    setTimeout(function () {
      setBillId()
      CheckDefaultSameDayService("")
      getHRBizDefineByUiClass()
    }, 1000)
  }

  mbos("applicationHistory").bind("click", function () {
    mbos.ui.open({
      path: mbos.pageInfo.path,
      name: "bill.listui",
    });
  })

  $("#application_img").on('error', function () {
    $(this).attr('src', '/mbos/store/4000148/'+mbos.pageInfo.path+'/default.png');
  });
  
}


_this.edit = function (event) {
  return page.edit && page.edit(event);

}
_this.addnew = function (event) {
  return page.addnew && page.addnew(event);
}
_this.save = function (event) {
  
  //202503加入社保数据校验;
  var opValiflag =  opValidate();
  if(!opValiflag){
    return;
  }
  var vali = mbos.ng.invokeAllScope("validate", { method: "save" });
  if (!vali) {
    return;
  }
  if (event.isvaliSuccess === false) {
    return;
  }

  if (requestParam.operateState === "ADDNEW") {
    mbos("billState").value({ isenum: true, value: 0 })
  }
  
  function _save() {
    return CheckResignBillInfoService(function () { save(event) })
  }
  //弱校验提示
  CheckWeakService(_save);
  //CheckResignAssign(_save)
  
}
_this.submit = function (event) {
  //202503加入社保数据校验;
  var opValiflag =  opValidate();
  if(!opValiflag){
    return;
  }

  var vali = mbos.ng.invokeAllScope("validate", { method: "submit" });
  if (!vali) {
    return;
  }
  mbos("billState").value({ isenum: true, value: 1 })
  
  
  function _submit() {
    return CheckResignBillInfoService(function () { submit(event) })
  }
  //弱校验提示
  CheckWeakService(_submit);
  // CheckResignAssign(_submit)
  
}

_this.back = function (event) {
  return page.back && page.back(event);
}

_this.afterSave = function (e) {
  if (requestParam.operateState === "ADDNEW") {
    mbos.ui.open({
      path: mbos.pageInfo.path,
      name: "application.editui",
      params: {
        billID: e.keyValue,
        operateState: "EDIT"
      }
    });
  } else {

  }
}
mbos('entity').bind('afterLoad', function () {
  if (requestParam.operateState !== "ADDNEW") {
    getHRBizDefineByUiClass()
  }
})

// 获取变动操作联动数据
function getHRBizDefineByUiClass() {
  mbos.eas.invokeScript({
    name: "commonOSFservice",
    param: ['getHRBizDefineByUiClass', JSON.stringify({ uiClass: "com.kingdee.eas.hr.affair.app.ResignBizBill.form" })],
    success: function (res) {
      _HRBizDefine = res
      var { outEmpType, affairActionReason, variationReason } = res[0] || {outEmpType:[], affairActionReason: [], variationReason: []}
      var first = res.map((item) => "'" + item.number + "'");
      var sec = outEmpType.map((item) => "'" + item.number + "'");
      var thrid = affairActionReason.map((item) => "'" + item.number + "'");
      var fourth = variationReason.map((item) => "'" + item.number + "'");
      if (requestParam.operateState === "ADDNEW" && res.length) {
        mbos("entrys.hrBizDefine", 0).value({ name: res[0].name, id: res[0].id, number: res[0].number });
        if (sec.length === 1) mbos("entrys.oldEmpType", 0).value(outEmpType[0])
        if (thrid.length === 1) mbos("entrys.affairActionReason", 0).value(affairActionReason[0])
        if (fourth.length === 1) mbos("entrys.variationReason", 0).value(variationReason[0])
      }
      // 用户设置的F7选项为空时， 把过滤条件设成xnull, 否则会全部显示
      if (first.length === 0) { first = ['"xnull"'] }
      if (sec.length === 0) { sec = ['"xnull"'] }
      if (thrid.length === 0) { thrid = ['"xnull"'] }
      if (fourth.length === 0) { fourth = ['"xnull"'] }
      // F7 选项 过滤
      mbos("entrys.hrBizDefine", 0).attr('dynamicFilter', 'number in (' + first.join(",") + ')');
      mbos("entrys.oldEmpType", 0).attr('dynamicFilter', 'number in (' + sec.join(",") + ')');
      mbos("entrys.affairActionReason", 0).attr('dynamicFilter', 'number in (' + thrid.join(",") + ')');
      mbos("entrys.variationReason", 0).attr('dynamicFilter', 'number in (' + fourth.join(",") + ')');

    },
    error: function (data) {
      if (typeof (data) == "string") {
        mbos.msgBox.showError("", data);
      } else {
        mbos.msgBox.showError({ ...data, msg: "" });
      }
    }
  })
}


_this.bizdatachange = function (event) {
  // isSameDatePersonChange
  //是否一天多次变动 是，最后工作日等于离职日期；
  //false：根据 isDefaultSameday判断最后工作日和离职日期是否同一天
  //isDefaultSameday
  var value = event.new_value
  if (!value) return

  CheckDefaultSameDayService(value, callback)

  function callback() {
    var nextDate = "";
    if (isSameDatePersonChange) {
      mbos("entrys.leftCompanyDate", 0).value(value);
    } else {
      if (isDefaultSameday) {
        mbos("entrys.leftCompanyDate", 0).value(value)
      } else {
        var prev = getPrevDate(value)
        mbos("entrys.leftCompanyDate", 0).value(prev)
      }
    }
  }

}

//后一天
function getNextDate(value) {
  var date = new Date(value)
  var nextDate =  new Date(date.getTime() + 24 * 60 * 60 * 1000)
  nextDate = nextDate.format('yyyy-MM-dd')
  return nextDate
}

function getPrevDate(value, day) {
  var date = new Date(value)
  var prevDate = day ? new Date(date.getTime() + day * 24 * 60 * 60 * 1000) : new Date(date.getTime() - 24 * 60 * 60 * 1000)
  var s1 = prevDate.format('yyyy-MM-dd')
  return s1
}

_this.leftdatechange = function (event) {
  var value = event.new_value
  var bizDate = mbos("entrys.bizDate", 0).value()
  if (!bizDate) {
    var param1 = { title: localeResource.msg50 };
    mbos.ui.showInfo(param1);
    return
  }
  var prev = getPrevDate(bizDate)
  if (isSameDatePersonChange) {
    if (value !== bizDate) {
      var param2 = { title: localeResource.msg43 };
      mbos.ui.showInfo(param2);
      mbos("entrys.leftCompanyDate", 0).value(bizDate);
       //禁用用户日期
       	nextDate = getNextDate(bizDate);
        mbos("entrys.forbidUserDate", 0).value(nextDate);
    }
  } else {
    if (value !== bizDate && value !== prev) {
      var param3 = { title: localeResource.msg44 };
      mbos.ui.showInfo(param3);
      mbos("entrys.leftCompanyDate", 0).value(bizDate);
       //禁用用户日期
       	nextDate = getNextDate(bizDate);
        mbos("entrys.forbidUserDate", 0).value(nextDate);
    }else{
       //禁用用户日期
       	nextDate = getNextDate(value);
        mbos("entrys.forbidUserDate", 0).value(nextDate);
    }
  }
}


mbos('page').bind('afterRendered', function () {

})


mbos("page").bind("afterSave", function (e) {
  var param1 = { title: localeResource.msg45 };
  mbos.ui.showInfo(param1);

  if (requestParam.operateState === "ADDNEW") {
    mbos.ui.open({
      path: mbos.pageInfo.path,
      name: "application.editui",
      params: {
        billID: e.keyValue,
        operateState: "EDIT"
      }
    });
  }
})

mbos("page").bind("afterSubmit", function (e) {
  var param1 = { title: localeResource.msg46 };
  mbos.ui.showInfo(param1);
  mbos.ui.open({
    path: mbos.pageInfo.path,
    name: "bill.listui",
    params: {
      billID: mbos("entity").value().id,
    }
  });
})

//保存，提交弱校验提示
function CheckWeakService(callback) {
  initEntityDataBeforeRequest()
  var data = mbos('entity').data

  mbos.eas.invokeScript({
    name: "commonOSFservice",
    param: ['checkWeakHireOrFlucExisService', JSON.stringify({ model: data })],
    success: function (res) {
      if (res.errorCode == '1') {
          mbos.ui.showConfirm({
            title: localeResource.msg53,
            msg: res.msg,
            callback: function (data) {
              if (data == 0) {
                //点击确定
                  CheckResignAssign(callback)
                //callback && callback()
              }
            }
          });

      } else {
         CheckResignAssign(callback)
      }
    },
    error: function (data) {
      if (typeof (data) == "string") {
        mbos.msgBox.showError("", data);
      } else {
        mbos.msgBox.showError({ ...data, msg: "" });
      }
    }
  })
}

function setBillId() {
  var param = [];
  param[0] = mbos('entity').data.bosType;
  mbos.eas.invokeScript({
    name: "getbillid",
    param: param,
    success: function (data) {
      mbos('entity').data.id = data;
    }
  })
}


function initEntityDataBeforeRequest() {
  mbos("hrOrgUnit").value(_hrOrgUnit)
  mbos('entrys.person', 0).value(_person)
  mbos("applier").value(_person)
  mbos("isMultiEntry").value(false)
  var data = mbos('entity').data
  data._entityName = "com.kingdee.eas.hr.affair.app.ResignBizBill"
  data.ismobile = "true"
}


// 获取头部信息
function initHeader() {
  mbos.eas.invokeScript({
    name: "commonOSFservice",
    param: ['getMobileUserInfoService', JSON.stringify({})],
    success: function (res) {
      var { personName, companyName, photo = "xxx", positionName, departmentName, personNumber, hrOrgUnit } = res
      _person.name = personName
      _person.id = easContext.person.id
      console.log(easContext.person)
      _person.bosType = easContext.person.bosType
      _hrOrgUnit = hrOrgUnit // id name

      $("#applicationHistory").text(localeResource.msg7)
      console.log($("#application_number"), personNumber, "per")
      $("#application_img").attr("src", photo ? "data:image/png;base64," + photo : '/mbos/store/4000148/'+mbos.pageInfo.path+'/default.png')
      $("#application_name").text(personName)
      $("#application_number").text(personNumber)
      $("#application_job").text(positionName + (departmentName ? (" | " + departmentName) : ""))
      $("#application_company").text(companyName);
      mbos("entrys_oldAdminOrg", 0).value({ name: res.adminName, id: res.adminId });
      mbos("entrys_oldPosition", 0).value({ name: res.positionName, id: res.positionId });
      mbos("entrys_oldJobGrade", 0).value({ name: res.jobGradeName, id: res.jobGradeId });
      mbos("entrys_oldJobLevel", 0).value({ name: res.jobLevelName, id: res.jobLevelId });
      $(".header_container").css("visibility", "visible")

      if (requestParam.operateState === "ADDNEW") {
        GetResignEmpBillNum()
      }
      setTimeout(function(){
          var dataSubmit = mbos('entity').value();
          mbos('nextperson1').checkParticipantPerson({
            editdata: dataSubmit,
            callback: function(){
              var nextPerson = mbos('entity').data.workflowNextPerson;
            }
          }); 
      },1000);
    },
    error: function (e) {
      $("#applicationHeader").hide()
    }
  })
}

//是否存在在途的单据
function getExistResignBillInfo() {
  mbos.eas.invokeScript({
    name: "commonOSFservice",
    param: ['GetExistResignBillInfoService', JSON.stringify({})],
    success: function (res) {
      if (res.isExist) {
        mbos.ui.open({
          path: mbos.pageInfo.path,
          name: "billDetail.editui",
          params: {
            billID: mbos("entity").value().id,
          }
        });
      }
    },
    error: function (e) {
      console.log(e);
    }
  })
}

//检查员工有待办任务时是否允许提交离职申请
function CheckResignAssign(callback) {
  initEntityDataBeforeRequest()
  var data = mbos('entity').data
  console.log(data, "检查员工有待办任务时是否允许提交离职申请 data--------")

  mbos.eas.invokeScript({
    name: "commonOSFservice",
    param: ['CheckResignAssignService', JSON.stringify({ model: data })],
    success: function (res) {
      var { isContainAssign, isResignCheck, assignMsg } = res
      if (isContainAssign) {
        if (isResignCheck) {
          mbos.ui.showConfirm({
            title: assignMsg,
            msg: "",
            callback: function (data) {
              if (data == 0) {
                callback && callback()
              }
            }
          });
        } else {
          mbos.ui.showInfo({ title: assignMsg, msg: "" });
        }
      } else {
        callback && callback()
      }
    },
    error: function (data) {
      if (typeof (data) == "string") {
        mbos.msgBox.showError("", data);
      } else {
        mbos.msgBox.showError({ ...data, msg: "" });
      }
    }
  })
}

// 保存和提交前校验业务数据
function CheckResignBillInfoService(callback, fallback) {
  var data = mbos('entity').data
  mbos.eas.invokeScript({
    name: "commonOSFservice",
    param: ['CheckResignBillInfoService', JSON.stringify({ model: data })],
    success: function (res) {
      callback && callback()
    },
    error: function (data) {
      if (typeof (data) == "string") {
        mbos.msgBox.showError("", data);
      } else {
        mbos.msgBox.showError({ ...data, msg: "" });
      }
    }
  })
}


// 是否申请记录存在单据
function checkIsExistResignBill() {
  mbos.eas.invokeScript({
    name: "commonOSFservice",
    param: ['IsExistResignBillRecordsService', JSON.stringify({})],
    success: function (res) {
      if (res.isExist) {
        $("#applicationHistory").show()
      }
    },
    error: function (e) {
      console.log(e);
    }
  })
}


// 获取单据编号
function GetResignEmpBillNum() {
  var data = {
    hrOrgUnitId: _hrOrgUnit.id,
    businessType: 3,
    personId: _person.id
  }
  mbos.eas.invokeScript({
    name: "commonOSFservice",
    param: ['GetResignEmpBillNumService', JSON.stringify(data)],
    success: function (res) {
      if (res.respObj) {
        mbos('number').value(res.respObj)
      } else {
        mbos('number').show()
      }
    },
    error: function (data) {
      if (typeof (data) == "string") {
        mbos.msgBox.showError("", data);
      } else {
        mbos.msgBox.showError({ ...data, msg: "" });
      }
    }
  })
}

_this.bdczchange = function (event) {
  console.log(_HRBizDefine)
  console.log(event)
  var { outEmpType, affairActionReason, variationReason } = _HRBizDefine.find((item) => item.id === event.new_value.id) || { outEmpType: [], affairActionReason: [], variationReason: [] }
  var sec = outEmpType.map((item) => "'" + item.number + "'");
  var thrid = affairActionReason.map((item) => "'" + item.number + "'");
  var fourth = variationReason.map((item) => "'" + item.number + "'");
  if (sec.length === 1) mbos("entrys.oldEmpType", 0).value(outEmpType[0])
  if (thrid.length === 1) mbos("entrys.affairActionReason", 0).value(affairActionReason[0])
  if (fourth.length === 1) mbos("entrys.variationReason", 0).value(variationReason[0])

  if (sec.length === 0) { sec = ['"xnull"'] }
  if (thrid.length === 0) { thrid = ['"xnull"'] }
  if (fourth.length === 0) { fourth = ['"xnull"'] }

  mbos("entrys.oldEmpType", 0).attr('dynamicFilter', 'number in (' + sec.join(",") + ')');
  mbos("entrys.affairActionReason", 0).attr('dynamicFilter', 'number in (' + thrid.join(",") + ')');
  mbos("entrys.variationReason", 0).attr('dynamicFilter', 'number in (' + fourth.join(",") + ')');
}

function getEditData() {
  mbos('entity').data.fromMbos = true;
  return mbos('entity').data;
}

function save(e) {
  var vali = mbos.ng.invokeAllScope("validate", { method: "save" });
  if (!vali) {
    return;
  }
  if (e.isvaliSuccess === false) {
    return;
  }
  // this  should be a init Action!  TODO
  mbos.post({
    url: "/mbos/editpage/save",
    param: {
      "bostype": getEditData().bosType,
      "model": JSON.stringify(getEditData()),
      "uiname": requestParam.name
    },
    success: function (data) {
      event = event || {};
      angular.extend(event, data);
      mbos.page.fire("afterSave", event);
    },
    error: function (data) {
      if (typeof (data) == "string") {
        mbos.msgBox.showError("", data);
      } else {
        mbos.msgBox.showError({ ...data, msg: "" });
      }
    }
  });
}


function submit(e) {
  console.log(111111)
  var vali = mbos.ng.invokeAllScope("validate", { method: "submit" });
  if (!vali) {
    return;
  }
  if (e.isvaliSuccess === false) {
    return;
  }
  //
  if (requestParam.isfromlcjs) {
    getEditData().isfromlcjs = requestParam.isfromlcjs;
  }
  if (requestParam.ssotype == "workflow") {
    getEditData().isfromlcjs = requestParam.isfromlcjs;
  }
  if (e.isvaliSuccess === false) {
    return;
  }
  mbos.post({
    url: "/mbos/editpage/submit",
    param: { "bostype": getEditData().bosType, "uiname": requestParam.name, "model": JSON.stringify(getEditData()) },
    success: function (data) {
      event = event || {};
      if (requestParam.ssotype == "workflow") {
        window.parent.postMessage("hasmbos", "*");
        return;
      }
      mbos.page.fire("afterSubmit", event);
      //mbos._invoke("afterSubmit", event);
    },
    error: function (data) {
      if (typeof (data) == "string") {
        mbos.msgBox.showError("", data);
      } else {
        mbos.msgBox.showError({ ...data, msg: "" });
      }
    }
  });
};



// 离职日期和最后工作日期是否同一天
function CheckDefaultSameDayService(date, callback) {
  var data = {
    personId: easContext.person.id,
    hrOrgUnitId: _hrOrgUnit.id,
    date: date
  }
  mbos.eas.invokeScript({
    name: "commonOSFservice",
    param: ['CheckDefaultSameDayService', JSON.stringify(data)],
    success: function (res) {
      console.log(res, 'res--------------')
      if (res.respCode == "000000") {
        isDefaultSameday = res.respObj.isDefaultSameday
        isSameDatePersonChange = res.respObj.isSameDatePersonChange
        isResignNextMonth = res.respObj.isResignNextMonth
        var bizDate = res.respObj.bizDate
        console.log(bizDate, '--bizDate-----')
        if (bizDate) {
          mbos('entrys.bizDate', 0).value(bizDate)
        }
        callback && callback()
      }
    },
    error: function (data) {
      if (typeof (data) == "string") {
        mbos.msgBox.showError("", data);
      } else {
        mbos.msgBox.showError({ ...data, msg: "" });
      }
    }
  })
}


Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "H+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

_this.suggestchange = function (event) {
  var value = event.new_value
  if (value.length >= 200) {
    mbos.ui.showInfo({ title: localeResource.msg52 });
    mbos('textarea2', 0).value(value.substr(0, 200))
  }
}
        
////202503加入社保数据校验;
_this.ces_change = function(event){
  var value = event.new_value.value;
  if(value ==  0 ){
    //添加图标,并且图标放入控件的后面
     $('#entrys_suspensionDate_0 label').append('<span class="must_input_icon ng-scope" style="margin-left:5px; color: red;">*</span>');
     $('#entrys_deduction_0 label').append('<span class="must_input_icon ng-scope" style="margin-left:5px; color: red;">*</span>');
     $('#entrys_otherSocialInfo_0 label').append('<span class="must_input_icon ng-scope" style="margin-left:5px; color: red;">*</span>');
  }else{
    //移除图标
    $('#entrys_suspensionDate_0 label span').remove();
    $('#entrys_deduction_0 label span').remove();
    $('#entrys_otherSocialInfo_0 label span').remove();
  }
         

}


//校验方法//202503加入社保数据校验;
function opValidate() {
  var cesEnum = mbos('entrys_fiveinsurances_0').value().value;
  var  sionDate = mbos('entrys_suspensionDate_0').value();
  var  deducVal = mbos('entrys_deduction_0').value();
  var  otherSo = mbos('entrys_otherSocialInfo_0').value();
  var isValid = true;
  var errorMsg = "";
  //如果cesEnum == 0 并且sionDate或deducVal或otherSo其中一个为空或者不存在，则提示不能为空
  if (cesEnum == 0 && (!sionDate || !deducVal || !otherSo)) {
    isValid = false;
    errorMsg = "社保结算信息必填,请检查!";
  }
    
  if (!isValid) {
    mbos.ui.showError({ title: errorMsg });
    return false;
  }
  return true;
}
        
