///// <summary>
        ///// 임시 사이트 추가
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
        //[HttpPost, Route("registtemporarysite")]
        //[AllowAnonymous]
        ////[ValidateAntiForgeryToken]
        //public async Task<IActionResult> RegistTemporarySite([FromBody] RegisterSiteModel model)
        //{

        //    //model.Email = value["Email"].ToString();
        //    //model.Password = value["Password"].ToString();
        //    //model.ConfirmPassword = value["ConfirmPassword"].ToString();
        //    //model.Username
        //    if (ModelState.IsValid)
        //    {

        //        UserAccount contractor = await _userManager.FindByEmailAsync(model.ContractorEmail);
        //        if(contractor == null)
        //        {
        //            IdentityError error = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).ContractorNotFounded(model.ContractorEmail);
        //            IdentityResult _result = IdentityResult.Failed(error);
        //            return BadRequest(new { Result = _result });
        //        }
        //        ContractorUser cu = await _accountContext.ContractorUsers.FindAsync(contractor.Id);

        //        TemporaryContractorSite newSite = new TemporaryContractorSite();
        //        newSite.Address1 = model.Address1;
        //        newSite.Address2 = model.Address2;
        //        newSite.ContractUserId = contractor.Id;
        //        newSite.Latitude = model.Latitude;
        //        newSite.IsJeju = model.IsJejuSite;
        //        newSite.Longtidue = model.Longtidue;
        //        newSite.LawFirstCode = model.LawFirstCode;
        //        newSite.LawMiddleCode = model.LawMiddleCode;
        //        newSite.LawLastCode = model.LawLastCode;
        //        newSite.ServiceCode = model.ServiceCode;
        //        newSite.RegisterTimestamp = DateTime.Now;

        //        foreach (RegisterAssetModel asset in model.Assets)
        //        {
        //            string assetName = $"{asset.Type}{asset.Index}";
        //            TemporaryContractorAsset newAsset = new TemporaryContractorAsset();
        //            newAsset.AssetName = assetName;
        //            newAsset.AssetType = asset.Type;
        //            newAsset.CapacityKW = asset.CapacityMW;
        //            newAsset.ContractorSite = newSite;
        //            newAsset.UniqueId = Guid.NewGuid().ToString();
        //            await _accountContext.TemporaryContractorAssets.AddAsync(newAsset);
        //        }

        //        await _accountContext.TemporaryContractorSites.AddAsync(newSite);
        //        await _accountContext.SaveChangesAsync();
        //        //var user = new ReservedAssetLocation
        //        //{
        //        //    AccountId = model.AccountId,
        //        //    Address1 = model.Address1,
        //        //    Address2 = model.Address2,
        //        //    ControlOwner = model.ControlOwner,
        //        //    //SiteInformation = model.SiteInformation,
        //        //    RegisterTimestamp = DateTime.Now,
        //        //    LawFirstCode = model.LawFirstCode,
        //        //    LawMiddleCode = model.LawMiddleCode,
        //        //    LawLastCode = model.LawLastCode,
        //        //    ServiceCode = model.ServiceCode,
        //        //    Latitude = model.Latitude,
        //        //    Longtidue = model.Longtidue
        //        //};
        //        //accountContext.ReservedAssetLocations.Add(user);
        //        //await accountContext.SaveChangesAsync();
        //        return Ok();
        //    }

        //    // If we got this far, something failed, redisplay form
        //    return BadRequest();
        //}

        private UserAccountEF CreateUserAccount(AggregatorRegistModelBase model)
        {
            var user = new UserAccountEF
            {
                FirstName          = model.FirstName,
                LastName           = model.LastName,
                Email              = model.Email,
                UserName           = model.Email,
                CompanyName        = model.Company,
                NormalizedUserName = model.Email.ToUpper(),
                PhoneNumber        = model.PhoneNumber,
                Address            = model.Address,
                RegistDate         = DateTime.Now,
                Expire             = DateTime.Now.AddDays(14),
                UserType           = model.Type
            };

            return(user);
        }
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> SignonSupervisor([FromBody] AggregatorRegistModelBase model)
        {
            if (ModelState.IsValid)
            {
                var trans = await _accountContext.Database.BeginTransactionAsync();

                try

                {
                    var user   = CreateUserAccount(model, RegisterType.Supervisor);
                    var result = await _userManager.CreateAsync(user, model.Password);

                    //result.Errors
                    if (result.Succeeded)
                    {
                        var role_add_result = await _userManager.AddToRoleAsync(user, UserRoleTypes.Supervisor);

                        //_userManager.AddClaimAsync(user, new Claim())
                        SupervisorUserEF aggregatorUser = new SupervisorUserEF();
                        aggregatorUser.UserId = user.Id;
                        await _accountContext.SupervisorUsers.AddAsync(aggregatorUser);

                        await _accountContext.SaveChangesAsync();

                        trans.Commit();
                        return(Ok(new { Result = result }));
                    }
                    else
                    {
                        trans.Rollback();
                        return(BadRequest(new { Result = result }));
                    }
                }
                catch (Exception ex)
                {
                    trans.Dispose();
                    logger.LogError(ex, ex.Message);
                    return(BadRequest(ex.Message));
                }
            }
            return(BadRequest());
        }
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> SignonContractor([FromBody] AggregatorRegistModelBase model)
        {
            if (ModelState.IsValid)
            {
                var trans = await _accountContext.Database.BeginTransactionAsync();

                try
                {
                    AggregatorGroupEF aggregatorGroup = await _accountContext.AggregatorGroups.FindAsync(model.AggregatorGroupId);

                    if (aggregatorGroup == null)
                    {
                        IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).AggregatorNotFounded(model.AggregatorGroupId);
                        IdentityResult _result = IdentityResult.Failed(error);
                        return(base.BadRequest(new { Result = _result }));
                    }

                    var user = CreateUserAccount(model, RegisterType.Contrator);

                    JObject obj    = JObject.FromObject(user);
                    var     result = await _userManager.CreateAsync(user, model.Password);

                    //result.Errors
                    if (result.Succeeded)
                    {
                        ContractorUserEF cu = new ContractorUserEF();
                        cu.AggGroupId     = aggregatorGroup.ID;
                        cu.ContractStatus = ContractStatusCodes.Signing;
                        cu.UserId         = user.Id;
                        _accountContext.ContractorUsers.Add(cu);

                        RegisterFileRepositaryEF registerModel = null;

                        if (string.IsNullOrEmpty(model.RegisterFilename) == false)
                        {
                            registerModel = RegisterFile(user.Id, model.RegisterFilename, model.RegisterFilebase64);
                            _accountContext.RegisterFileRepositaries.Add(registerModel);
                        }

                        await _userManager.AddToRoleAsync(user, UserRoleTypes.Contractor);

                        await _accountContext.SaveChangesAsync();


                        if (model.NotifyEmail)
                        {
                            string email_contents = htmlGenerator.GenerateHtml("NotifyEmail.html",
                                                                               new
                            {
                                Name       = $"{user.FirstName} {user.LastName}",
                                Company    = model.Company,
                                Email      = model.Email,
                                Phone      = model.PhoneNumber,
                                Address    = model.Address,
                                Aggregator = aggregatorGroup.AggName
                            });

                            string sender = "PEIU 운영팀";
                            string target = "";

                            List <string> supervisor_emails = (await _userManager.GetUsersInRoleAsync(UserRoleTypes.Supervisor)).Select(x => x.Email).ToList();
                            target = "발전사업자";

                            var agg_result = _accountContext.VwAggregatorusers.Where(x => x.AggGroupId == model.AggregatorGroupId);
                            supervisor_emails.AddRange(agg_result.Select(x => x.Email));

                            //var aggregator_account_users = await _userManager.GetUsersInRoleAsync(UserRoleTypes.Supervisor);
                            await _emailSender.SendEmailAsync(sender, $"새로운 {target} 가입이 요청되었습니다", email_contents, registerModel, supervisor_emails.ToArray());

                            logger.LogInformation($"가입 알림 메일 전송: {string.Join(", ", supervisor_emails)}");
                        }
                        trans.Commit();
                        return(Ok(new { Result = result }));


                        //_userManager.find
                        //if (user.AuthRoles == (int)AuthRoles.Aggregator || user.AuthRoles == (int)AuthRoles.Business)
                        //    await Publisher.PublishMessageAsync(obj.ToString(), cancellationTokenSource.Token);

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                        // Send an email with this link
                        //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                        //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                        //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                        //    "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
                        //await _signInManager.SignInAsync(user, isPersistent: false);
                        //_logger.LogInformation(3, "User created a new account with password.");
                    }
                    else
                    {
                        trans.Dispose();
                        return(BadRequest(new { Result = result }));
                    }
                }
                catch (Exception ex)
                {
                    trans.Dispose();
                    logger.LogError(ex, ex.Message);
                    throw;
                }
            }

            // If we got this far, something failed, redisplay form
            return(BadRequest());
        }
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> SignonAggregator([FromBody] AggregatorRegistModelBase model)
        {
            if (ModelState.IsValid)
            {
                var trans = await _accountContext.Database.BeginTransactionAsync();

                try

                {
                    AggregatorGroupEF aggregatorGroup = _accountContext.AggregatorGroups.FirstOrDefault(x => x.AggName == model.Company);
                    if (aggregatorGroup == null)
                    {
                        aggregatorGroup                = new AggregatorGroupEF();
                        aggregatorGroup.ID             = Guid.NewGuid().ToString();
                        aggregatorGroup.AggName        = model.Company;
                        aggregatorGroup.Representation = "";
                        aggregatorGroup.Address        = model.Address;
                        aggregatorGroup.CreateDT       = DateTime.Now;
                        aggregatorGroup.PhoneNumber    = model.PhoneNumber;
                        await _accountContext.AddAsync(aggregatorGroup);
                    }

                    var user   = CreateUserAccount(model, RegisterType.Aggregator);
                    var result = await _userManager.CreateAsync(user, model.Password);

                    //result.Errors
                    if (result.Succeeded)
                    {
                        var role_add_result = await _userManager.AddToRoleAsync(user, UserRoleTypes.Aggregator);

                        //_userManager.AddClaimAsync(user, new Claim())
                        AggregatorUserEF aggregatorUser = new AggregatorUserEF();
                        aggregatorUser.AggregatorGroup = aggregatorGroup;
                        aggregatorUser.UserId          = user.Id;
                        await _accountContext.AggregatorUsers.AddAsync(aggregatorUser);

                        RegisterFileRepositaryEF registerModel = null;

                        if (string.IsNullOrEmpty(model.RegisterFilename) == false)
                        {
                            registerModel = RegisterFile(user.Id, model.RegisterFilename, model.RegisterFilebase64);
                            _accountContext.RegisterFileRepositaries.Add(registerModel);
                        }

                        await _accountContext.SaveChangesAsync();

                        if (model.NotifyEmail)
                        {
                            string email_contents = htmlGenerator.GenerateHtml("NotifyEmail.html",
                                                                               new
                            {
                                Name       = $"{user.FirstName} {user.LastName}",
                                Company    = model.Company,
                                Email      = model.Email,
                                Phone      = model.PhoneNumber,
                                Address    = model.Address,
                                Aggregator = aggregatorGroup.AggName
                            });

                            string sender = "PEIU 운영팀";
                            string target = "";

                            List <string> supervisor_emails = (await _userManager.GetUsersInRoleAsync(UserRoleTypes.Supervisor)).Select(x => x.Email).ToList();
                            target = "중개거래사업자";

                            var agg_result = _accountContext.VwAggregatorusers.Where(x => x.AggGroupId == model.AggregatorGroupId);
                            supervisor_emails.AddRange(agg_result.Select(x => x.Email));

                            //var aggregator_account_users = await _userManager.GetUsersInRoleAsync(UserRoleTypes.Supervisor);
                            await _emailSender.SendEmailAsync(sender, $"새로운 {target} 가입이 요청되었습니다", email_contents, registerModel, supervisor_emails.ToArray());

                            logger.LogInformation($"가입 알림 메일 전송: {string.Join(", ", supervisor_emails)}");
                        }
                        trans.Commit();
                        return(Ok(new { Result = result }));
                    }
                    else
                    {
                        trans.Dispose();
                        return(BadRequest(new { Result = result }));
                    }
                }
                catch (Exception ex)
                {
                    trans.Dispose();
                    logger.LogError(ex, ex.Message);
                }
            }
            return(BadRequest());
        }
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> SignonContractor([FromBody] AggregatorRegistModelBase model)
        {
            //TransactionScope trans_scope = new TransactionScope(System.Transactions.TransactionScopeAsyncFlowOption.Enabled);
            var trans_scope = await accountEF.Database.BeginTransactionAsync();

            try

            {
                if (ModelState.IsValid)
                {
                    using (NHibernate.ISession session = _accountContext.SessionFactory.OpenSession())
                        using (ITransaction trans = session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                        {
                            AggregatorGroup aggregatorGroup = await session.GetAsync <AggregatorGroup>(model.AggregatorGroupId);

                            if (aggregatorGroup == null)
                            {
                                if (model.Type == RegisterType.Contrator)
                                {
                                    IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).AggregatorNotFounded(model.AggregatorGroupId);
                                    IdentityResult _result = IdentityResult.Failed(error);
                                    return(base.BadRequest(new { Result = _result }));
                                }
                                else
                                {
                                    var groups = await session.CreateCriteria <AggregatorGroup>()
                                                 .Add(Restrictions.Eq("AggName", model.Company))
                                                 .ListAsync <AggregatorGroup>();

                                    aggregatorGroup = groups.FirstOrDefault();
                                    if (aggregatorGroup == null)
                                    {
                                        aggregatorGroup                = new AggregatorGroup();
                                        aggregatorGroup.ID             = Guid.NewGuid().ToString();
                                        aggregatorGroup.AggName        = model.Company;
                                        aggregatorGroup.Representation = "";
                                        aggregatorGroup.Address        = model.Address;
                                        aggregatorGroup.CreateDT       = DateTime.Now;
                                        aggregatorGroup.PhoneNumber    = model.PhoneNumber;
                                        await session.SaveAsync(aggregatorGroup);
                                    }
                                }
                            }


                            var user = CreateUserAccount(model);

                            JObject obj    = JObject.FromObject(user);
                            var     result = await _userManager.CreateAsync(user, model.Password);

                            //result.Errors
                            if (result.Succeeded)
                            {
                                RegisterAccount(session, user, model.AggregatorGroupId);
                                RegisterFileRepositary  registerModel           = RegisterFile(session, user.Id, model.RegisterFilename, model.RegisterFilebase64);
                                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                                await Publisher.PublishMessageAsync(obj.ToString(), cancellationTokenSource.Token);

                                logger.LogInformation($"회원 가입 성공: {obj}");
                                if (model.NotifyEmail)
                                {
                                    string email_contents = htmlGenerator.GenerateHtml("NotifyEmail.html",
                                                                                       new
                                    {
                                        Name       = $"{user.FirstName} {user.LastName}",
                                        Company    = model.Company,
                                        Email      = model.Email,
                                        Phone      = model.PhoneNumber,
                                        Address    = model.Address,
                                        Aggregator = aggregatorGroup.AggName
                                    });

                                    string sender = "PEIU 운영팀";
                                    string target = "";

                                    List <string> supervisor_emails = (await _userManager.GetUsersInRoleAsync(UserRoleTypes.Supervisor)).Select(x => x.Email).ToList();
                                    if (model.Type == RegisterType.Aggregator)
                                    {
                                        target = "중개거래사업자";
                                    }
                                    else if (model.Type == RegisterType.Contrator)
                                    {
                                        target = "발전사업자";
                                        var agg_result = await session.CreateCriteria <VwAggregatoruser>()
                                                         .Add(Restrictions.Eq("AggGroupId", model.AggregatorGroupId))
                                                         .ListAsync <VwAggregatoruser>();

                                        supervisor_emails.AddRange(agg_result.Select(x => x.Email));

                                        //targetEmailUsers = await _userManager.GetUsersInRoleAsync(UserRoleTypes.Aggregator);
                                        //targetEmailUsers = targetEmailUsers.Where(x=>x.agg)
                                    }
                                    else if (model.Type == RegisterType.Supervisor)
                                    {
                                        target = "관리자";
                                    }

                                    //var aggregator_account_users = await _userManager.GetUsersInRoleAsync(UserRoleTypes.Supervisor);
                                    await _emailSender.SendEmailAsync(sender, $"새로운 {target} 가입이 요청되었습니다", email_contents, registerModel, supervisor_emails.ToArray());

                                    logger.LogInformation($"가입 알림 메일 전송: {string.Join(", ", supervisor_emails)}");
                                }
                                //throw new Exception();
                                await trans.CommitAsync();

                                //trans.Commit();
                                trans_scope.Commit();
                                return(Ok(new { Result = result }));
                            }
                            else
                            {
                                trans_scope.Dispose();
                                return(BadRequest(new { Result = result }));
                            }
                        }
                }
                else
                {
                    trans_scope.Dispose();
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                trans_scope.Dispose();
                logger.LogError(ex, ex.Message);
                return(BadRequest());
            }
        }