XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

STHApplication

【MAUI】寄当家——安卓端交易管理系统

公开
关注 0 Fork 0 Star 0
UTF-8
using JiDangJia.Core;
using JiDangJia.Services;

namespace JiDangJia.Views;

public sealed class LoginPage : ContentPage
{
    private readonly AuthClient auth=AuthClient.Current;
    private readonly Entry username=new(){Placeholder="手机号 / 登录账号",Keyboard=Keyboard.Email,ReturnType=ReturnType.Next};
    private readonly Entry password=new(){Placeholder="输入密码(至少 8 位)",IsPassword=true,ReturnType=ReturnType.Done};
    private readonly Entry name=new(){Placeholder="您的称呼 / 门店联系人"};
    private readonly Entry code=new(){Placeholder="输入管理员分发的 JDJ 卡密",MaxLength=40,Keyboard=Keyboard.Text,ReturnType=ReturnType.Done};
    private readonly Label error=Ui.Text("",12,Ui.Red);
    private readonly Button action;
    private readonly Label mode;
    private readonly Border nameBox;
    private readonly View codeBox,codeLink;
    private readonly PurchasePanel purchases;
    private readonly LegalConsentPanel legal;
    private readonly IDispatcherTimer priceTimer;
    private bool register,restored;
    public LoginPage(bool activationRequired=false,string account="")
    {
        Title=AppProduct.Name;NavigationPage.SetHasNavigationBar(this,false);
        var brand=Ui.Stack(Ui.Icon("home",Ui.Gold,49),Ui.Text(AppProduct.Name,38,Ui.Paper,true),Ui.Text(AppProduct.Tagline,14,Ui.Gold));brand.Padding=new Thickness(30,55,30,48);brand.Spacing=19;
        var hero=new Grid {BackgroundColor=Ui.Ink};hero.Add(new GraphicsView {Drawable=new RibbonDrawable(),InputTransparent=true});hero.Add(brand);
        action=Ui.Button("登录",Submit);mode=Ui.Text(AppProduct.RegisterPrompt,12,Ui.Bronze);
        nameBox=Ui.Card(name,12,new Thickness(14,0),Ui.Paper);nameBox.IsVisible=false;
        codeBox=Ui.Stack(Ui.Text("卡密激活 / 续费",13,Ui.Bronze,true),Ui.Card(code,12,new Thickness(14,0),Ui.Paper),Ui.Text("首次使用或续期请填写卡密,兑换后绑定此账户与设备。",11,Ui.Muted));codeBox.IsVisible=false;
        codeLink=Ui.Tap(Ui.Text("有卡密?点击输入",12,Ui.Bronze),()=>{RevealCode();return Task.CompletedTask;},"有卡密?点击输入");
        purchases=PurchaseUi.Panel(Navigation,async value=>{code.Text=value;RevealCode();await Navigation.PopAsync();});
        legal=new LegalConsentPanel(Navigation);
        priceTimer=Dispatcher.CreateTimer();priceTimer.Interval=TimeSpan.FromMinutes(1);priceTimer.Tick+=(_,_)=>{_ = purchases.Refresh();};
        var form=Ui.Stack(Ui.Text("欢迎回来",25,bold:true),Ui.Text("已有有效授权可直接登录,首次使用请激活卡密。",12,Ui.Muted),Ui.Card(username,12,new Thickness(14,0),Ui.Paper),Ui.Card(password,12,new Thickness(14,0),Ui.Paper),nameBox,codeBox,legal,error,action,codeLink,Ui.Tap(mode,()=>{SetMode(!register);error.Text="";return Task.CompletedTask;}),Ui.Divider(),purchases);
        form.Padding=new Thickness(26,30,26,40);form.Spacing=15;Content=new ScrollView {Content=Ui.Stack(hero,form)};
        username.Text=account;if(activationRequired){restored=true;RevealCode();error.Text=new ActivationRequiredException(account).Message;}
    }
    protected override async void OnAppearing()
    {
        base.OnAppearing();priceTimer.Start();_ = purchases.Refresh();action.IsEnabled=false;
        try
        {
            if(!restored)
            {
                restored=true;
                try{if(await auth.Restore()){await EnterApp();return;}}
                catch(ActivationRequiredException ex){username.Text=ex.Username;RevealCode();error.Text=ex.Message;}
                catch(LegalConsentRequiredException ex){error.Text=ex.Message;}
            }
            await legal.Refresh();
        }
        catch(Exception ex){error.Text=ex.Message;}
        finally{action.IsEnabled=true;_ = AppUpdates.Check(this);}
    }
    protected override void OnDisappearing(){priceTimer.Stop();base.OnDisappearing();}
    private async Task Submit()
    {
        error.Text="";
        try
        {
            await legal.Refresh();var consent=legal.ReadConsent();
            if(string.IsNullOrWhiteSpace(username.Text)||string.IsNullOrWhiteSpace(password.Text))throw new ArgumentException("请填写账号与密码");
            var account=username.Text;var secret=password.Text;var activation=code.Text;
            if(register){await auth.RegisterAccount(account,secret,name.Text??"",consent);SetMode(false);}
            await auth.Login(account,secret,activation,consent);await EnterApp();
        }
        catch(ActivationRequiredException ex){RevealCode();error.Text=ex.Message;}
        catch(Exception ex){error.Text=ex.Message;}
    }
    private void SetMode(bool value)
    {
        register=value;nameBox.IsVisible=value;action.Text=value?"注册并登录":"登录";mode.Text=value?"已有账户?返回登录":AppProduct.RegisterPrompt;
    }
    private void RevealCode(){codeBox.IsVisible=true;codeLink.IsVisible=false;}
    public static async Task EnterApp()
    {
        try{var auth=AuthClient.Current;await AppLock.Load();AccountDataClear.Pending();if(AppLock.Enabled){AppLock.Cover(Application.Current!.Windows[0],CreateRoot);return;}CreateRoot();}
        catch(Exception ex){var page=Application.Current?.Windows.FirstOrDefault()?.Page;if(page is not null)await page.DisplayAlertAsync("无法进入账户",ex.Message,"知道了");}
    }
    private static void CreateRoot()
    {
        var auth=AuthClient.Current;auth.RequireLicense();
#if COMMUNITY_APP
        Application.Current!.Windows[0].Page=new NavigationPage(new MainPage());
#else
        var db=new Database(Path.Combine(FileSystem.AppDataDirectory,"accounts",auth.AccountId,"pawn.db"));
        var accountId=auth.AccountId;db.BeforeWrite=()=>{if(auth.AccountId!=accountId)throw new InvalidOperationException("登录账户已切换,请返回首页");auth.RequireLicense();};
        var owner=db.Query("SELECT * FROM User LIMIT 1").First();owner["name"]=auth.Name;owner["phone"]=auth.Username;db.Save("User",owner);
        var root=new MainPage(new BusinessService(db));Application.Current!.Windows[0].Page=new NavigationPage(root);
        _=OrderCameraRecovery.Restore(root,new BusinessService(db));
#endif
    }
    public static void ShowLogin(bool activationRequired=false,string account=""){if((Application.Current!.Windows[0].Page as NavigationPage)?.RootPage is MainPage root)root.Suspend();Application.Current!.Windows[0].Page=new NavigationPage(new LoginPage(activationRequired,account));}
}

