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)
    }
}
