function jsRelationTelNumber(){

};
jsRelationTelNumber.grid=null;/*联系人列表*/
jsRelationTelNumber.CurTelNumber=null;/*当前需要关联的号码*/
jsRelationTelNumber.CurSelectedRow=null;/*当前双击的行*/

$(function(){
        jsRelationTelNumber.CurTelNumber=unescape(App.query("strNum"));
        $("#curTelNumber").html(jsRelationTelNumber.CurTelNumber);/*标题*/
         showTime("txt_BeginTime","txt_EndTime",false,80);
         customerDefaultTime("txt_BeginTime", "txt_EndTime",24*30);
         jsRelationTelNumber.GroupDropdown();
        jsRelationTelNumber.GetLinkManGrid();/*加载主列表*/
});

/*分组下拉框搜索条件*/
jsRelationTelNumber.GroupDropdown=function(){
    var typeItemArray=[];
    typeItemArray.push({"text":"全部","value":"0"});
    var txtSql="select ID,GROUPNAME as Name from T_GROUPDEF";
    var  obj= DBReader.selectSqlForJson(txtSql);
    if(obj!=null)
    { 
        var result=eval("[{"+obj+"}]");          
        if(result[0].result=="1" && result[0].table!=undefined)
        {      
            for (var index = 0; index < result[0].table.length; index++) {
                typeItemArray.push({ text:result[0].table[index].Name, value:result[0].table[index].ID});
            } 
        }
   }   
    var drop = $("#txtGroup").dropdown({
            dropwidth: 110,
            selectedIndex: -1,
            vinputid:"hideTxtGroup",
            items: typeItemArray,
            isNoItems:true,
            selecteditem:{text: "全部", value:"0"},
            selectedchange:jsRelationTelNumber.searchString
        });
};

/*加载联系人列表*/
jsRelationTelNumber.GetLinkManGrid=function(){
    var w = $(document.documentElement).width()-1;
     var gh = $(document.documentElement).height() - $("#div-top-container").height()-80;
/*<-------------------------------------------------------------主列表---------------------------------------------------->*/
     var option = {
         height: gh,
         width: w,
         colModel:
         [
            { display: '联系人编号', name: 'EmpID', width: (w * 0.1), sortable: false, align: 'left',hide:true},
            { display: '姓名', name: 'NAME', width: (w * 0.05), sortable: true, align: 'left' },
            { display: '昵称', name: 'NICKNAME', width: (w * 0.05), sortable: true, align: 'left' },
	        { display: '性别', name: 'MANORWOMAN', width: (w * 0.05), sortable: true, align: 'left' },
	        { display: '职位', name: 'BUSINESS', width: (w * 0.08), sortable: true, align: 'left' },
	        { display: '手机1', name: 'MOBILE', width: (w * 0.1), sortable: true, align: 'left' },
	        { display: '手机2', name: 'S2', width: (w * 0.1), sortable: true, align: 'left' },
	        { display: '电话1', name: 'TEL1', width: (w * 0.12), sortable: true, align: 'left' },
	        { display: '电话2', name: 'TEL2', width: (w * 0.12), sortable: true, align: 'left' },
	        { display: '公司编号', name: 'COMPANY_ID', width: (w * 0.1), sortable: false, align: 'left',hide:true},
	        { display: '公司', name: 'CompanyName', width: (w * 0.18), sortable: true, align: 'left' },
	        { display: '备注', name: 'REMARK', width: (w * 0.18), sortable: true, align: 'left',process:jsRelationTelNumber.FormartRemark}
		 ],
         customFunction: jsRelationTelNumber.ShowLinkManPage, 
         rowhandler: jsRelationTelNumber.doubleClick,
         singleselected: true,
         selectedonclick:true,
         rp: 10,
         rowbinddata:true,
         sortname: 'T_COMPANY.COMPANY_ID',
         sortorder: 'desc'
     };
     jsRelationTelNumber.grid = $("#tbAssociationList").ikegrid(option);
};

/*格式化备注*/
jsRelationTelNumber.FormartRemark=function(value,pid,rows){
    if(value.toString()!="")
    {
        var strValue=unescape(value.toString()).length>10?unescape(value.toString()).substring(0,10)+"...":unescape(value.toString());
        return '<a href="#" title='+unescape(value.toString())+'>'+strValue+'</a>';
    }
}

