//报工数量
import ProcessRequest from '../common/util/request/ProcessRequest';
import { BindTaskSeqVO } from '../viewmodel/BindTaskSeqVO';
import TaskSeqVO from '../viewmodel/process/TaskSeqInfo';
import RequestParamModel from '../viewmodel/RequestParamModel';
import preferencesUtil from '../common/util/PerferencesUtil';
import CommonConstants from '../common/constants/CommonConstants';

@CustomDialog
export struct ReportWorkNumDialog{
  controller: CustomDialogController
  onConfirm: (num:number)=> void = () => {}
  scroller: Scroller = new Scroller()

  //是否全选
  @State isAllSelected:boolean = false
  //选择的数量
  @State selectNum:number= 0
  //当前工单
  @State currentWorkOrderCode:string = ''
  //当前工序号
  @State currentOperationId:string = ''
  //当前工位
  @Consume('currentStationId') currentStationId:string
  //总数量
  @State totalNum:number= 0
  //查询报工
  @State queryTaskSeq: TaskSeqVO[] = []
  @Consume ('bindTaskSeq') bindTaskSeq: BindTaskSeqVO[]
  @Prop userName:string= ''
  @State selectedIndexes:number[] =[]

  onQueryTask=async ()=>{
    let result: TaskSeqVO[] = await ProcessRequest.post('/api/v1/plan/task/list', {
      stationId:this.currentStationId,
      workOrderCode:this.currentWorkOrderCode,
      operationId:this.currentOperationId,
      stateList:[-1,0,1]
    } as RequestParamModel) as TaskSeqVO[];
    let seqNos: string[] = []
    seqNos = await preferencesUtil.get(CommonConstants.PREFERENCE_INSTANCE_NAME, this.currentWorkOrderCode, seqNos)
    if (!seqNos || seqNos.length <= 0) {
      this.queryTaskSeq = []
      this.totalNum = 0
      return
    }
    for (const element of result) {
      if (seqNos.includes(element.seqNo!)) {
        this.queryTaskSeq.push(element)
      }
    }
    this.totalNum = this.queryTaskSeq.length
  }

  private isSelectedByOthers(item: TaskSeqVO): boolean {
    // 检查所有其他用户的选择记录
    return this.bindTaskSeq.some(userSelection =>
    userSelection.userName !== this.userName &&
    userSelection.reportSeq?.some(seq =>
    seq.seqNo === item.seqNo &&
      seq.operationId === item.operationId
    )
    );
  }

  // 获取选择当前项的用户名
  private getSelectingUserName(item: TaskSeqVO): string | undefined {
    const userSelection = this.bindTaskSeq.find(userSelection =>
    userSelection.reportSeq?.some(seq =>
    seq.seqNo === item.seqNo &&
      seq.operationId === item.operationId)
    );
    return userSelection?.userName;
  }

  //选择单个
  private onSelectSeqNo(index: number) {
    const item = this.queryTaskSeq[index];

    if (this.isSelectedByOthers(item)) {
      return; // 已被其他用户选择，不允许操作
    }

    if (this.selectedIndexes.includes(index)) {
      this.selectedIndexes = this.selectedIndexes.filter(i => i !== index);
    } else {
      this.selectedIndexes = [index, ...this.selectedIndexes];
    }

    this.updateSelectState();
  }

  //全选
  private handleSelectAll() {
    this.isAllSelected = !this.isAllSelected;

    if (this.isAllSelected) {
      // 只选择未被其他用户选中的项
      this.selectedIndexes = [];
      this.queryTaskSeq.forEach((item: TaskSeqVO, index: number) => {
        if (!this.isSelectedByOthers(item)) {
          this.selectedIndexes.push(index);
        }
      });
    } else {
      this.selectedIndexes = [];
    }

    this.updateSelectState();
  }

  //更新选择状态
  private updateSelectState() {
    this.selectNum = this.selectedIndexes.length;
    const availableItems = this.queryTaskSeq.filter(item => !this.isSelectedByOthers(item));
    this.isAllSelected = availableItems.length > 0 &&
      this.selectedIndexes.length === availableItems.length;
  }

  aboutToAppear(): void {
    this.onQueryTask().then(() => {
      // 查询完成后检查是否有当前用户已选的项
      this.queryTaskSeq.forEach((item, index) => {
        const selectingUser = this.getSelectingUserName(item);
        if (selectingUser === this.userName) {
          this.selectedIndexes.push(index);
        }
      });
      this.updateSelectState();
    });
  }

