图片上传

This commit is contained in:
xiaoxiao
2025-05-13 17:25:26 +08:00
parent 3d1c988435
commit ab1f72ba6c
12 changed files with 627 additions and 84 deletions
+3 -1
View File
@@ -10,4 +10,6 @@ export { ChooseEmailComp } from './src/main/ets/view/ChooseEmailComp'
export { ChooseOfficePhoneComp } from './src/main/ets/view/ChooseOfficePhoneComp'
export { EditUserDataComp } from './src/main/ets/view/EditUserDataComp'
export { EditUserDataComp } from './src/main/ets/view/EditUserDataComp'
export { SpecialitySelectedSheet } from './src/main/ets/view/SpecialitySelectedSheet'
@@ -1,12 +1,59 @@
import { hdHttp, HdResponse, BasicConstant, ExpertData, authStore } from '@itcast/basic'
import { BusinessError } from '@kit.BasicServicesKit';
import promptAction from '@ohos.promptAction';
import HashMap from '@ohos.util.HashMap';
import { router } from '@kit.ArkUI';
interface callBackData {
code: number,
message:string,
msg:string,
data: string
}
@Preview
@Component
export struct ChangePhoneComp {
@State phoneNumber: string = ''
@State smsCode: string = ''
@State countdown: number = 0
uploadChangePhoneAction(){
const hashMap: HashMap<string, string> = new HashMap();
hashMap.set('newMobile',this.phoneNumber)
hashMap.set('oldMobile',authStore.getUser().photo)
hashMap.set('sms',this.smsCode)
hdHttp.httpReq<string>(BasicConstant.urlmyLan+'updateMobile',hashMap).then(async (res: HdResponse<string>) => {
let json:callBackData = JSON.parse(res+'') as callBackData;
console.log('更新手机号数据:',json);
if (json.code == 200) {
promptAction.showToast({message:'修改成功'});
router.back();
} else {
promptAction.showToast({message:json.message});
}
}).catch((err: BusinessError) => {
console.info(`Response login succeeded: ${err}`);
})
}
uploadSmsAction(){
const hashMap: HashMap<string, string> = new HashMap();
hashMap.set('type','6');
hashMap.set('mobile',this.phoneNumber)
hdHttp.httpReq<string>(BasicConstant.urlmyLan+'smsSend',hashMap).then(async (res: HdResponse<string>) => {
let json:callBackData = JSON.parse(res+'') as callBackData;
console.log('获取验证码数据:',json);
if (json.code == 200) {
promptAction.showToast({message:'发送成功'});
this.startCountdown();
} else {
promptAction.showToast({message:json.message});
}
}).catch((err: BusinessError) => {
console.info(`Response login succeeded: ${err}`);
})
}
// 验证码倒计时
private startCountdown() {
this.countdown = 60
@@ -54,6 +101,9 @@ export struct ChangePhoneComp {
TextInput({ placeholder: '请输入验证码' })
.fontSize(16)
.backgroundColor(Color.White)
.onChange((value: string) => {
this.smsCode = value
})
}
.margin({ top: 10 })
.width('60%')
@@ -76,11 +126,15 @@ export struct ChangePhoneComp {
.margin({ top: 10 })
.enabled(this.countdown === 0)
.onClick(() => {
if (this.phoneNumber.length >= 11) {
this.startCountdown()
} else {
if (this.phoneNumber.length < 11 || !this.phoneNumber) {
promptAction.showToast({message:'请输入手机号'})
return
}
if (!EMAIL_REGEX.test(this.phoneNumber)) {
promptAction.showToast({message:'请输入正确的手机号'})
return
}
this.uploadSmsAction()
})
}
.width('95%')
@@ -100,18 +154,19 @@ export struct ChangePhoneComp {
.fontSize(18)
.position({x:'5%',y:'80%'})
.onClick(() => {
// 处理登录逻辑
if (!/^1[3-9]\d{9}$/.test(this.phoneNumber)) {
promptAction.showToast({message:'请输入有效手机号'})
if (this.phoneNumber.length < 11 || !this.phoneNumber) {
promptAction.showToast({message:'请输入手机号'})
return
}
if (!EMAIL_REGEX.test(this.phoneNumber)) {
promptAction.showToast({message:'请输入正确的手机号'})
return
}
if (!this.smsCode) {
promptAction.showToast({message:'请输入验证码'})
promptAction.showToast({message:'验证码不能为空'})
return
}
// 执行登录操作...
this.uploadChangePhoneAction();
})
}
.width('100%')
@@ -119,3 +174,6 @@ export struct ChangePhoneComp {
.backgroundColor('#FFFFFF')
}
}
// 手机正则表达式
const EMAIL_REGEX = /^1[3-9][0-9]{9}$/
@@ -1,10 +1,34 @@
import { hdHttp, HdResponse, BasicConstant, ExpertData, authStore } from '@itcast/basic'
import { BusinessError } from '@kit.BasicServicesKit';
import promptAction from '@ohos.promptAction';
import { authStore } from '@itcast/basic';
import { router } from '@kit.ArkUI';
interface updateExtraData {
uuid: string,
userName: string,
birthDate: string,
type: string,
photo: string,
email: string,
certificateImg: string,
positionUuid: string,
officeUuid: string,
officeName: string,
diseaseUuids: string
}
interface callBackData {
expert:ExpertData,
code:number,
message:string,
specialy:[],
data:ExpertData,
special:[]
}
@Preview
@Component
export struct ChooseEmailComp {
@State phoneNumber: string = ''
@State emailString: string = ''
@State countdown: number = 0
// 验证码倒计时
@@ -19,15 +43,43 @@ export struct ChooseEmailComp {
}, 1000)
}
commitEmailData(editEmail:string){
const updateDataUrl:string = BasicConstant.urlExpert + 'modify';
hdHttp.post<string>(updateDataUrl, {
uuid: authStore.getUser().uuid,
userName: authStore.getUser().userName,
email: editEmail,
type:'2'
} as updateExtraData).then(async (res: HdResponse<string>) => {
let json:callBackData = JSON.parse(res+'') as callBackData;
if(json.code == 1 && json.data && typeof json.data === 'object') {
authStore.updateUser(json.data)
console.log('更新用户邮箱成功:', authStore.getUser().email);
promptAction.showToast({message:'修改成功', duration: 1000})
router.back();
} else {
console.error('更新用户邮箱失败:'+json.message)
promptAction.showToast({ message: json.message, duration: 1000 })
}
}).catch((err: BusinessError) => {
console.info(`更新用户邮箱请求失败: ${err}`);
})
}
private validateEmailFormat(email: string): boolean {
return EMAIL_REGEX.test(email.trim())
}
build() {
Column() {
// 手机号输入框
Row() {
TextInput({ placeholder: authStore.getUser().email.length>0?authStore.getUser().email:'请输入您的邮箱' })
.fontSize(16)
.contentType(ContentType.EMAIL_ADDRESS)
.backgroundColor(Color.White)
.onChange((value: string) => {
this.phoneNumber = value
this.emailString = value
})
}
.margin({ top: 10 })
@@ -62,13 +114,11 @@ export struct ChooseEmailComp {
.fontSize(18)
.position({x:'5%',y:'80%'})
.onClick(() => {
// 处理登录逻辑
if (!/^1[3-9]\d{9}$/.test(this.phoneNumber)) {
promptAction.showToast({message:'请输入有效手机号'})
return
}
// 执行登录操作...
// if (this.validateEmailFormat(this.emailString)) {
// promptAction.showToast({message:'请输入正确的邮箱格式'})
// return
// }
this.commitEmailData(this.emailString);
})
}
.width('100%')
@@ -76,3 +126,6 @@ export struct ChooseEmailComp {
.backgroundColor('#FFFFFF')
}
}
// 邮箱正则表达式
const EMAIL_REGEX = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
@@ -1,23 +1,58 @@
import { hdHttp, HdResponse, BasicConstant, ExpertData, authStore } from '@itcast/basic'
import { BusinessError } from '@kit.BasicServicesKit';
import promptAction from '@ohos.promptAction';
import { authStore } from '@itcast/basic';
import { router } from '@kit.ArkUI';
interface updateExtraData {
uuid: string,
userName: string,
birthDate: string,
type: string,
photo: string,
email: string,
certificateImg: string,
positionUuid: string,
officeUuid: string,
officeName: string,
diseaseUuids: string,
officePhone: string
}
interface callBackData {
expert:ExpertData,
code:number,
message:string,
specialy:[],
data:ExpertData,
special:[]
}
@Preview
@Component
export struct ChooseOfficePhoneComp {
@State phoneNumber: string = ''
@State smsCode: string = ''
@State officePhoneStr: string = ''
@State countdown: number = 0
// 验证码倒计时
private startCountdown() {
this.countdown = 60
const timer = setInterval(() => {
if (this.countdown > 0) {
this.countdown--
commitOfficePhoneData(officePhoneStr:string){
const updateDataUrl:string = BasicConstant.urlExpert + 'modify';
hdHttp.post<string>(updateDataUrl, {
uuid: authStore.getUser().uuid,
userName: authStore.getUser().userName,
officePhone: this.officePhoneStr,
type:'2'
} as updateExtraData).then(async (res: HdResponse<string>) => {
let json:callBackData = JSON.parse(res+'') as callBackData;
if(json.code == 1 && json.data && typeof json.data === 'object') {
authStore.updateUser(json.data)
console.log('更新用户办公室电话成功:', authStore.getUser().email);
promptAction.showToast({message:'修改成功', duration: 1000})
router.back();
} else {
clearInterval(timer)
console.error('更新用户办公室电话失败:'+json.message)
promptAction.showToast({ message: json.message, duration: 1000 })
}
}, 1000)
}).catch((err: BusinessError) => {
console.info(`更新用户办公室电话请求失败: ${err}`);
})
}
build() {
@@ -28,7 +63,7 @@ export struct ChooseOfficePhoneComp {
.fontSize(16)
.backgroundColor(Color.White)
.onChange((value: string) => {
this.phoneNumber = value
this.officePhoneStr = value
})
}
.margin({ top: 10 })
@@ -64,15 +99,11 @@ export struct ChooseOfficePhoneComp {
.position({x:'5%',y:'80%'})
.onClick(() => {
// 处理登录逻辑
if (!/^1[3-9]\d{9}$/.test(this.phoneNumber)) {
if (!/^1[3-9]\d{9}$/.test(this.officePhoneStr)) {
promptAction.showToast({message:'请输入有效手机号'})
return
}
if (!this.smsCode) {
promptAction.showToast({message:'请输入验证码'})
return
}
this.commitOfficePhoneData(this.officePhoneStr);
// 执行登录操作...
})
@@ -1,4 +1,5 @@
import { formatDate } from '../util/DateUtils'
import { authStore } from '@itcast/basic'
@CustomDialog
export struct DatePickerDialog {
@@ -18,7 +19,8 @@ export struct DatePickerDialog {
// 初始化日期范围(示例为1930-至今)
private dateOptions: DatePickerOptions = {
start: new Date('1930-01-01'),
end: new Date(this.selectedDateString)
end: new Date(this.selectedDateString),
selected: new Date(authStore.getUser().birthDate?authStore.getUser().birthDate:'1930-01-01'),
}
build() {
@@ -7,17 +7,38 @@ import { PhotoActionSheet } from './PhotoActionSheet'
import { DatePickerDialog } from './DatePickerDialog'
import { OfficeSelectedSheet } from './OfficeSelectedSheet'
import { PositionSelectedSheet } from './PositionSelectedSheet'
import { SpecialitySelectedSheet } from './SpecialitySelectedSheet'
import { http } from '@kit.NetworkKit';
interface extraData {
uuid: string
}
interface updateExtraData {
uuid: string,
userName: string,
birthDate: string,
type: string,
photo: string,
certificateImg: string,
positionUuid: string,
officeUuid: string,
officeName: string,
diseaseUuids: string
}
interface callBackData {
expert:ExpertData,
code:number,
message:string,
specialy:[]
specialy:[],
data:ExpertData,
special:[]
}
interface UploadAvatarResponse {
url:string;
uploadAvatarUrl:string,
}
@Component
@@ -38,11 +59,14 @@ export struct EditUserDataComp {
@State diseaseName:string = '';
@State intro:string = authStore.getUser().intro;
@State updateDataUrl:string = BasicConstant.urlExpert + 'modify';
private photoSheetDialog!: CustomDialogController;
private datePickerDialog!: CustomDialogController;
private officePickerDialog!: CustomDialogController;
private positionPickerDialog!: CustomDialogController;
private certificatePhotoSheetDialog!: CustomDialogController;
private diseaseSheetDialog!:CustomDialogController;
aboutToAppear() {
this.initPhotoDialog();
@@ -50,15 +74,18 @@ export struct EditUserDataComp {
this.initOfficePickerDialog();
this.initPositionPickerDialog();
this.initCerficatePhotoDialog();
this.initDiseaseSheetDIalog();
this.uploadUserDataAction();
console.log('用户资料:'+authStore.getUser().specialy);
}
// 添加public修饰符暴露方法
public refreshData() {
this.uploadUserDataAction();
}
uploadUserDataAction() {
const hashMap: HashMap<string, string> = new HashMap();
const userDataUrl:string = BasicConstant.urlExpert+'getExpertByUuid';
hashMap.set('uuid',authStore.getUser().uuid)
hdHttp.post<string>(userDataUrl, {
uuid: authStore.getUser().uuid,
} as extraData).then(async (res: HdResponse<string>) => {
@@ -96,9 +123,28 @@ export struct EditUserDataComp {
this.photoSheetDialog = new CustomDialogController({
builder: PhotoActionSheet({
controller: this.photoSheetDialog,
onPhotoSelected: (uri: string) => {
this.photoPath = uri;
console.log('Selected image URI:', uri);
onPhotoSelected: async (url: string) => {
this.photoPath = url;
console.log('Selected image URI:', url);
try {
promptAction.showToast({ message: '正在上传图片...', duration: 2000 });
// 调用上传方法,使用明确的返回类型
const response = await hdHttp.uploadImage<UploadAvatarResponse>(
this.updateDataUrl,
url
);
if (response.code === 1) {
promptAction.showToast({ message: '图片上传成功' });
console.log('上传成功,返回数据:', response.data);
// 处理上传成功后的逻辑
// this.currentUser.avatar = response.data.avatarUrl;
} else {
promptAction.showToast({ message: response.message || '图片上传失败' });
}
} catch (error) {
console.error('图片上传出错:', error);
promptAction.showToast({ message: '图片上传出错,请重试' });
}
}
}),
alignment: DialogAlignment.Bottom,
@@ -115,7 +161,26 @@ export struct EditUserDataComp {
controller:this.officePickerDialog,
officeSelected: (name:string , uuid:string) => {
this.officeName = name;
}
hdHttp.post<string>(this.updateDataUrl, {
uuid: authStore.getUser().uuid,
userName: authStore.getUser().userName,
officeName: name,
officeUuid:uuid,
type:'2'
} as updateExtraData).then(async (res: HdResponse<string>) => {
let json:callBackData = JSON.parse(res+'') as callBackData;
if(json.code == 1 && json.data && typeof json.data === 'object') {
authStore.updateUser(json.data)
this.arrToStringSpecialy(json.special);
console.log('更新用户信息科室成功:', authStore.getUser().intro);
} else {
console.error('更新用户信息科室失败:'+json.message)
promptAction.showToast({ message: json.message, duration: 1000 })
}
}).catch((err: BusinessError) => {
console.info(`更新用户信息职称科室失败: ${err}`);
})
}
}),
alignment: DialogAlignment.Bottom,
customStyle: true,
@@ -131,6 +196,24 @@ export struct EditUserDataComp {
controller:this.officePickerDialog,
officeSelected: (name:string , uuid:string) => {
this.positionName = name;
hdHttp.post<string>(this.updateDataUrl, {
uuid: authStore.getUser().uuid,
userName: authStore.getUser().userName,
positionUuid: uuid,
type:'2'
} as updateExtraData).then(async (res: HdResponse<string>) => {
let json:callBackData = JSON.parse(res+'') as callBackData;
if(json.code == 1 && json.data && typeof json.data === 'object') {
authStore.updateUser(json.data)
this.arrToStringSpecialy(json.special);
console.log('更新用户信息职称成功:', authStore.getUser().intro);
} else {
console.error('更新用户信息职称失败:'+json.message)
promptAction.showToast({ message: json.message, duration: 1000 })
}
}).catch((err: BusinessError) => {
console.info(`更新用户信息职称请求失败: ${err}`);
})
}
}),
alignment: DialogAlignment.Bottom,
@@ -147,6 +230,24 @@ export struct EditUserDataComp {
controller:this.datePickerDialog,
dateSelected:(date:string) => {
this.birthday = date;
hdHttp.post<string>(this.updateDataUrl, {
uuid: authStore.getUser().uuid,
userName: authStore.getUser().userName,
birthDate: date,
type:'2'
} as updateExtraData).then(async (res: HdResponse<string>) => {
let json:callBackData = JSON.parse(res+'') as callBackData;
if(json.code == 1 && json.data && typeof json.data === 'object') {
authStore.updateUser(json.data)
this.arrToStringSpecialy(json.special);
console.log('更新用户信息生日成功:', authStore.getUser().intro);
} else {
console.error('更新用户信息生日失败:'+json.message)
promptAction.showToast({ message: json.message, duration: 1000 })
}
}).catch((err: BusinessError) => {
console.info(`更新用户信息生日请求失败: ${err}`);
})
}
}),
alignment: DialogAlignment.Bottom,
@@ -161,9 +262,9 @@ export struct EditUserDataComp {
this.certificatePhotoSheetDialog = new CustomDialogController({
builder: PhotoActionSheet({
controller: this.certificatePhotoSheetDialog,
onPhotoSelected: (uri: string) => {
this.certificatePhoto = uri;
console.log('Selected image URI:', uri);
onPhotoSelected: (url: string) => {
this.certificatePhoto = url;
console.log('Selected image URI:', url);
}
}),
alignment: DialogAlignment.Bottom,
@@ -174,6 +275,39 @@ export struct EditUserDataComp {
});
}
private initDiseaseSheetDIalog() {
this.diseaseSheetDialog = new CustomDialogController({
builder: SpecialitySelectedSheet({
controller:this.diseaseSheetDialog,
specialitySelected: (diseaseUuids:string)=>{
hdHttp.post<string>(this.updateDataUrl, {
uuid: authStore.getUser().uuid,
userName: authStore.getUser().userName,
diseaseUuids: diseaseUuids,
type:'2'
} as updateExtraData).then(async (res: HdResponse<string>) => {
let json:callBackData = JSON.parse(res+'') as callBackData;
if(json.code == 1 && json.data && typeof json.data === 'object') {
authStore.updateUser(json.data)
this.arrToStringSpecialy(json.special);
console.log('更新用户信息专长成功:', authStore.getUser().intro);
} else {
console.error('更新用户信息专长失败:'+json.message)
promptAction.showToast({ message: json.message, duration: 1000 })
}
}).catch((err: BusinessError) => {
console.info(`更新用户信息专长请求失败: ${err}`);
})
}
}),
alignment: DialogAlignment.Bottom,
customStyle: true,
autoCancel: false,
backgroundColor: ('rgba(0,0,0,0.5)'),
height: '100%'
})
}
build() {
Scroll() {
Column() {
@@ -199,7 +333,12 @@ export struct EditUserDataComp {
EditUserDataItem({ label: '手机号码', required: true, content: this.phone , hasArrow: true})
.onClick(()=>{
router.pushUrl({
url:'pages/MinePage/ChangePhonePage'
url:'pages/MinePage/ChangePhonePage',
params:{
onBack:()=>{
this.uploadUserDataAction();
}
}
})
})
EditUserDataItem({ label: '邮箱', content: this.email , hasArrow: true})
@@ -239,6 +378,7 @@ export struct EditUserDataComp {
EditUserDataItem({ label: '执业医师证图片或胸牌', required: true, content: this.certificatePhoto })
.onClick(()=>this.certificatePhotoSheetDialog.open())
EditUserDataItem({ label: '专长', required: true, content: this.diseaseName , hasArrow: true})
.onClick(()=>this.diseaseSheetDialog.open())
EditUserDataItem({ label: '个人简介', content: this.intro, hasArrow: true })
.onClick(()=>{
router.pushUrl({
@@ -2,6 +2,7 @@ import { hdHttp, HdResponse,BasicConstant, logger,RequestDefaultModel, Data } f
import { promptAction } from '@kit.ArkUI'
import HashMap from '@ohos.util.HashMap';
import { BusinessError } from '@kit.BasicServicesKit';
import { authStore } from '@itcast/basic'
interface DefaultData {
'officeName':string;
@@ -16,6 +17,8 @@ export struct OfficeSelectedSheet {
@Prop selectedOffice:object = new Object;
@State selectedModel:DefaultData = { officeName: '', officeUuid: '' };
@State selectedIndex:number = 0;
// 添加回调函数属性
private officeSelected: (name:string , uuid:string) => void = () => {};
@@ -35,19 +38,23 @@ export struct OfficeSelectedSheet {
uploadOffice() {
hdHttp.httpReq<string>(this.officeRequestUrl,this.hashMap).then(async (res: HdResponse<string>) => {
logger.info('Response officelist success'+res);
console.info(`Response officelist succeeded: ${res}`);
let json:RequestDefaultModel = JSON.parse(res+'') as RequestDefaultModel;
if(json.code=='1') {
this.officeArr = json.data as DefaultData[];
this.officeNameArr = json.data.map(item => item.officeName);
console.log('科室名称数组:', this.officeNameArr);
for (let index = 0; index < this.officeNameArr.length; index++) {
const element = this.officeNameArr[index];
if (element == authStore.getUser().officeName) {
this.selectedIndex = index;
}
}
} else {
console.error('科室数据失败:'+json.message)
promptAction.showToast({ message: json.message, duration: 1000 })
}
}).catch((err: BusinessError) => {
console.info(`Response login fail: ${err}`);
console.info(`Response fail: ${err}`);
})
}
@@ -83,7 +90,8 @@ export struct OfficeSelectedSheet {
.height(40)
TextPicker({
range:this.officeNameArr
range:this.officeNameArr,
selected:this.selectedIndex
})
.selectedTextStyle({
color: '#007AFF',
@@ -1,7 +1,8 @@
import { hdHttp, HdResponse,BasicConstant, logger,RequestDefaultModel, Data } from '@itcast/basic'
import { hdHttp, HdResponse,BasicConstant,RequestDefaultModel } from '@itcast/basic'
import { promptAction } from '@kit.ArkUI'
import HashMap from '@ohos.util.HashMap';
import { BusinessError } from '@kit.BasicServicesKit';
import { authStore } from '@itcast/basic'
interface DefaultData {
'name':string;
@@ -16,6 +17,8 @@ export struct PositionSelectedSheet {
@Prop selectedOffice:object = new Object;
@State selectedModel:DefaultData = { name: '', uuid: '' };
@State selectedIndex:number = 0;
// 添加回调函数属性
private officeSelected: (name:string , uuid:string) => void = () => {};
@@ -35,19 +38,23 @@ export struct PositionSelectedSheet {
uploadOffice() {
hdHttp.httpReq<string>(this.officeRequestUrl,this.hashMap).then(async (res: HdResponse<string>) => {
logger.info('Response officelist success'+res);
console.info(`Response officelist succeeded: ${res}`);
let json:RequestDefaultModel = JSON.parse(res+'') as RequestDefaultModel;
if(json.code=='1') {
this.officeArr = json.data as DefaultData[];
this.officeNameArr = json.data.map(item => item.name);
for (let index = 0; index < this.officeNameArr.length; index++) {
const element = this.officeNameArr[index];
if (element == authStore.getUser().positionName) {
this.selectedIndex = index;
}
}
console.log('职称名称数组:', this.officeNameArr);
} else {
console.error('职称数据失败:'+json.message)
promptAction.showToast({ message: json.message, duration: 1000 })
}
}).catch((err: BusinessError) => {
console.info(`Response login fail: ${err}`);
console.info(`Response fail: ${err}`);
})
}
@@ -83,7 +90,8 @@ export struct PositionSelectedSheet {
.height(40)
TextPicker({
range:this.officeNameArr
range:this.officeNameArr,
selected:this.selectedIndex
})
.selectedTextStyle({
color: '#007AFF',
@@ -0,0 +1,132 @@
import { hdHttp, HdResponse,BasicConstant,RequestDefaultModel } from '@itcast/basic'
import HashMap from '@ohos.util.HashMap';
import { promptAction } from '@kit.ArkUI'
import { BusinessError } from '@kit.BasicServicesKit';
interface DefaultData {
'name':string;
'uuid':string;
}
@CustomDialog
export struct SpecialitySelectedSheet {
controller: CustomDialogController;
@State specialityArr:Array<DefaultData> = [];
@State specialityNameArr:Array<string> = [];
@State selectedTags: Array<string> = [];
// 添加回调函数属性
private specialitySelected: (seletedTags:string) => void = () => {};
// 修改构造函数
constructor(controller: CustomDialogController, specialitySelected: (seletedTags:string) => void) {
super();
this.controller = controller;
this.specialitySelected = specialitySelected;
}
aboutToAppear(): void {
this.uploadSpeciality();
}
uploadSpeciality() {
const officeRequestUrl:string = BasicConstant.urlExpert+'disease'
const hashMap: HashMap<string, string> = new HashMap();
hdHttp.httpReq<string>(officeRequestUrl,hashMap).then(async (res: HdResponse<string>) => {
let json:RequestDefaultModel = JSON.parse(res+'') as RequestDefaultModel;
if(json.code=='1') {
this.specialityArr = json.data as DefaultData[];
this.specialityNameArr = json.data.map(item => item.name);
console.log('请求专长接口成功,信息:', this.specialityArr);
} else {
console.error('请求专长接口失败:'+json.message)
promptAction.showToast({ message: json.message, duration: 1000 })
}
}).catch((err: BusinessError) => {
console.info(`Response fail: ${err}`);
})
}
build() {
Column() {
// 操作按钮区域
Row({space:70}) {
Button('取消')
.layoutWeight(1)
.backgroundColor(Color.Transparent)
.fontColor($r('app.color.main_color'))
.backgroundColor(Color.White)
.width(80)
.onClick(() => {
this.controller.close()
})
Text('请选择专长')
.fontSize(15)
.fontColor('#666666')
Button('确定')
.layoutWeight(1)
.backgroundColor(Color.Transparent)
.fontColor($r('app.color.main_color'))
.backgroundColor(Color.White)
.width(80)
.onClick(() => {
this.controller.close()
// 拼接为逗号分隔字符串
const diseaseName = this.selectedTags.join(',');
console.log('当前选中标签的uuid字符串:', diseaseName);
this.specialitySelected(diseaseName);
})
}
.height(40)
Grid() {
ForEach(this.specialityArr, (data: DefaultData) => {
GridItem() {
// 单个标签组件
Text(data.name)
.fontSize(12)
.width('100%')
.height(30)
.textAlign(TextAlign.Center)
.backgroundColor(this.isSelected(data.uuid) ? '#b58078' : '#FFFFFF')
.onClick(() => {
this.handleTagClick(data.uuid)
})
}
.height(30)
.width('25%') // 四等分宽度
.borderWidth(1)
.borderColor(Color.Gray)
})
}
}
.width('100%')
.height(240)
.backgroundColor(Color.White)
}
// 判断是否选中
private isSelected(uuid: string): boolean {
return this.selectedTags.includes(uuid)
}
private handleTagClick(uuid: string) {
const index = this.selectedTags.indexOf(uuid);
if (index === -1) {
// 添加选中(限制最多10个)
if (this.selectedTags.length >= 10) {
promptAction.showToast({ message: '最多可选择十项!', duration: 1000 });
return;
}
this.selectedTags = [...this.selectedTags, uuid];
} else {
// 取消选中
const newSelected = [...this.selectedTags];
newSelected.splice(index, 1);
this.selectedTags = newSelected;
}
console.log('当前选中标签:', this.selectedTags)
}
}