/*加载数据*/
jsRelationTelNumber.ShowLinkManPage=function(pageSize, pageIndex, searchStr,extpara,order) 
{   
    var countTop=pageSize*pageIndex;
    var strSql = "select top " + countTop + "  T_EMPLOYEE.EMPLOYEE_ID as EmpID,T_EMPLOYEE.NAME ,T_EMPLOYEE.MANORWOMAN ,T_EMPLOYEE.BUSINESS,T_EMPLOYEE.NICKNAME,T_COMPANY.COMPANY_ID,iif(ISNULL(T_COMPANY.SIMPLE_NAME),T_COMPANY.FULL_NAME,T_COMPANY.SIMPLE_NAME) as CompanyName,T_EMPLOYEE.MOBILE, T_EMPLOYEE.TEL1, T_EMPLOYEE.TEL2,T_EMPLOYEE.REMARK from T_EMPLOYEE inner join T_COMPANY on T_COMPANY.COMPANY_ID=T_EMPLOYEE.COMPANY_ID ";
    var strWhere=" WHERE 1=1 ";  
    if(jsTitle.GetCallBillNameByCallNum(jsRelationTelNumber.CurTelNumber)!="无" && jsRelationTelNumber.CurTelNumber!=""){
      strWhere+=" AND T_EMPLOYEE.EMPLOYEE_ID not in (select EMPLOYEE_ID from T_EMPLOYEE where MOBILE ='"+jsRelationTelNumber.CurTelNumber+"' or TEL1='"+jsRelationTelNumber.CurTelNumber+ "' or TEL2='"+jsRelationTelNumber.CurTelNumber+ "' or S2='"+jsRelationTelNumber.CurTelNumber +"' or REMARK  like '%"+jsRelationTelNumber.CurTelNumber+"%') ";
    }
    var sort = " desc";
    if (order != undefined && order.toUpperCase().indexOf("ASC") != -1) {
        sort = " asc";
    }    
    if(searchStr!="" && searchStr!=undefined)
    {
        if(searchStr[0]._LinkManName !="" && searchStr[0]._LinkManName != null){
            strWhere+=" AND (T_EMPLOYEE.NAME like '%"+searchStr[0]._LinkManName+"%' OR T_EMPLOYEE.NICKNAME like '%"+searchStr[0]._LinkManName+"%')";   
        }
        if(searchStr[0]._Company !="" && searchStr[0]._Company != null){
            strWhere+=" AND (T_COMPANY.SIMPLE_NAME like '%"+searchStr[0]._Company+"%' OR T_COMPANY.FULL_NAME like '%"+searchStr[0]._Company+"%')";        
        }
        if(searchStr[0]._Group  !="" && searchStr[0]._Group != null){
            strWhere += " AND T_EMPLOYEE.GROUP_ID="+searchStr[0]._Group;   
        }
        if(searchStr[0]._Remark  !="" && searchStr[0]._Remark != null){
            strWhere += " AND T_EMPLOYEE.REMARK like '%"+searchStr[0]._Remark+"%'";   
        }
        if(searchStr[0]._TelNum!="" && searchStr[0]._TelNum!=null){
            strWhere+="AND T_EMPLOYEE.EMPLOYEE_ID  in (select EMPLOYEE_ID from T_EMPLOYEE where MOBILE ='"+searchStr[0]._TelNum+"' or TEL1='"+searchStr[0]._TelNum+ "' or TEL2='"+searchStr[0]._TelNum+ "' or S2='"+searchStr[0]._TelNum +"' or REMARK  like '%"+searchStr[0]._TelNum+"%') ";
        }
    }     
   
   if(searchStr!="" && searchStr!=undefined){
        if(searchStr[0]._BeginTime!="" || searchStr[0]._EndTime!=""){
            var shortWhere = "select EMPLOYEEID from T_CALLBILL where 1=1 ";
            if(searchStr[0]._BeginTime!="" && searchStr[0]._BeginTime!=null){
                shortWhere = shortWhere + " and CALLTIME >= #"+ searchStr[0]._BeginTime +"#";
            }
            if(searchStr[0]._EndTime!="" && searchStr[0]._EndTime!=null){
                 shortWhere = shortWhere + " and CALLTIME <=#"+ searchStr[0]._EndTime+"#";
            }
            strWhere = strWhere + " and T_EMPLOYEE.EMPLOYEE_ID not in (" + shortWhere +")";
            shortWhere=null;
        }
   }else if($("#txt_BeginTime").val()!="" || $("#txt_EndTime").val()!=""){
        var shortWhere = "select EMPLOYEEID from T_CALLBILL where 1=1 " ;
        if($("#txt_BeginTime").val()!="" && $("#txt_BeginTime").val()!=null){
             shortWhere = shortWhere + " and CALLTIME >= #"+ $("#txt_BeginTime").val()+"#";
        }
        if($("#txt_EndTime").val()!="" && $("#txt_EndTime").val()!=null){
             shortWhere = shortWhere + " and CALLTIME <= #"+ $("#txt_EndTime").val()+"#";
        }
        strWhere = strWhere + " and T_EMPLOYEE.EMPLOYEE_ID not in (" + shortWhere +")";
        shortWhere=null;
    }
    
//    var strOrderBy="";

//    if(order !="" && order != null)
//    {
//        var str=order.toUpperCase().replace(/ASC/i,"").replace(/DESC/i,"").replace(/\s/g, "");
//        if(str !="T_EMPLOYEE.EMPLOYEE_ID")
//         {
//            strOrderBy=order+",T_EMPLOYEE.EMPLOYEE_ID DESC";
//         }
//        else
//         {
//            strOrderBy=order;
//         }   
//    }
    strSql = strSql + strWhere+" Order By "+order;    
  
    /*分页代码*/
    if(countTop >0)
    {
        //           strSql="select TOP "+ pageSize +" (select count(COMPANY_ID) from ( " + strSql +")) as AllCount, * from (" + strSql +") where COMPANY_ID NOT IN (SELECT TOP "+ countTop +" COMPANY_ID from (" + strSql + "))";
       strSql = "  select( select count(*)  from ( SELECT T_EMPLOYEE.EMPLOYEE_ID FROM T_EMPLOYEE LEFT JOIN  T_COMPANY  ON T_EMPLOYEE.COMPANY_ID=T_COMPANY.COMPANY_ID " + strWhere + " )) as AllCount,* from (select top " + pageSize + " * from ( " + strSql + "  ,T_COMPANY.COMPANY_ID asc)   order by " + order.toUpperCase().replace("DESC", "").replace("ASC", "") + (sort == " asc" ? " desc" : " asc") + "   ,T_COMPANY.COMPANY_ID asc)order by " + order.toUpperCase().replace("DESC", "").replace("ASC", "") + sort;
    }
    else
    {
         strSql="select TOP "+ pageSize +" (select count(COMPANY_ID) from ( " + strSql +")) as AllCount, * from (" + strSql +") ";
    } // window.clipboardData.setData("text",strSql);
  var strResult=DBReader.selectSqlForJson(strSql);
  var result;
    if (strResult != null) {
        result = eval("[{" + strResult + "}]");
        result[0].pageIndex = pageIndex;
    }
    countTop=null;
    strSql=null;
    strWhere=null;
    
    CollectGarbage();
    return strResult == null ? null : result[0];
};