public sealed class LicensePage : ContentPage
{
    private readonly AuthClient auth=AuthClient.Current;
    private readonly Label status=Ui.Text("",15,Ui.Bronze,true);
    public LicensePage()
    {
        Title="账户与授权";var code=new Entry {Placeholder="输入管理员分发的 JDJ 卡密",MaxLength=40};
        var body=Ui.Stack();body.Padding=22;
        body.Add(Ui.Card(Ui.Stack(Ui.Row(Ui.Icon("shield",Ui.Gold,36),Ui.Stack(Ui.Text(auth.Name,22,bold:true),Ui.Text(auth.Username,12,Ui.Muted))),Ui.Divider(),status)));
        body.Add(Ui.Card(Ui.Stack(Ui.Section("卡密激活 / 续费"),Ui.Text("输入管理员提供的卡密,授权绑定此账户与设备。续费将在现有有效期上累加。",12,Ui.Muted),Ui.Card(code,12,new Thickness(12,0),Ui.Paper),Ui.Button("确认激活",async()=> {await auth.Activate(code.Text??"");Refresh();await DisplayAlertAsync("激活成功","授权已更新。","完成");}))));
#if COMMUNITY_APP
        body.Add(Ui.Button("个人 / 企业认证",()=>Navigation.PushAsync(new IdentityPage()),false));
        body.Add(Ui.Button("我的举报",()=>Navigation.PushAsync(new MyReportsPage()),false));
#endif
        body.Add(Ui.Button("手机号绑定",()=>Navigation.PushAsync(new PhonePage()),false));
        body.Add(Ui.Button("协议与隐私政策",()=>Navigation.PushAsync(new LegalCenterPage()),false));
        body.Add(Ui.Button("购买卡密 / 续费",()=>Navigation.PushAsync(new PurchasePage("YEAR",async value=>{code.Text=value;await Navigation.PopAsync();})),false));
        body.Add(Ui.Button("购买永久卡",()=>Navigation.PushAsync(new PurchasePage("PERMANENT",async value=>{code.Text=value;await Navigation.PopAsync();})),false));
        body.Add(Ui.Button("申请发票",()=>Navigation.PushAsync(new PurchaseSupportPage(true)),false));
        body.Add(Ui.Button("我的购买订单",()=>Navigation.PushAsync(new PurchaseHistoryPage(async value=>{code.Text=value;await Navigation.PopAsync();})),false));
        body.Add(Ui.Button("联网校验授权",async()=> {await auth.RefreshLicense();Refresh();},false));
        body.Add(Ui.Card(Ui.Stack(Ui.Text("设备标识",12,Ui.Muted),Ui.Text(auth.DeviceId,10,Ui.Muted))));
        body.Add(Ui.Button("修改登录密码",async()=> {var old=await PasswordDialog.Ask(this,"修改密码","输入原密码");if(old is null)return;var password=await PasswordDialog.Ask(this,"修改密码","输入新密码(至少 8 位)");if(password is null)return;await auth.ChangePassword(old,password);LoginPage.ShowLogin();},false));
        body.Add(Ui.Button("退出账户",async()=> {await auth.Logout();LoginPage.ShowLogin();},false));
        Content=new ScrollView {Content=body};Refresh();
    }
    private void Refresh()=>status.Text=auth.Licensed?auth.Permanent?"永久授权":"授权有效至 "+auth.ExpiresAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm"):"授权未激活、已到期或已停用";
}