Ver código fonte

feat: 完成在地址管理页面中对地址的显示、添加、删除、修改和持久化

YuJing 1 mês atrás
pai
commit
6d8d6e5835

+ 4 - 4
commons/basic/src/main/ets/utils/arkts/utils/YTRouter.ets

@@ -133,8 +133,8 @@ class YTRouter extends NavPathStack {
   }
 
   // 前往借阅结果页面
-  router2BorrowAnsPage(){
-    this.pushPathByName('BorrowAnsPage', null)
+  router2BorrowAnsPage(isComplete: boolean){
+    this.pushPathByName('BorrowAnsPage', isComplete)
   }
 
   // 中心弹窗
@@ -158,8 +158,8 @@ class YTRouter extends NavPathStack {
   }
 
   // 添加地址页面
-  router2IncreaseAddressPage(status: number, callBack?: Callback<PopInfo>){
-    this.pushPathByName('IncreaseAddressPage', status, callBack)
+  router2IncreaseAddressPage(addressIndex?: number, callBack?: Callback<PopInfo>){
+    this.pushPathByName('IncreaseAddressPage', addressIndex, callBack)
   }
 
   // 预约还书页面

+ 40 - 0
features/feature/src/main/ets/apis/AddressApi.ets

@@ -0,0 +1,40 @@
+import { YTRequest } from "basic";
+import { Address } from "../model/Address";
+import { ApiUrl } from "./ApiUrl";
+
+export class AddressApi {
+  /**
+   * 获取地址列表
+   * @returns
+   */
+  static getAddressList(): Promise<Address[]> {
+    return YTRequest.post<Array<Address>>(ApiUrl.getAddress, {});
+  }
+
+  /**
+   * 添加地址
+   * @param address 地址信息
+   * @returns
+   */
+  static addAddress(address: Address): Promise<boolean> {
+    return YTRequest.post<boolean>(ApiUrl.addAddress, address);
+  }
+
+  /**
+   * 删除地址
+   * @param id 地址ID
+   * @returns
+   */
+  static removeAddress(addressId: string): Promise<boolean> {
+    return YTRequest.post<boolean>(ApiUrl.removeAddress, { addressId });
+  }
+
+  /**
+   * 修改地址
+   * @param address 地址信息
+   * @returns
+   */
+  static updateAddress(address: Address): Promise<boolean> {
+    return YTRequest.post<boolean>(ApiUrl.updateAddress, address);
+  }
+}

+ 34 - 1
features/feature/src/main/ets/apis/ApiUrl.ets

@@ -73,6 +73,39 @@ export class ApiUrl {
    */
   static getUnifiedPayInfo = '/api/book/order/pay';
 
-  // 获取订单分页
+  /**
+   * @description 获取订单分页
+   * @method POST
+   */
   static getOrderPage = '/api/book/order/page';
+
+  /**
+   * @description 轮询查询订单状态
+   * @method POST
+   */
+  static queryOrderStatus = '/api/book/order/queryPayStatus';
+
+  /**
+   * @description 添加地址
+   * @method POST
+   */
+  static addAddress = '/api/book/address/addAddress';
+
+  /**
+   * @description 删除地址
+   * @method POST
+   */
+  static removeAddress = '/api/book/address/removeAddress'
+
+  /**
+   * @description 修改地址
+   * @method POST
+   */
+  static updateAddress = '/api/book/address/updateAddress'
+
+  /**
+   * @description 获取地址
+   * @method POST
+   */
+  static getAddress = '/api/book/address/list'
 }

+ 6 - 0
features/feature/src/main/ets/apis/OrderApi.ets

@@ -1,6 +1,7 @@
 import { BookItem, YTRequest } from "basic";
 import { DepositData, GetUnifiedPayInfoRequestData,
   OrderDetailData,
+  OrderPayResultData,
   OrderValidationData } from "../model/OrderModelIndex";
 import { PageResponse } from "../model/PageResponse";
 import { bookPackageQuery, userOrderQuery } from "../model/Query";
@@ -66,4 +67,9 @@ export class OrderApi {
   static getUserOrderList(param: userOrderQuery): Promise<PageResponse<OrderDetailData>> {
     return YTRequest.post<PageResponse<OrderDetailData>, userOrderQuery>(ApiUrl.getOrderPage, param)
   }
+
+  // 查询订单状态
+  static queryOrderStatus(orderId: string): Promise<OrderPayResultData> {
+    return YTRequest.post<OrderPayResultData>(ApiUrl.queryOrderStatus, {orderId})
+  }
 }

+ 1 - 7
features/feature/src/main/ets/components/AddressItemComp.ets

@@ -11,12 +11,7 @@ export struct AddressItemComp {
   @Param isLocation: boolean = true
   @Param align_: VerticalAlign = VerticalAlign.Center
 
-  @Param address: Address = {
-    userName: '占三峰',
-    phone: '13598728343',
-    address: '高新区火炬园路321号韩菲诗.诚享大厦304室内',
-    region: '福建-厦门-火炬园',
-  }
+  @Param address: Address = {}
 
   @Event click: () => void
 
@@ -28,7 +23,6 @@ export struct AddressItemComp {
         Image($r('[basic].media.icon_send')).width(24).aspectRatio(1)
       }
 
-
       Column({space: 5}){
         Text(`${this.address.region?.split('-').join('')}${this.address.address}`)
           .attributeModifier(new CustomTextStyle({ size: 14, weight: 400, color: '#FF000000' }))

+ 3 - 0
features/feature/src/main/ets/components/chooseAddress.ets

@@ -17,16 +17,19 @@ export struct ChooseAddress {
     let index = 0
 
     index = arr.findIndex(item => this.address!.includes(item.text))
+    index = index < 0 ? 0 : index
     this.value.push(arr[index].value)
 
     arr = arr[index].children!
     if(!arr) return
     index = arr.findIndex(item => this.address!.includes(item.text))
+    index = index < 0 ? 0 : index
     this.value.push(arr[index].value)
 
     arr = arr[index].children!
     if(!arr) return
     index = arr.findIndex(item => this.address!.includes(item.text))
+    index = index < 0 ? 0 : index
     this.value.push(arr[index].value)
   }
 

+ 52 - 5
features/feature/src/main/ets/model/Address.ets

@@ -1,21 +1,68 @@
 export interface Address {
+  /**
+   * 地址ID
+   */
+  id?: string;
+
+  /**
+   * 用户ID
+   */
+  userId?: string;
+
+  /**
+   * 收件人名称
+   */
+  userName?: string;
+
   /**
    * 手机
    */
   phone?: string;
 
+  /**
+   * 详细地区(格式如:XXX-XXX-XXX)
+   */
+  region?: string;
+
   /**
    * 详细地址
    */
   address?: string;
 
   /**
-   * 详细地区(格式如:XXX-XXX-XXX)
+   * 创建者
    */
-  region?: string;
+  createBy?: string;
 
   /**
-   * 收件人名称
+   * 创建时间
    */
-  userName?: string;
-}
+  createTime?: string;
+
+  /**
+   * 更新者
+   */
+  updateBy?: string;
+
+  /**
+   * 更新时间
+   */
+  updateTime?: string;
+
+
+  // // todo
+  // constructor(data?: Address) {
+  //   if (data) {
+  //     this.id = data.id;
+  //     this.userId = data.userId;
+  //     this.userName = data.userName;
+  //     this.phone = data.phone;
+  //     this.region = data.region;
+  //     this.address = data.address;
+  //     this.createBy = data.createBy;
+  //     this.createTime = data.createTime;
+  //     this.updateBy = data.updateBy;
+  //     this.updateTime = data.updateTime;
+  //   }
+  // }
+}

+ 8 - 0
features/feature/src/main/ets/model/OrderModelIndex.ets

@@ -217,3 +217,11 @@ export interface OrderDetailData {
    */
   bookPrice?: string;
 }
+
+
+/**
+ * 订单支付结果数据结构
+ */
+export interface OrderPayResultData {
+  flag: string
+}

+ 1 - 0
features/feature/src/main/ets/model/RouterModel.ets

@@ -1,6 +1,7 @@
 import { BookItem } from "basic";
 import { OrderStatus } from "./EnumState";
 
+// 订单详情 - 路由参数
 export class OrderDetailModel{
   bookList: Array<BookItem> = []
   status: OrderStatus = OrderStatus.UNCONFIRMED

+ 36 - 1
features/feature/src/main/ets/model/Storage.ets

@@ -1,6 +1,8 @@
 import { BookItem } from "basic"
+import { AddressApi } from "../apis/AddressApi"
 import { bookListApi } from "../apis/BookListApi"
 import { OrderApi } from "../apis/OrderApi"
+import { Address } from "./Address"
 import { BookListTypeItem, BookListTypeList } from "./BookModelIndex"
 import { PageResponse } from "./PageResponse"
 import { bookPackageQuery } from "./Query"
@@ -91,4 +93,37 @@ export class CartStorage{
 
 // 用户地址
 @ObservedV2
-export class UserAddressStorage{}
+export class UserAddressStorage{
+  @Trace addressList: Array<Address> = []
+
+  constructor() {
+    this.getUserAddressList()
+  }
+
+  // 获取用户地址列表
+  async getUserAddressList(){
+    let list = await AddressApi.getAddressList()
+    this.addressList = list ?? []
+  }
+
+  // 删除用户地址
+  async deleteUserAddress(id: string){
+    let ans = await AddressApi.removeAddress(id)
+    console.log(`ans = ${JSON.stringify(ans)}`)
+    this.getUserAddressList()
+  }
+
+  // 添加地址
+  async addUserAddress(address: Address){
+    let ans = await AddressApi.addAddress(address)
+    console.log(`ans = ${JSON.stringify(ans)}`)
+    this.getUserAddressList()
+  }
+
+  // 修改地址
+  async updateUserAddress(address: Address){
+    let ans = await AddressApi.updateAddress(address)
+    console.log(`ans = ${JSON.stringify(ans)}`)
+    this.getUserAddressList()
+  }
+}

+ 9 - 5
features/feature/src/main/ets/pages/Address/AddressManagementPage.ets

@@ -2,21 +2,25 @@ import { RouterPage, YTAvoid, YTHeader, yTRouter } from 'basic'
 import { AddressItemComp } from '../../components/AddressItemComp'
 import { buttonComp } from '../../components/BuilderIndex'
 import { AddressAddPageState } from '../../model/EnumState'
+import { UserAddressStorage } from '../../model/Storage'
 import { CustomTextStyle } from '../../style/CustomTextStyle'
+import { AppStorageV2 } from '@kit.ArkUI'
+import { Address } from '../../model/Address'
 
 /**
  * 地址管理页面
  */
 @ComponentV2
-@RouterPage
 struct AddressManagementPage {
   @Local safeBottom: number = AppStorage.get(YTAvoid.SAFE_BOTTOM_KEY) as number
 
+  addressConnect: UserAddressStorage = AppStorageV2.connect(UserAddressStorage, () => new UserAddressStorage())!
+
   editAddress(index?: number){
     if(index != undefined){
-      yTRouter.router2IncreaseAddressPage(AddressAddPageState.EDIT)
+      yTRouter.router2IncreaseAddressPage(index)
     } else {
-      yTRouter.router2IncreaseAddressPage(AddressAddPageState.ADD)
+      yTRouter.router2IncreaseAddressPage()
     }
   }
 
@@ -28,8 +32,8 @@ struct AddressManagementPage {
         Column({space: 10}){
           Column(){
             List({space: 16}){
-              ForEach(new Array(10).fill(''), (item: string, index) => {
-                AddressItemComp({type: 1, click: () =>{
+              ForEach(this.addressConnect.addressList, (item: Address, index) => {
+                AddressItemComp({type: 1, address: item ,click: () =>{
                   this.editAddress(index)
                 }})
               })

+ 97 - 32
features/feature/src/main/ets/pages/Address/IncreaseAddressPage.ets

@@ -1,21 +1,35 @@
-import { BasicType, DiaLogSheetControl, YTAvoid, YTHeader, yTRouter } from 'basic'
+import { BasicType, DiaLogSheetControl, IBestToast, userInfo, YTAvoid, YTHeader, yTRouter } from 'basic'
 import { buttonComp } from '../../components/BuilderIndex'
 import { ChooseAddress } from '../../components/chooseAddress'
 import { AddressAddPageState } from '../../model/EnumState'
+import { UserAddressStorage } from '../../model/Storage'
 import { CustomTextStyle } from '../../style/CustomTextStyle'
+import { AppStorageV2 } from '@kit.ArkUI'
+import { Address } from '../../model/Address'
 
 /**
  * 新增地址页面
  */
 @ComponentV2
 struct IncreaseAddressPage {
-  @Param pageState: AddressAddPageState = AddressAddPageState.ADD
+  @Param @Require addressIndex?: number
 
   @Local safeBottom: number = AppStorage.get(YTAvoid.SAFE_BOTTOM_KEY) as number
+  // 页面状态
+  @Local pageState: AddressAddPageState = AddressAddPageState.ADD
   // 是否设置为默认地址
   @Local isDefaultAddress: boolean = false
-  // 选择的地址
+
+  // 选择的地址 以 - 进行分割
   @Local address: string = ''
+  // 收件人名称
+  @Local userName: string = ''
+  // 收货人手机号
+  @Local phone: string = ''
+  // 详细地址
+  @Local region: string = ''
+
+  addressConnect: UserAddressStorage = AppStorageV2.connect(UserAddressStorage, () => new UserAddressStorage())!
 
   forEach: Array<BasicType> = [
     { text: '收件人', message: '请输入收件人', type: 'Input' },
@@ -29,16 +43,23 @@ struct IncreaseAddressPage {
     let control: DiaLogSheetControl = new DiaLogSheetControl(this.getUIContext(), false, false)
     yTRouter.router2BottomDialog({
       control: control,
-      builder: () => { this.chooseAddress(control, this.address) }
+      builder: () => { this.chooseAddress(control, this.region) }
     }, (ans) => {
       let res = ans.result as Array<string>
-      this.address = res.join('-')
+      this.region = res.join('-')
     })
   }
 
   // 保存地址
-  saveAddress() {
-
+  async saveAddress() {
+    const addressItem: Address = this.getAddressObject()
+    if(this.pageState == AddressAddPageState.ADD) {
+      await this.addressConnect.addUserAddress(addressItem)
+    } else {
+      await this.addressConnect.updateUserAddress(addressItem)
+    }
+    IBestToast.show('保存成功')
+    yTRouter.pop()
   }
 
   // 设置为默认地址
@@ -53,12 +74,42 @@ struct IncreaseAddressPage {
     }, (info) => {
       let ans = info.result as number
       if(ans == 1) {
-        // todo 执行删除的逻辑
+        let id = this.addressConnect.addressList[this.addressIndex!].id
+        this.addressConnect.deleteUserAddress(id!)
         yTRouter.pop()
       }
     })
   }
 
+  // 初始化页面数据
+  initData() {
+    if(this.addressIndex != undefined) {
+      this.pageState = AddressAddPageState.EDIT
+      const addressItem: Address = this.addressConnect.addressList[this.addressIndex]
+      this.address = addressItem.address ?? ''
+      this.userName = addressItem.userName ?? ''
+      this.phone = addressItem.phone ?? ''
+      this.region = addressItem.region ?? ''
+    }
+  }
+
+  // 生成地址对象
+  getAddressObject(): Address {
+    let addressItem: Address = this.addressIndex ? this.addressConnect.addressList[this.addressIndex] : {}
+
+    addressItem.address = this.address
+    addressItem.userName = this.userName
+    addressItem.phone = this.phone
+    addressItem.region = this.region
+    addressItem.userId = userInfo.getId()!
+
+    return addressItem
+  }
+
+  aboutToAppear(): void {
+    this.initData()
+  }
+
   build() {
     NavDestination() {
       Column() {
@@ -75,13 +126,16 @@ struct IncreaseAddressPage {
                   .fontColor('#FF000000')
 
                 if(item.type == "Event"){
-                  Text(this.address || item.message)
+                  Text(this.region || item.message)
                     .fontSize(14)
                     .fontWeight(500)
                     .fontColor('#FF000000')
                     .onClick(item.click)
-                } else {
-                  TextInput({placeholder: item.message})
+                } else if(item.type == "Input" || item.type == "InputNumber") {
+                  TextInput({
+                    placeholder: item.message,
+                    text: item.text == '收件人' ? this.userName : item.text == '联系电话' ? this.phone : this.address,
+                  })
                     .padding(0)
                     .fontSize(14)
                     .borderRadius(0)
@@ -90,6 +144,15 @@ struct IncreaseAddressPage {
                     .placeholderFont({size: 14})
                     .backgroundColor(Color.Transparent)
                     .type(item.type == "Input" ? undefined : InputType.PhoneNumber)
+                    .onChange((text) => {
+                      if(item.text == '收件人') {
+                        this.userName = text
+                      } else if(item.text == '联系电话') {
+                        this.phone = text
+                      } else {
+                        this.address = text
+                      }
+                    })
                 }
               }
               .width('100%')
@@ -104,27 +167,29 @@ struct IncreaseAddressPage {
           .borderRadius(8)
           .backgroundColor(Color.White)
 
-
-          Row(){
-            Text('设为默认地址')
-              .attributeModifier(new CustomTextStyle({size: 14, weight: 500}))
-
-            if(this.isDefaultAddress) {
-              Image($r('[basic].media.icon_select'))
-                .width(15).aspectRatio(1)
-            } else {
-              Row()
-                .borderRadius(15)
-                .border({width: 1})
-                .width(15).aspectRatio(1)
+          // todo 是否保留
+          if(true) {
+            Row(){
+              Text('设为默认地址')
+                .attributeModifier(new CustomTextStyle({size: 14, weight: 500}))
+
+              if(this.isDefaultAddress) {
+                Image($r('[basic].media.icon_select'))
+                  .width(15).aspectRatio(1)
+              } else {
+                Row()
+                  .borderRadius(15)
+                  .border({width: 1})
+                  .width(15).aspectRatio(1)
+              }
             }
+            .padding(15)
+            .width('100%')
+            .borderRadius(8)
+            .backgroundColor(Color.White)
+            .justifyContent(FlexAlign.SpaceBetween)
+            .onClick(() =>{ this.setDefaultAddress() })
           }
-          .padding(15)
-          .width('100%')
-          .borderRadius(8)
-          .backgroundColor(Color.White)
-          .justifyContent(FlexAlign.SpaceBetween)
-          .onClick(() =>{ this.setDefaultAddress() })
         }
         .width('100%')
         .layoutWeight(1)
@@ -162,6 +227,6 @@ struct IncreaseAddressPage {
 }
 
 @Builder
-function IncreaseAddressBuilder(_: string, state?: AddressAddPageState) {
-  IncreaseAddressPage({pageState: state})
+function IncreaseAddressBuilder(_: string, addressIndex?: number) {
+  IncreaseAddressPage({addressIndex})
 }

+ 11 - 2
features/feature/src/main/ets/pages/Order/InitiatePayPage.ets

@@ -4,7 +4,7 @@ import { bundleManager, common } from '@kit.AbilityKit'
 import { BusinessError } from '@kit.BasicServicesKit'
 import { WebViewJavascriptBridge, WVJBResponseCallback } from '@yue/webview_javascript_bridge'
 import { YTAvoid, yTRouter } from 'basic'
-import { GetUnifiedPayInfoRequestData } from '../../model/OrderModelIndex'
+import { GetUnifiedPayInfoRequestData, OrderPayResultData } from '../../model/OrderModelIndex'
 import { OrderApi } from '../../apis/OrderApi'
 import { PageState } from '../../model/EnumState'
 
@@ -23,6 +23,8 @@ struct InitiatePayPage {
   navBarShow: boolean = true
   controller: webview.WebviewController = new webview.WebviewController()
   historyCurrIndex: number = 0
+  // 订单支付结果
+  orderState: OrderPayResultData = { flag: '0' }
 
   // WebViewJavascriptBridge 桥接
   private bridge: WebViewJavascriptBridge | undefined;
@@ -145,6 +147,8 @@ struct InitiatePayPage {
         this.onBackPress()
       }
     }
+
+    this.getPaymentResult()
   }
 
   // 页面自行处理返回逻辑,不进行页面路由
@@ -175,11 +179,16 @@ struct InitiatePayPage {
   }
 
   // todo 获取订单支付结果
-  async getPaymentResult(orderId: string): Promise<void> {
+  async getPaymentResult(): Promise<void> {
     /**
      * 前往借阅成功页面
      */
     // yTRouter.router2BorrowAnsPage()
+    this.orderState = await OrderApi.queryOrderStatus(this.orderId)
+    console.log(`订单状态 = ${JSON.stringify(this.orderState)}`)
+    if(this.orderState.flag == '1') {
+      yTRouter.router2BorrowAnsPage(true)
+    }
   }