  build() {
    Column(){
      Column() {
        Text("报工数量")
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_30'))
      }
      .height('8%')
      .width('100%')
      .justifyContent(FlexAlign.Center)
      Row() {
        Row(){
          Row(){}.width('5%')
          Checkbox()
            .select(this.isAllSelected)
            .selectedColor($r('app.color.0A84FF'))
            .unselectedColor($r('app.color.60FFFFFF'))
            .width($r('app.float.virtualSize_24'))
            .mark({
              strokeColor:$r('app.color.000000'),
              size: $r('app.float.virtualSize_20'),
              strokeWidth: 1
            })
            .height($r('app.float.virtualSize_24'))
            .onChange(async (value: boolean) => {
            })
            .onClick(()=>{
              this.handleSelectAll()
            })
          Text("全选")
            .fontColor($r('app.color.FFFFFF'))
            .fontSize($r('app.float.fontSize_16'))
        }
        .width('20%')
        .justifyContent(FlexAlign.Start)
        .backgroundColor(this.isAllSelected?$r('app.color.200A84FF'):$r('app.color.20FFFFFF'))
        .borderRadius($r('app.float.virtualSize_16'))
        .onClick(()=>{
          this.handleSelectAll()
        })
        Row(){
          Text(`${this.selectNum}`)
            .fontColor($r('app.color.30D158'))
            .fontSize($r('app.float.fontSize_16'))
            .fontWeight(FontWeight.Lighter)
          Text(`/${this.totalNum}`)
            .fontColor($r('app.color.FFFFFF'))
            .fontSize($r('app.float.fontSize_16'))
            .fontWeight(FontWeight.Lighter)
        }
        .margin({left:'49%'})
        .width('30%')
        .justifyContent(FlexAlign.End)
      }
      .borderRadius($r('app.float.virtualSize_16'))
      .height('7%')
      .width('96%')
      .margin({left:'2%',right:'2%',bottom:'1.5%'})
      Row() {
        List({space:8,scroller:this.scroller}){
          ForEach(this.queryTaskSeq, (item:TaskSeqVO,index) => {
            ListItem() {
              Row(){
                Checkbox()
                  .select(this.selectedIndexes.includes(index)||this.isSelectedByOthers(item))
                  .selectedColor($r('app.color.30D158'))
                  .unselectedColor($r('app.color.60FFFFFF'))
                  .width($r('app.float.virtualSize_24'))
                  .mark({
                    strokeColor:$r('app.color.000000'),
                    size: $r('app.float.virtualSize_20'),
                    strokeWidth: 1
                  })
                  .height($r('app.float.virtualSize_24'))
                  .onClick(()=>{
                    this.onSelectSeqNo(index)
                    this.selectNum = this.selectedIndexes.length;
                  })
                Text('S/N')
                  .fontColor($r('app.color.FFFFFF'))
                  .fontSize($r('app.float.fontSize_16'))
                  .fontWeight(FontWeight.Lighter)
                Text(item.seqNo)
                  .fontColor($r('app.color.FFFFFF'))
                  .fontSize($r('app.float.fontSize_16'))
                  .fontWeight(FontWeight.Bold)
                  .margin({left:'2%'})
                Text(this.getSelectingUserName(item))
                  .fontColor($r('app.color.FFFFFF'))
                  .fontSize($r('app.float.fontSize_12'))
                  .fontWeight(FontWeight.Lighter)
                  .width('50%')
                  .textAlign(TextAlign.End)
              }
              .borderRadius($r('app.float.virtualSize_16'))
              .backgroundColor(
                this.selectedIndexes.includes(index) ||this.isSelectedByOthers(item)?
                $r('app.color.2030D158') :
                $r('app.color.20FFFFFF')
              )
              .border({
                width:  1 ,
                color: this.selectedIndexes.includes(index)||this.isSelectedByOthers(item) ?
                $r('app.color.30D158') :
                $r('app.color.20FFFFFF')
              })
              .width('100%')
              .opacity(this.isSelectedByOthers(item) ? 0.3 : 1)
              .onClick(()=>{
                this.onSelectSeqNo(index)
                this.selectNum = this.selectedIndexes.length;
              })
            }
            .width('96%')
            .margin({left:'2%',right:'2%'})
          })
        }
        .height('100%')
        .width('100%')
      }
      .height('73%')
      .width('100%')
      .margin({bottom:'1.5%'})
      Column() {
        Divider()
          .vertical(false)
          .strokeWidth(1)
          .color($r('app.color.15FFFFFF'))
        Row() {
          Row() {
            Text('取消')
              .fontColor($r('app.color.60FFFFFF'))
              .fontSize($r('app.float.fontSize_30'))
          }
          .justifyContent(FlexAlign.Center)
          .width('50%')
          .onClick(() => this.controller.close())
          Divider()
            .vertical(true)
            .strokeWidth(1)
            .color($r('app.color.15FFFFFF'))
          Row() {
            Text('确定')
              .fontColor($r('app.color.007AFF'))
              .fontSize($r('app.float.fontSize_30'))
          }
          .justifyContent(FlexAlign.Center)
          .width('50%')
          .onClick(() => {
            const currentUserSelection: BindTaskSeqVO = {
              userName: this.userName,
              reportSeq: this.queryTaskSeq.filter((_, index) => this.selectedIndexes.includes(index))
            };
            const existingUserIndex = this.bindTaskSeq.findIndex(
              item => item.userName === this.userName
            );
            if (existingUserIndex >= 0) {
              this.bindTaskSeq[existingUserIndex].reportSeq = currentUserSelection.reportSeq;
            } else {
              this.bindTaskSeq.push(currentUserSelection);
            }
            this.onConfirm(this.selectedIndexes.length);
            console.info("sssssss"+this.bindTaskSeq.length)
            this.controller.close()
          })
        }
      }
      .width('100%')
      .height('8%')
    }
    .height('71%')
    .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'))
  }
}