/*搜索*/
jsRelationTelNumber.searchString=function(){
    var strWhere=[];
    var htxt_LinkManName=$.trim($("#hsltName").val()).split('\"').join('“');htxt_LinkManName=htxt_LinkManName.split('\'').join('‘');
    var htxt_Company=$.trim($("#hsltCompany").val()).split('\"').join('“');htxt_Company=htxt_Company.split('\'').join('‘');
    var htxt_BeginTime=$("#txt_BeginTime").val();
    var htxt_EndTime=$("#txt_EndTime").val();    
    var htxt_Group="";
    if($("#hideTxtGroup").val()!=0){
        htxt_Group= $("#hideTxtGroup").val();
    }
    var htxt_Remark=$("#txtRemark").val();
    var htxt_TelNum=$("#hTxtTelNum").val();
    strWhere.push({_LinkManName:htxt_LinkManName,_Company:htxt_Company,_BeginTime:htxt_BeginTime,_EndTime:htxt_EndTime,_Group:htxt_Group,_Remark:htxt_Remark,_TelNum:htxt_TelNum});
    $("#tbAssociationList").DoSearch(strWhere);
};

/*清空*/
jsRelationTelNumber.Cancel=function(){
    $("#frSearchForm").resetForm();
    jsRelationTelNumber.searchString();
};

