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

STHApplication

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

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

namespace JiDangJia.Views;

public sealed class LegalConsentPanel : VerticalStackLayout
{
    private readonly INavigation navigation;
    private readonly CheckBox user=new(){Color=Ui.Bronze,AutomationId="legal-user-consent"};
    private readonly CheckBox privacy=new(){Color=Ui.Bronze,AutomationId="legal-privacy-consent"};
    private readonly CheckBox mobile=new(){Color=Ui.Bronze,AutomationId="legal-mobile-consent"};
    private readonly Label status=Ui.Text("正在加载注册登录条款…",11,Ui.Muted);
    private readonly SemaphoreSlim loading=new(1,1);
    private LegalPolicies? policies;
    public LegalConsentPanel(INavigation navigation)
    {
        this.navigation=navigation;Spacing=0;
        Add(Ui.Text("注册 / 登录条款",13,Ui.Bronze,true));
        Add(Row(user,"我已阅读并同意《用户协议》",()=>policies?.UserAgreement));
        Add(Row(privacy,"我已阅读并同意《隐私政策》",()=>policies?.PrivacyPolicy));
        Add(Row(mobile,"我已阅读并同意《中国移动认证服务条款》",()=>policies?.ChinaMobile));
        Add(Ui.Text("中国移动条款仅在使用其认证服务时适用,当前尚未接入。",11,Ui.Muted));Add(status);
        SetAvailable(false);
    }
    private View Row(CheckBox box,string text,Func<LegalDocument?> document)
    {
        box.WidthRequest=44;box.HeightRequest=44;SemanticProperties.SetDescription(box,text);
        var link=Ui.Text(text,12,Ui.Bronze);link.TextDecorations=TextDecorations.Underline;
        var grid=new Grid{ColumnDefinitions=[new(44),new(GridLength.Star)],ColumnSpacing=4};grid.Add(box);
        grid.Add(Ui.Tap(link,()=>navigation.PushAsync(new LegalDocumentPage(document()??throw new InvalidOperationException("条款尚未加载,请重试"))),"阅读"+text),1);return grid;
    }
    private void SetAvailable(bool value){user.IsEnabled=privacy.IsEnabled=mobile.IsEnabled=value;}
    public async Task Refresh()
    {
        await loading.WaitAsync();try
        {
            var latest=await AuthClient.Current.LegalPolicies();
            bool changed=policies is not null&&(policies.UserAgreement.Version!=latest.UserAgreement.Version||policies.PrivacyPolicy.Version!=latest.PrivacyPolicy.Version||policies.ChinaMobile.Version!=latest.ChinaMobile.Version);
            policies=latest;if(changed){user.IsChecked=privacy.IsChecked=mobile.IsChecked=false;}
            status.Text=changed?"条款已更新,请重新阅读并勾选。":"协议 v"+latest.UserAgreement.Version+" · 隐私 v"+latest.PrivacyPolicy.Version+(latest.UserAgreement.Content.Contains("[待填写")||latest.PrivacyPolicy.Content.Contains("[待填写")?" · 草稿信息待运营者完善":"");
            SetAvailable(true);
        }
        catch{status.Text="条款加载失败,点击登录时将重试。";SetAvailable(false);throw;}
        finally{loading.Release();}
    }
    public LegalConsent ReadConsent()
    {
        if(policies is null)throw new LegalConsentRequiredException("条款尚未加载,请联网后重试");
        var consent=policies.Consent(user.IsChecked,privacy.IsChecked,mobile.IsChecked);
        if(!LegalPolicyRules.AllAccepted(consent))throw new LegalConsentRequiredException();return consent;
    }
}

public sealed class LegalDocumentPage : ContentPage
{
    public LegalDocumentPage(LegalDocument document)
    {
        Title=document.Title;var text=Ui.Text(document.Content,15);text.LineHeight=1.4;
        var body=Ui.Stack(Ui.Text(document.Title,24,bold:true),Ui.Text("版本 "+document.Version+" · "+(document.PublishedAt.Length==0?"待发布预览":document.PublishedAt),11,Ui.Muted),Ui.Text(document.ChangeNote,12,Ui.Muted),Ui.Divider(),text);
        if(document.ExternalUrl.Length>0)body.Add(Ui.Button("阅读中国移动官方完整条款",async()=>{if(document.ExternalUrl!=LegalPolicyRules.ChinaMobileUrl)throw new InvalidOperationException("官方条款地址无效");await Browser.Default.OpenAsync(document.ExternalUrl,BrowserLaunchMode.SystemPreferred);}));
        body.Padding=22;Content=new ScrollView{Content=body};
    }
}

