//参与人员
import { pinyin } from "pinyin-pro";
import ProcessRequest from '../common/util/request/ProcessRequest';
import { BindTaskSeq } from '../viewmodel/process/BindTaskSeq';
import ReportInfo from '../viewmodel/process/ReporterInfo';
import RequestParamModel from '../viewmodel/RequestParamModel';
import { UserInfo } from '../viewmodel/UserInfo';
import promptAction from '@ohos.promptAction';

@CustomDialog
export struct JoinPersonNameDialog{
  controller: CustomDialogController

  scroller: Scroller = new Scroller()
  @Link currentReporterIndex: number
  @State nameList:UserInfo[]=[]
  @State selectNameIndex:number=-1
  @State selectName:string = ''
  @State queryName:string = ''
  @Link reporterList: ReportInfo[]
  @Consume ('bindTaskSeq') bindTaskSeq: BindTaskSeq[]

  private value: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G',
    'H', 'I', 'J', 'K', 'L', 'M', 'N',
    'O', 'P', 'Q', 'R', 'S', 'T', 'U',
    'V', 'W', 'X', 'Y', 'Z','#']

  onSelectIndexItem(index:string) {
    for (let i = 0; i < this.nameList.length; i++) {
      console.log("名字：" + this.nameList[i].userName + " index1:" + this.nameList[i].nameInitial + " index2:" + index)
      if (this.nameList[i].nameInitial == index) {
        this.scroller.scrollToIndex(i) //滚动到索引位置
        break;
      }
    }
  }
  private onSelectName(index: number) {
    this.selectNameIndex = index
    this.selectName = this.nameList[index].userName ?? ""
    const nameExists = this.reporterList.some(item =>
    item.userName && this.selectName &&
      item.userName.toString().toLowerCase() === this.selectName.toString().toLowerCase().trim()
    );
    if (nameExists) {
      promptAction.showToast({
        message: '该用户已添加，请添加其他用户！',
        duration: 2000
      });
      return;
    }
    if (this.reporterList[this.currentReporterIndex]) {
      this.reporterList[this.currentReporterIndex].userName = this.selectName;
      this.reporterList[this.currentReporterIndex].userId = this.nameList[index].id! as string;
      this.reporterList = [...this.reporterList];
    }
    if (this.bindTaskSeq[this.currentReporterIndex]) {
      this.bindTaskSeq[this.currentReporterIndex].userName = this.selectName;
      this.bindTaskSeq[this.currentReporterIndex].userId = this.nameList[index].id! as string;
    }

  }

  loadPersonNameList = async ()=>{
    this.nameList = await ProcessRequest.post('/api/v1/sys/user/list', {
      userName:this.queryName
    } as RequestParamModel)
    for(let i = 0; i < this.nameList.length; i++) {
      let pinyinStr = pinyin(this.nameList[i].userName, { toneType: "none" });
      let index = pinyinStr.substring(0, 1).toUpperCase();
      if (!(new RegExp("^[A-Z]$").test(index))) {
        index = "#";
      }
      this.nameList[i].nameInitial = index
    }
    this.nameList.sort((a: UserInfo, b: UserInfo): number => {
      const aInitial = a.nameInitial || "#";
      const bInitial = b.nameInitial || "#";
      const aName = a.userName || a.userName || "";
      const bName = b.userName || b.userName || "";
      if (aInitial === bInitial) {
        return aName.localeCompare(bName);
      }
      if (aInitial === "#") {
        return 1;
      }
      if (bInitial === "#") {
        return -1;
      }
      return aInitial.localeCompare(bInitial);
    });
  }

  aboutToAppear(): void {
    this.loadPersonNameList()
  }

  build() {
    Column(){
      Column() {
        Text("参与人员")
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_30'))
      }
      .height('8%')
      .width('100%')
      .justifyContent(FlexAlign.Center)
      Row() {
        TextInput({  placeholder: '录入人员姓名' })
          .type(InputType.Normal)
          .placeholderFont({ size: $r('app.float.fontSize_16') })
          .placeholderColor($r('app.color.30FFFFFF'))
          .fontSize($r('app.float.fontSize_16'))
          .fontColor($r('app.color.FFFFFF'))
          .enableKeyboardOnFocus(false)
          .width('84%')
          .onChange((value: string) => {
            this.queryName = value
            this.loadPersonNameList()
          })
        Row() {
          Image($r('app.media.process_search'))
            .width($r('app.float.virtualSize_48'))
            .height($r('app.float.virtualSize_48'))
            .fillColor($r('app.color.0A84FF'))
            .onClick(() => {
              this.loadPersonNameList()
            })
        }
        .width('16%')
        .height('100%')
        .justifyContent(FlexAlign.Center)
        .borderRadius($r('app.float.virtualSize_16'))
        .backgroundColor($r('app.color.20FFFFFF'))
      }
      .borderRadius($r('app.float.virtualSize_16'))
      .backgroundColor($r('app.color.000000'))
      .height('7%')
      .width('60%')
      .margin({bottom:'2%',left:'20%',right:'20%'})
      Row() {
        List({ space: 0, initialIndex: 0,scroller:this.scroller}){
          ForEach(this.nameList, (item:UserInfo,index) => {
            ListItem() {
              Column(){
                if (index===0||this.nameList[index-1].nameInitial != item.nameInitial){
                  Row(){
                    Text(item.nameInitial)
                      .fontColor($r('app.color.FFFFFF'))
                      .fontSize($r('app.float.fontSize_60'))
                  }
                  .width($r('app.float.virtualSize_80'))
                  .height($r('app.float.virtualSize_80'))
                  .backgroundColor($r('app.color.0A84FF'))
                  .justifyContent(FlexAlign.Center)
                  .alignItems(VerticalAlign.Center)
                  .margin({left:'2%'})
                }
                Row(){
                  Text(item.userName)
                    .fontSize($r('app.float.fontSize_24'))
                    .fontColor($r('app.color.FFFFFF'))
                    .margin({left:'2%'})
                  Text(item.deptNames)
                    .fontSize($r('app.float.fontSize_16'))
                    .fontColor($r('app.color.FFFFFF'))
                    .fontWeight(FontWeight.Lighter)
                    .margin({left:'2%'})
                }
                .justifyContent(FlexAlign.Start)
                .alignItems(VerticalAlign.Center)
                .padding(20)
                .width('100%')
                .backgroundColor(this.selectNameIndex===index?$r('app.color.200A84FF'):'')
                .onClick(()=>{
                  this.onSelectName(index)
                  this.controller.close();
                })
              }
              .alignItems(HorizontalAlign.Start)
            }
          })
        }
        .layoutWeight(1)
        .scrollBar(BarState.Off)
        .height('100%')
        .width('90%')

        AlphabetIndexer({ arrayValue: this.value, selected: 0})
          .color($r('app.color.FFFFFF'))
          .selectedColor($r('app.color.FFFFFF'))
          .selectedBackgroundColor($r('app.color.20FFFFFF'))
          .usingPopup(false)
          .selectedFont({ size: 16, weight: FontWeight.Bolder })
          .itemSize(25.2)
          .alignStyle(IndexerAlign.Right)
          .onSelect((index: number) => {
            this.onSelectIndexItem(this.value[index]);
          })

      }
      .height('83%')
      .width('100%')
    }
    .height('100%')
    .width('30%')
    .backgroundColor($r('app.color.2A2A2A'))
    .justifyContent(FlexAlign.End)
    .alignItems(HorizontalAlign.Start)
    .borderColor($r('app.color.000000'))
    .borderWidth(1)
    .borderRadius($r('app.float.virtualSize_16'))
  }
}