/*双击行选择关联客户*/
jsRelationTelNumber.doubleClick=function(target){
    $(target).dblclick(function(){     
       jsRelationTelNumber.CurSelectedRow=$(target);
      var strSql="SELECT e.[NAME],e.NICKNAME,e.MANORWOMAN,e.BUSINESS,e.MOBILE,e.TEL1,e.TEL2,e.S2,c.SIMPLE_NAME,c.ADDRESS FROM T_EMPLOYEE AS e inner join T_COMPANY as c on e.COMPANY_ID=c.COMPANY_ID WHERE e.EMPLOYEE_ID="+$(target).attr("EmpID");
      var strResult=DBReader.selectSqlForJson(strSql);//alert(strResult);
      var result;
        if (strResult != null) {
            result = eval("[{" + strResult + "}]");
            if(result[0].result==1 && result[0].table!=undefined){
                var strTelNum="TEL1";
                if(result[0].table[0].MOBILE=="" || result[0].table[0].MOBILE==null){
                    strCulmn="MOBILE";
                }else if(result[0].table[0].TEL1=="" || result[0].table[0].TEL1==null){
                    strCulmn="TEL1";
                }else if(result[0].table[0].TEL2=="" || result[0].table[0].TEL2==null){
                    strCulmn="TEL2";
                }else if(result[0].table[0].S2=="" || result[0].table[0].S2==null){
                    strCulmn="S2";
                }else{
                    strCulmn="REMARK";
                }
        
                if(jsRelationTelNumber.UpdateLinkManInfo(strCulmn)){
                    ShowWindow.opener.execScript(App.query("formIndex"),App.query("action").replace('@comID',$(target).attr("COMPANY_ID")).replace("@empID",$(target).attr("EmpID")));
                }else{
                    ShowWindow.opener.execScript(App.query("formIndex"),App.query("action").replace('@comID',0).replace("@empID",0));
                }  
                strSql=null;strResult=null;result=null;
                CollectGarbage();                 
               ShowWindow.close();
            }
        }  
   }); 
 };
 
/*更改联系人号码信息*/
jsRelationTelNumber.UpdateLinkManInfo=function(strCulmn){
    var result=-1;
    /*将联系人号码等于当前号码的资料清空*/
    var txtSql1="UPDATE T_EMPLOYEE SET MOBILE='' WHERE MOBILE='"+jsRelationTelNumber.CurTelNumber+"' and EMPLOYEE_ID="+jsRelationTelNumber.CurSelectedRow.attr("EmpID");
    DBReader.execSql(txtSql1);
    var txtSql2="UPDATE T_EMPLOYEE SET TEL1='' WHERE TEL1='"+jsRelationTelNumber.CurTelNumber+"' and EMPLOYEE_ID="+jsRelationTelNumber.CurSelectedRow.attr("EmpID");
    DBReader.execSql(txtSql2);   
    var txtSql3="UPDATE T_EMPLOYEE SET TEL2='' WHERE TEL2='"+jsRelationTelNumber.CurTelNumber+"' and EMPLOYEE_ID="+jsRelationTelNumber.CurSelectedRow.attr("EmpID");
    DBReader.execSql(txtSql3);
    txtSql4="UPDATE T_EMPLOYEE SET S2='' WHERE S2='"+jsRelationTelNumber.CurTelNumber+"' and EMPLOYEE_ID="+jsRelationTelNumber.CurSelectedRow.attr("EmpID");
    DBReader.execSql(txtSql4);
    
    /*更新指定联系人的号码为当前号码*/
    var txtSql5="";
    if(strCulmn=="REMARK"){
        var strRemark="";
        if(jsRelationTelNumber.CurSelectedRow.attr("REMARK")!=""){
           strRemark=jsRelationTelNumber.CurSelectedRow.attr("REMARK")+":"+jsRelationTelNumber.CurTelNumber;
         }else{
             strRemark=jsRelationTelNumber.CurTelNumber
        }
        txtSql5="UPDATE T_EMPLOYEE SET REMARK='"+strRemark+"' WHERE EMPLOYEE_ID="+jsRelationTelNumber.CurSelectedRow.attr("EmpID")+";";
     }else{
          txtSql5="UPDATE T_EMPLOYEE SET "+strCulmn+"='"+jsRelationTelNumber.CurTelNumber+"' WHERE EMPLOYEE_ID="+jsRelationTelNumber.CurSelectedRow.attr("EmpID")+";";
    }
    if(txtSql5!=""){ result=DBReader.execSql(txtSql5);}
    
    /*更改号码后，更新当前联系人为历史通话记录联系人名，如果历史通话记录中已经记录了联系人名称的那么就不做修改*/
   var txtSql6="UPDATE T_CALLBILL SET CUSTOMER='"+jsRelationTelNumber.CurSelectedRow.attr("CompanyName")+jsRelationTelNumber.CurSelectedRow.attr("EmpName")+"',COMPANYID="+jsRelationTelNumber.CurSelectedRow.attr("COMPANY_ID")+",EMPLOYEEID="+jsRelationTelNumber.CurSelectedRow.attr("EmpID")+" WHERE  TELNUM='"+jsRelationTelNumber.CurTelNumber+"' AND CUSTOMER='无';";
  DBReader.execSql(txtSql6);
  
  //window.clipboardData.setData("text",txtSql6);
  txtSql1=null;txtSql2=null;txtSql3=null;
  txtSql4=null;txtSql5=null;txtSql6=null;
  CollectGarbage();
  return result;  
};