public sealed class LegalCenterPage : ContentPage
{
    private readonly VerticalStackLayout body=Ui.Stack();
    public LegalCenterPage(){Title="协议与隐私政策";body.Padding=20;Content=new ScrollView{Content=body};}
    protected override async void OnAppearing()
    {
        base.OnAppearing();body.Clear();try
        {
            var policies=await AuthClient.Current.LegalPolicies();
            foreach(var document in new[]{policies.UserAgreement,policies.PrivacyPolicy,policies.ChinaMobile})body.Add(Ui.Button(document.Title+" · v"+document.Version,()=>Navigation.PushAsync(new LegalDocumentPage(document)),false));
            var receipt=await AuthClient.Current.LegalStatus();body.Add(Ui.Text(receipt.AcceptedAt.Length==0?"尚无账户同意记录":$"本账户同意记录:协议 v{receipt.UserAgreementVersion} / 隐私 v{receipt.PrivacyPolicyVersion} / 移动条款 v{receipt.ChinaMobileVersion}\n{receipt.AcceptedAt}",12,Ui.Muted));
            if(!receipt.Current)body.Add(Ui.Text("条款已更新,下次登录需重新阅读并勾选。",13,Ui.Bronze));
        }
        catch(Exception ex){body.Add(Ui.Text(ex.Message,13,Ui.Red));}
    }
}

