/// <summary>
        /// 批量操作--导入成员
        /// </summary>
        /// <param name="OPType"></param>
        /// <returns></returns>
        public ActionResult batchuser(int?OPType)
        {
            string strRet = "[\"jsonrpc\" : \"2.0\", \"result\" : null, \"id\" : \"{0}\"]";

            string strErrRet = "[\"jsonrpc\" : \"2.0\", \"error\" : [\"code\": {0}, \"message\": \"{1}\"], \"id\" : \"id\"]";

            string operateType = "";

            try
            {
                if (Request.Files.Count == 0)
                {
                    strRet = string.Format(strErrRet, "100", "未发现上传文件!");
                    return(Content(strRet));
                }

                Dictionary <string, Stream> dic = new Dictionary <string, Stream>();

                for (int i = 0; i < Request.Files.Count; i++)
                {
                    HttpPostedFileBase objFile = Request.Files[i];
                    dic.Add(objFile.FileName, objFile.InputStream);
                }


                var ret = MediaApi.Upload(GetToken(), UploadMediaFileType.file, dic, "");

                System.Threading.Thread.Sleep(1000);

                //上传失败
                if (!string.IsNullOrEmpty(ret.errmsg) && ret.errmsg.IndexOf("ok") < 0)
                {
                    strRet = string.Format(strErrRet, ret.errcode, ret.errmsg);
                    return(Content(strRet));
                }

                BatchUserResult objRet;

                var       objConfig   = WeChatCommonService.GetWeChatConfig(AppId);
                string    callbackUrl = CommonService.GetSysConfig(SysConfigCode.CallBackUrl, "");//从Sysconfig数据库中读url
                BatchUser objUser     = new BatchUser()
                {
                    media_id = ret.media_id,
                    callback = new callback()
                    {
                        token          = objConfig.WeixinToken,          // Token,
                        encodingaeskey = objConfig.WeixinEncodingAESKey, // EncodingAESKey,
                        url            = callbackUrl                     //app.innocellence.com/wechatqy/led
                    }
                };

                if (OPType == 1)
                {
                    objRet      = MailListApi.BatchUpdateUser(GetToken(), objUser);
                    operateType = "sync_user";
                }
                else if (OPType == 2)
                {
                    objRet      = MailListApi.BatchReplaceUser(GetToken(), objUser);
                    operateType = "replace_user";
                }
                else if (OPType == 3)
                {
                    objRet      = MailListApi.BatchReplaceDept(GetToken(), objUser);
                    operateType = "replace_party";
                }
                else
                {
                    objRet = new BatchUserResult()
                    {
                        errmsg = "参数错误!"
                    };
                }

                //当执行导入操作时将返回的jobId插入到表中去
                if (!string.IsNullOrEmpty(objRet.errmsg))
                {
                    strRet = string.Format(strRet, objRet.jobid);
                    var jobLog = new BatchJobLog()
                    {
                        JobID       = objRet.jobid,
                        Status      = 0,
                        Type        = operateType,
                        CreatedDate = DateTime.Now
                    };

                    _batchJobLogService.Repository.Insert(jobLog);//插入表中
                }
                else
                {
                    strRet = string.Format(strErrRet, objRet.errcode, objRet.errmsg);
                }
            }
            catch (Exception ex)
            {
                strRet = string.Format(strErrRet, "102", ex.Message);
            }


            return(Content(strRet.Replace("[", "{").Replace("]", "}")));
        }
        /// <summary>
        /// 同步成员功能,与fishflow通信
        /// </summary>
        /// <param name="accountManageId"></param>
        public void SyncMember(int accountManageId)
        {
            var          url           = CommonService.GetSysConfig("FishflowUrl", "");
            var          userName      = CommonService.GetSysConfig("FishflowUserName", "");
            var          password      = CommonService.GetSysConfig("FishflowPassword", "");
            var          whiteCompany  = CommonService.GetSysConfig("FishflowWhiteCompany", "");
            var          dDepartmentID = int.Parse(CommonService.GetSysConfig("DimissionDepartment", ""));
            EmployeeInfo client        = new EmployeeInfo()
            {
                Url = url,
                GCSoapHeaderValue = new GCSoapHeader()
                {
                    UserName = userName, Password = password
                }
            };
            int total = 0;
            int index = 1;
            //每次通信得到50条记录
            int pageCount = 50;
            HashSet <string> employeeNoBag = new HashSet <string>();

            do
            {
                //fishflow通信
                var result = client.GetEmployeeInfo2(index, pageCount);
                result = EncryptionHelper.DecryptDES(result);
                //得到返回结果反序列化成我们的对象
                var view = JsonConvert.DeserializeObject <EmployeeInfoView>(result);
                var currentEmployeeList = new List <EmployeeData>();
                if (index == 1)
                {
                    total = view.Data.TotalQty - pageCount;
                }
                else
                {
                    total -= pageCount;
                }
                index++;
                if (view.IsSuccess)
                {
                    foreach (var e in view.Data.EmployeeInfo)
                    {
                        //fishflow的部门在我们这里部门ID要加10000,以示与丁香园区分
                        if (e.BUID != null)
                        {
                            e.BUID += 10000;
                        }
                        if (e.SBUID != null)
                        {
                            e.SBUID += 10000;
                        }
                        if (e.GroupID != null)
                        {
                            e.GroupID += 10000;
                        }
                        //经确认,只有部门子公司的员工需要同步
                        if (!string.IsNullOrEmpty(whiteCompany))
                        {
                            var companies = whiteCompany.Split(",".ToArray()).Select(a => a.Trim()).ToList();
                            if (e.CompanyID == null || !companies.Contains(e.CompanyID.ToString()))
                            {
                                continue;
                            }
                        }
                        //经确认,符合7开头长度是9位的员工号员工不需要同步
                        if (!string.IsNullOrEmpty(e.EmployeeNo) && e.EmployeeNo.StartsWith("7") && e.EmployeeNo.Length == 9)
                        {
                            continue;
                        }
                        //经确认,fishflow中重复的用户只添加第一个
                        if (employeeNoBag.Contains(e.EmployeeNo))
                        {
                            continue;
                        }
                        else
                        {
                            employeeNoBag.Add(e.EmployeeNo);
                            currentEmployeeList.Add(e);
                        }
                    }
                    //同步成员信息到我们数据库,先将数据存入SysAddressBookMemberTemp缓存表,方便对比变更的用户信息
                    var ctx      = (DbContext)_tempRepository.UnitOfWork;
                    var entities = currentEmployeeList.Select(e =>
                    {
                        var department = JsonConvert.SerializeObject(GetDepartmentId(e, accountManageId, dDepartmentID));
                        return(new SysAddressBookMemberTemp()
                        {
                            EmployeeNo = e.EmployeeNo,
                            Status = 4, //未关注
                            EmployeeStatus = e.EmployeeStatus,
                            UserName = e.CName,
                            EnName = e.EName,
                            AccountManageId = accountManageId,
                            //Avatar =
                            //Birthday =
                            Department = department,
                            FishflowDepartment = department,
                            UserId = GenerateUserId(e.EmployeeNo),
                            Gender = GetGenderNumber(e.Gender),
                            DirectManagerID = e.DirectManagerID,
                            CompanyID = e.CompanyID != null ? e.CompanyID.ToString() : string.Empty,
                            GradeCode = e.GradeCode,
                            City = e.City,
                            Mobile = GetMobileString(e.Mobile),
                            Position = GetPositionString(e.Position),
                            Email = e.Email,
                            DeleteFlag = 0,
                            CreateTime = DateTime.Now,
                            Extend1 = e.ADAccount,
                        });
                    }).Where(e => !e.Department.Equals("[]", StringComparison.CurrentCultureIgnoreCase));
                    using (var transactionScope = new TransactionScope())
                    {
                        #region SQL update
                        var options = new BulkInsertOptions
                        {
                            EnableStreaming = true,
                        };
                        ctx.BulkInsert(entities, options);
                        ctx.SaveChanges();
                        //经确认,已关注用户只更新姓名,性别,部门,在职离职状态变化的;
                        //未关注用户只更新姓名,性别,手机,邮箱,部门,在职离职状态变化的;
                        string findChangeSubscribeUserSQL   = @"select t.id from SysAddressBookMember m join SysAddressBookMemberTemp t on m.EmployeeNo = t.EmployeeNo where m.[Status] = 1 and (m.DeleteFlag != 1 or m.DeleteFlag is null) and
                        (m.[UserName] != t.[UserName] or m.[Gender] != t.[Gender] or m.[FishflowDepartment] != t.[FishflowDepartment] or m.[EmployeeStatus] != t.[EmployeeStatus]) ";
                        string findChangeUnsubscribeUserSQL = @"select t.id from SysAddressBookMember m join SysAddressBookMemberTemp t on m.EmployeeNo = t.EmployeeNo where m.[Status] != 1 and (m.DeleteFlag != 1 or m.DeleteFlag is null) and
                        (m.[UserName] != t.[UserName] or m.[Gender] != t.[Gender] or m.[Mobile] != t.[Mobile] or m.[Email] != t.[Email] or m.[FishflowDepartment] != t.[FishflowDepartment] or m.[EmployeeStatus] != t.[EmployeeStatus]) ";
                        string findChangeUserSQL            = @"select 
                        tt.[Id], tt.[Gender],tt.[UserName],tt.[EnName],tt.[Mobile],tt.[Position],tt.[Email],tt.[City],tt.[FishflowDepartment],tt.[Extend1],
                        CASE ISNULL(mm.[DXYDepartment], '') WHEN '' Then tt.[Department]
                        ELSE REPLACE(tt.[Department], ']',',')+REPLACE(mm.[DXYDepartment], '[','') End as Department,
                        mm.[WeiXinId],mm.[Status],mm.[Avatar],mm.[GradeCode],mm.[EmployeeNo],
                        mm.[EmployeeStatus],mm.[Birthday],mm.[CompanyID],mm.[DirectManagerID],
                        mm.[DeleteFlag],mm.[UserId] ,mm.[CreateTime],mm.[AccountManageId],mm.[TagList],mm.[LabourUnionStatus] 
                        from SysAddressBookMemberTemp tt join SysAddressBookMember mm on tt.EmployeeNo = mm.EmployeeNo where mm.AccountManageId = tt.AccountManageId and tt.id in (({0}) union ({1}))";
                        string findNewUserSQL   = @"select * from SysAddressBookMemberTemp where EmployeeStatus = 'A' and EmployeeNo in (select EmployeeNo from SysAddressBookMemberTemp except (select EmployeeNo from SysAddressBookMember where (DeleteFlag!=1 or DeleteFlag is null) and AccountManageId = {0}))";
                        string updateOldUserSQL = @"update SysAddressBookMember 
                                                                    set [UserName] = SysAddressBookMemberTemp.UserName,             
                                                                    [EmployeeStatus] = SysAddressBookMemberTemp.EmployeeStatus,
                                                                    [EnName] = SysAddressBookMemberTemp.EnName,
                                                                    [FishflowDepartment] = SysAddressBookMemberTemp.Department,
                                                                    [Department] = CASE ISNULL([DXYDepartment], '') WHEN '' Then SysAddressBookMemberTemp.Department
                                                                                               ELSE REPLACE(SysAddressBookMemberTemp.Department, ']',',')+REPLACE([DXYDepartment], '[','')
                                                                                               End,
                                                                    [Gender] = SysAddressBookMemberTemp.Gender,
                                                                    [City] = SysAddressBookMemberTemp.City,
                                                                    [Mobile] = SysAddressBookMemberTemp.Mobile,
                                                                    [Position] = SysAddressBookMemberTemp.Position,
                                                                    [Email] = SysAddressBookMemberTemp.Email,
                                                                    [DirectManagerID] = SysAddressBookMemberTemp.DirectManagerID,
                                                                    [CompanyID] = SysAddressBookMemberTemp.CompanyID,
                                                                    [GradeCode] = SysAddressBookMemberTemp.GradeCode,
                                                                    [Extend1] = SysAddressBookMemberTemp.Extend1
                                                                    from SysAddressBookMemberTemp
                                                                    where SysAddressBookMember.EmployeeNo = SysAddressBookMemberTemp.EmployeeNo
                                                                    and SysAddressBookMember.AccountManageId = SysAddressBookMemberTemp.AccountManageId
                                                                    and (SysAddressBookMember.DeleteFlag != 1 or SysAddressBookMember.DeleteFlag is null)";

                        StringBuilder builder     = new StringBuilder("insert into SysAddressBookMember (");
                        string        tableValues = @"[WeiXinId],[Status],[Gender],[UserName],[EnName],[Mobile],[Avatar],[Position],[Email],[Department],[FishflowDepartment],
                                                               [GradeCode],[EmployeeNo],[EmployeeStatus],[City],[Birthday],[CompanyID],[DirectManagerID],
                                                               [DeleteFlag],[UserId] ,[CreateTime],[AccountManageId],[TagList],[Extend1]";
                        builder.Append(tableValues);
                        builder.AppendFormat(") select {0} ", tableValues);
                        builder.Append(@"from SysAddressBookMemberTemp where EmployeeStatus = 'A' and EmployeeNo in (select EmployeeNo from SysAddressBookMemberTemp except (select EmployeeNo from SysAddressBookMember where (DeleteFlag!=1 or DeleteFlag is null)  and AccountManageId = {0}))");
                        string insertNewUserSQL = builder.ToString();
                        var    changeObjects    = _tempRepository.SqlQuery(string.Format(findChangeUserSQL, findChangeSubscribeUserSQL, findChangeUnsubscribeUserSQL)).ToList();
                        var    newObjects       = _tempRepository.SqlQuery(string.Format(findNewUserSQL, accountManageId)).ToList();
                        changeObjects.AddRange(newObjects);

                        logger.Debug("Start changeObjects! Count:{0} ", changeObjects.Count);

                        changeObjects.ForEach(a =>
                        {
                            if (!string.IsNullOrEmpty(a.EmployeeStatus) && a.EmployeeStatus.Equals("D", StringComparison.CurrentCultureIgnoreCase))
                            {
                                a.Department = JsonConvert.SerializeObject(new int[] { dDepartmentID });
                            }
                        });
                        var apiModels = changeObjects.Select(e => e.ConvertToMember()).Select(m => (new AddressBookMemberView()
                        {
                            ConvertEntity = m
                        }).ConvertApiModel).ToList();
                        apiModels.ForEach(a =>
                        {
                            if (a.status == 1 || a.department.Contains(dDepartmentID))
                            {
                                //裁减掉不需要同步到腾讯后台的用户信息
                                CutPropertyBefaultSync2TX(a);
                            }
                        });
                        var templateModels = apiModels.Select(a => (new AddressBookMemberView()
                        {
                            ConvertApiModel = a
                        }).ConvertTemplateModel).ToList();
                        this.Repository.SqlExcute(updateOldUserSQL);
                        this.Repository.SqlExcute(insertNewUserSQL, accountManageId);
                        //this.Repository.SqlExcute(updateTempUserIdSQL, accountManageId);
                        #endregion

                        //同步成员信息到腾讯后台
                        #region Batch API update
                        if (templateModels.Count > 0)
                        {
                            Dictionary <string, Stream> dic = new Dictionary <string, Stream>();
                            //var templateModels = _tempRepository.Entities.ToList().Select(e => e.ConvertToMember()).Select(m => (new AddressBookMemberView() { ConvertEntity = m }).ConvertTemplateModel).ToList();
                            templateModels.ForEach(t =>
                            {
                                if (!string.IsNullOrEmpty(t.Position) && t.Position.IndexOf(",") > 0)
                                {
                                    t.Position = "\"" + t.Position + "\"";
                                }
                                if (!string.IsNullOrEmpty(t.UserName) && t.UserName.IndexOf(",") > 0)
                                {
                                    t.UserName = "******"" + t.UserName + "\"";
                                }
                            });
                            var stream = GetUploadCsv(templateModels);
                            dic.Add("上传模板.csv", stream);

                            logger.Debug("Start upload User to WeChat Server! Count:{0} ", templateModels.Count);

                            var ret = MediaApi.Upload(GetToken(accountManageId), UploadMediaFileType.file, dic, "");
                            System.Threading.Thread.Sleep(200);
                            if (ret.errcode == Weixin.ReturnCode_QY.请求成功)
                            {
                                var       objConfig   = WeChatCommonService.lstSysWeChatConfig.Find(a => a.AccountManageId == accountManageId);
                                string    callbackUrl = CommonService.GetSysConfig(SysConfigCode.CallBackUrl, "");//从Sysconfig数据库中读url
                                BatchUser objUser     = new BatchUser()
                                {
                                    media_id = ret.media_id,
                                    callback = new callback()
                                    {
                                        token          = objConfig.WeixinToken,                                  // Token,
                                        encodingaeskey = objConfig.WeixinEncodingAESKey,                         // EncodingAESKey,
                                        url            = callbackUrl + string.Format("?appid={0}", objConfig.Id) //app.innocellence.com/wechatqy/led
                                    }
                                };
                                try
                                {
                                    var objRet = MailListApi.BatchUpdateUser(GetToken(accountManageId), objUser);
                                    if (objRet.errcode == Weixin.ReturnCode.请求成功)
                                    {
                                        var jobLog = new BatchJobLog()
                                        {
                                            JobID       = objRet.jobid,
                                            Status      = 0,
                                            Type        = "sync_user",
                                            CreatedDate = DateTime.Now
                                        };

                                        _batchJobLogService.Repository.Insert(jobLog);//插入表中

                                        //清除临时缓存数据
                                        _tempRepository.Delete(a => true);

                                        transactionScope.Complete();
                                    }
                                    else
                                    {
                                        logger.Error("An error occurred while uploading page: {0} msg:{1}", index, objRet.errmsg);
                                    }
                                }
                                catch (Exception e)
                                {
                                    logger.Error("An error occurred while uploading page {0}", index);
                                    logger.Error("CallbackURL: {0}", objUser.callback.url);
                                    logger.Error(e.ToString());
                                }
                            }
                        }
                        else
                        {
                            //清除临时缓存数据
                            _tempRepository.Delete(a => true);
                            transactionScope.Complete();
                        }

                        #endregion
                    }
                }
                else
                {
                    logger.Error("Sync Member Page Error: {0}, Index is {1}.", view.Message, index);
                }
            }while (total > 0);
        }