public sealed class LegalAdminPage : ContentPage
{
    private readonly VerticalStackLayout body=Ui.Stack();
    private readonly Entry title=new(){Placeholder="协议标题",MaxLength=80,AutomationId="legal-admin-title"};
    private readonly Entry note=new(){Placeholder="本次更新说明(用户可见)",MaxLength=500,AutomationId="legal-admin-note"};
    private readonly Editor editor=new(){HeightRequest=460,MaxLength=LegalPolicyRules.MaxCharacters,AutoSize=EditorAutoSizeOption.Disabled,AutomationId="legal-admin-content"};
    private readonly Label state=Ui.Text("",12,Ui.Muted);
    private LegalPolicies? policies;private string key=LegalPolicyRules.UserAgreement,sourceFile="";
    private LegalDocument Current=>key==LegalPolicyRules.UserAgreement?policies!.UserAgreement:policies!.PrivacyPolicy;
    public LegalAdminPage()
    {
        if(!AuthClient.Current.IsAdmin)throw new InvalidOperationException("需要管理员权限");Title="用户协议与隐私政策管理";body.Padding=18;Content=new ScrollView{Content=body};
    }
    protected override async void OnAppearing(){base.OnAppearing();if(policies is null)try{await Load();}catch(Exception ex){body.Clear();body.Add(Ui.Text(ex.Message,13,Ui.Red));body.Add(Ui.Button("重新加载",Load,false));}}
    private async Task Load(){policies=await AuthClient.Current.LegalPolicies();Render();}
    private void Render()
    {
        var document=Current;sourceFile="";title.Text=document.Title;editor.Text=document.Content;note.Text="";
        state.Text="当前版本 "+document.Version+" · 发布时间 "+document.PublishedAt;body.Clear();
        body.Add(Ui.Row(Ui.Button("用户协议",()=>Select(LegalPolicyRules.UserAgreement),key==LegalPolicyRules.UserAgreement),Ui.Button("隐私政策",()=>Select(LegalPolicyRules.PrivacyPolicy),key==LegalPolicyRules.PrivacyPolicy)));
        body.Add(state);body.Add(Ui.Text("可直接编辑或导入 TXT、Markdown、DOCX(最多 2 MB)。导入后先预览,点击发布才替换当前版本;历史正文和用户同意记录保留。",12,Ui.Muted));
        body.Add(title);body.Add(Ui.Button("导入新协议文件",Import,false));body.Add(editor);body.Add(note);
        body.Add(Ui.Button("预览发布内容",()=>Navigation.PushAsync(new LegalDocumentPage(Draft())),false));
        body.Add(Ui.Button("发布新版本",Publish));body.Add(Ui.Button("查看历史版本",()=>Navigation.PushAsync(new LegalHistoryPage(key)),false));body.Add(Ui.Button("重新加载当前版本",Load,false));
        body.Add(Ui.Card(Ui.Stack(Ui.Text("中国移动认证服务条款",16,bold:true),Ui.Text("使用中国移动官方链接,平台后台不能改写其条款。当前尚未接入号码认证。",12,Ui.Muted),Ui.Button("查看条款入口",()=>Navigation.PushAsync(new LegalDocumentPage(policies!.ChinaMobile)),false))));
    }
    private async Task Select(string value)
    {if(value==key)return;if((editor.Text!=Current.Content||!string.IsNullOrWhiteSpace(note.Text)||title.Text!=Current.Title)&&!await DisplayAlertAsync("切换协议","未发布的编辑不会保留,确认切换?","切换","继续编辑"))return;key=value;Render();}
    private LegalDocument Draft()=>Current with{Title=(title.Text??"").Trim(),Content=LegalPolicyRules.Normalize(editor.Text??""),Version=Current.Version+1,PublishedAt="",ChangeNote=note.Text??"",SourceFileName=sourceFile};
    private async Task Import()
    {
        var file=await FilePicker.Default.PickAsync(new PickOptions{PickerTitle="选择协议文件",FileTypes=new FilePickerFileType(new Dictionary<DevicePlatform,IEnumerable<string>>{[DevicePlatform.Android]=["text/plain","text/markdown","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[DevicePlatform.WinUI]=[".txt",".md",".docx"]})});if(file is null)return;
        await using var stream=await file.OpenReadAsync();using var memory=new MemoryStream();var buffer=new byte[8192];int count;
        while((count=await stream.ReadAsync(buffer))>0){if(memory.Length+count>LegalPolicyRules.MaxImportBytes)throw new ArgumentException("协议文件不能超过 2 MB");memory.Write(buffer,0,count);}
        var content=LegalDocumentImport.Read(memory.ToArray(),file.FileName);editor.Text=content;sourceFile=Path.GetFileName(file.FileName);state.Text="已导入 "+sourceFile+" · "+content.Length+" 字符,尚未发布";
    }
    private async Task Publish()
    {
        var draft=Draft();if(!await DisplayAlertAsync("发布新版本",draft.Title+" · "+draft.Content.Length+" 字符\n发布后,新注册、登录和恢复登录需同意新版本。确认发布?","发布","返回编辑"))return;
        var result=await AuthClient.Current.PublishLegal(key,new(Current.Version,draft.Title,draft.Content,draft.ChangeNote,sourceFile));await Load();state.Text="已发布版本 "+result.Version+";历史同意记录仍对应原版本。";
    }
}

public sealed class LegalHistoryPage : ContentPage
{
    private readonly string key;private readonly VerticalStackLayout body=Ui.Stack();private long before;
    public LegalHistoryPage(string key){this.key=key;Title="协议历史版本";body.Padding=20;Content=new ScrollView{Content=body};}
    protected override async void OnAppearing(){base.OnAppearing();if(body.Count==0)try{await More();}catch(Exception ex){body.Add(Ui.Text(ex.Message,13,Ui.Red));}}
    private async Task More()
    {
        var versions=await AuthClient.Current.LegalHistory(key,before);foreach(var version in versions)
        {
            body.Add(Ui.Card(Ui.Stack(Ui.Text(version.Title+" · v"+version.Version,17,bold:true),Ui.Text(version.PublishedAt+"\n"+version.ChangeNote,12,Ui.Muted),Ui.Button("阅读此版本",async()=>await Navigation.PushAsync(new LegalDocumentPage(await AuthClient.Current.LegalVersion(key,version.Version))),false))));before=version.Version;
        }
        if(versions.Count==40){Button? more=null;more=Ui.Button("加载更早版本",async()=>{body.Remove(more!);await More();},false);body.Add(more);}
    }
}