//工序（计时）报工
import ProcessRequest from '../common/util/request/ProcessRequest'
import ProcessInfo from '../viewmodel/process/ProcessInfo'
import ReporterInfo from '../viewmodel/process/ReporterInfo'
import ReportInfo from '../viewmodel/process/ReporterInfo'
import TaskSeqVO from '../viewmodel/process/TaskSeqInfo'
import RequestParamModel from '../viewmodel/RequestParamModel'
import WorkOrderInfo from '../viewmodel/WorkOrderInfo'
import promptAction from '@ohos.promptAction'
import ProcessReportTimeBased from '../viewmodel/process/ProcessReportTimeBased'
import { BindTaskSeq } from '../viewmodel/process/BindTaskSeq'
import preferencesUtil from '../common/util/PerferencesUtil'
import CommonConstants from '../common/constants/CommonConstants'

@CustomDialog
export struct ReportTimeBasedDialog {

  controller: CustomDialogController
  private scrollerList: Scroller = new Scroller()

  //选中的工序id
  @Link selectOperationId: string
  //从首页传来的工单
  @Link selectWorkOder: WorkOrderInfo
  // 当前生产过程
  @Link process: ProcessInfo
  //查询报工
  @Link reporterList: ReportInfo[]
  //工序名字
  selectOperationName: string = ''
  //当前工序已报工数量
  @State reportedNum: number = 0
  //计划报工数量
  @State planReportNum: number = 0
  // 记录当前点击的报工人索引
  @State currentReporterIndex: number = 0;
  //当前工位
  @Consume('currentStationId') currentStationId: string
  // 当前登录用户名称
  @Consume('currentUserName') userName: string
  // 当前登录用户名称
  @Consume('currentUserId') currentUserId: number
  @Consume ('bindTaskSeq') bindTaskSeq: BindTaskSeq[]
  // 开工时间
  startWorkTime: string = ''

  //选择报工数量
  onSelectReportNum: (index:number) => void = () => {}
  //选择不良品数量
  onSelectDefectNum: (index:number) => void = () => {}
  //选择用户用时占比
  onSelectWorkHourRate: (index:number) => void = () => {}
  //选择报工人
  onSelectReporter: (index:number) => void = () => {}
  // 报工后清除相关数据
  clearSelectData: () => void = () => {}
  //加载第一个报工人（无法删除）
  loadFirstReporter=async ()=>{
    if (this.reporterList.length > 0) {
      return
    }
    const firstReporter: ReporterInfo = {}
    firstReporter.userName = this.userName
    firstReporter.userId = this.currentUserId.toString()
    firstReporter.workingHoursRate = 1
    this.reporterList.push(firstReporter)
  }

  async aboutToAppear() {
    this.loadFirstReporter()
    // 查询所有流转卡号
    let res = await ProcessRequest.post('/api/v1/plan/task/list', {
      stationId: this.currentStationId,
      workOrderCode: this.selectWorkOder.workOrderCode!,
      operationId: this.selectOperationId
    } as RequestParamModel) as TaskSeqVO[];
    if (!res || res.length <= 0) {
      return
    }
    this.planReportNum = res.length
    // 计算已报工数量
    let num: number = 0
    for (const element of res) {
      if (element.state! === '2') {
        num++
      }
    }
    this.reportedNum = num
  }

  build() {
    Column() {
      Column() {
        Text('工序报工')
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_30'))
      }
      .height('10%')
      .width('100%')
      .justifyContent(FlexAlign.Center)

      Column(){
        Row(){
          Column({space:3}){
            Text(this.selectWorkOder.materialName)
              .fontSize($r('app.float.fontSize_24'))
              .fontColor($r('app.color.FFFFFF'))
            Text(this.selectWorkOder.materialCode)
              .fontSize($r('app.float.fontSize_12'))
              .fontColor($r('app.color.FFFFFF'))
              .fontWeight(FontWeight.Lighter)
            Row(){
              Text('工单 ')
                .fontSize($r('app.float.fontSize_16'))
                .fontColor($r('app.color.FFFFFF'))
                .fontWeight(FontWeight.Lighter)
              Text(this.selectWorkOder.workOrderCode)
                .fontSize($r('app.float.fontSize_16'))
                .fontColor($r('app.color.FFFFFF'))
                .fontWeight(FontWeight.Bold)
            }
          }
          .height('100%')
          .width('30%')
          .justifyContent(FlexAlign.End)
          .alignItems(HorizontalAlign.Start)
          Row(){
            Text('工序 ')
              .fontSize($r('app.float.fontSize_16'))
              .fontColor($r('app.color.FFFFFF'))
              .fontWeight(FontWeight.Lighter)
            Text(this.selectOperationName)
              .fontSize($r('app.float.fontSize_16'))
              .fontColor($r('app.color.FFFFFF'))
              .fontWeight(FontWeight.Bold)
          }
          .height('100%')
          .width('40%')
          .justifyContent(FlexAlign.Center)
          .alignItems(VerticalAlign.Bottom)
          Column(){
            Row(){
              Text(`${this.reportedNum}/`)
                .fontSize($r('app.float.fontSize_38'))
                .fontColor($r('app.color.FFFFFF'))
              Text(`${this.planReportNum}`)
                .fontSize($r('app.float.fontSize_38'))
                .fontColor($r('app.color.60FFFFFF'))
            }
            Text('当前工序已报工/计划')
              .fontSize($r('app.float.fontSize_12'))
              .fontColor($r('app.color.FFFFFF'))
              .fontWeight(FontWeight.Lighter)
          }
          .height('100%')
          .width('30%')
          .justifyContent(FlexAlign.End)
          .alignItems(HorizontalAlign.End)
        }
        .height('14.4%')
        .width('100%')
        .alignItems(VerticalAlign.Bottom)

        Divider()
          .vertical(false)
          .width('100%')
          .strokeWidth(1)
          .color($r('app.color.15FFFFFF'))
          .height('3.1%')
        // 报工流水号、不良流水号选择
        Row({space: 5}) {
          Column() {
            Text(`报工数量`)
              .fontColor($r('app.color.FFFFFF'))
              .fontSize($r('app.float.fontSize_16'))
              .fontWeight(FontWeight.Regular)
              .height('27%')
              .margin({left:'2%'})
            Row(){
              Text(this.reporterList && this.reporterList[0].reportNum ? this.reporterList[0].reportNum! : '0')
                .fontColor($r('app.color.FFFFFF'))
                .fontSize($r('app.float.fontSize_24'))
                .margin({left:'8%'})
                .width('82%')
                .textAlign(TextAlign.Start)
              Text('>')
                .fontColor($r('app.color.FFFFFF'))
                .fontSize($r('app.float.fontSize_24'))
                .textAlign(TextAlign.Start)
                .width('10%')
            }
            .justifyContent(FlexAlign.Start)
            .borderRadius($r('app.float.virtualSize_16'))
            .height('73%')
            .backgroundColor($r('app.color.20FFFFFF'))
            .onClick(()=>{
              this.onSelectReportNum(0)
            })
          }
          .width('30%')
          .height('100%')
          .alignItems(HorizontalAlign.Start)
          Column(){
            Text(`不良品数量`)
              .fontColor($r('app.color.FFFFFF'))
              .fontSize($r('app.float.fontSize_16'))
              .fontWeight(FontWeight.Regular)
              .height('27%')
              .margin({left:'2%'})
            Row(){
              Text(this.reporterList && this.reporterList[0].defectNum ? this.reporterList[0].defectNum! : '0')
                .fontColor($r('app.color.FFFFFF'))
                .fontSize($r('app.float.fontSize_24'))
                .margin({left:'8%'})
                .width('82%')
                .textAlign(TextAlign.Start)
              Text('>')
                .fontColor($r('app.color.FFFFFF'))
                .fontSize($r('app.float.fontSize_24'))
                .textAlign(TextAlign.Start)
                .width('10%')
            }
            .justifyContent(FlexAlign.Start)
            .borderRadius($r('app.float.virtualSize_16'))
            .backgroundColor($r('app.color.20FFFFFF'))
            .height('73%')
            .onClick(()=>{
              this.onSelectDefectNum(0)
            })
          }
          .width('30%')
          .alignItems(HorizontalAlign.Start)
          .height('100%')
          Blank()
          Text('开工时间：' +this.startWorkTime)
            .fontColor($r('app.color.FFFFFF'))
            .fontSize($r('app.float.fontSize_12'))
            .fontWeight(FontWeight.Lighter)
        }
        .width('100%')
        .height('17.2%')
        Row().height('7.9%')
        // 添加报工人
        Row(){
          Image($r('app.media.general_create'))
            .width($r('app.float.virtualSize_24'))
            .height($r('app.float.virtualSize_24'))
            .fillColor($r('app.color.0A84FF'))
          Text('添加报工人')
            .fontColor($r('app.color.0A84FF'))
            .fontSize($r('app.float.fontSize_24'))
            .margin({left:'4%'})
        }
        .height('8.8%')
        .width('14%')
        .justifyContent(FlexAlign.Center)
        .backgroundColor($r('app.color.20FFFFFF'))
        .borderRadius($r('app.float.virtualSize_16'))
        .onClick(() => {
          const newReporter: ReportInfo = {}
          // 默认占比为剩余占比
          if (this.reporterList && this.reporterList.length > 0) {
            let rateTotal: number = 1
            for (const element of this.reporterList) {
              if (element.workingHoursRate && element.workingHoursRate > 0) {
                rateTotal -= element.workingHoursRate
              }
            }
            newReporter.workingHoursRate = rateTotal
          }
          this.reporterList.push(newReporter)
        })

        Column(){
          List({space: 8, scroller: this.scrollerList}) {
            ForEach(this.reporterList, (item: ReporterInfo, index: number) => {
              ListItem() {
                Row(){
                  Column(){
                    Text(`报工人${index+1}`)
                      .fontColor($r('app.color.FFFFFF'))
                      .fontSize($r('app.float.fontSize_16'))
                      .fontWeight(FontWeight.Regular)
                      .height('30%')
                      .margin({left:'2%'})
                    Row(){
                      Text(item.userName)
                        .fontColor($r('app.color.FFFFFF'))
                        .fontSize($r('app.float.fontSize_24'))
                        .margin({left:'8%'})
                        .width('82%')
                        .textAlign(TextAlign.Start)
                      Text('>')
                        .fontColor($r('app.color.FFFFFF'))
                        .fontSize($r('app.float.fontSize_24'))
                        .textAlign(TextAlign.Start)
                        .width('10%')
                    }
                    .justifyContent(FlexAlign.Start)
                    .borderRadius($r('app.float.virtualSize_16'))
                    .height('70%')
                    .enabled(index!=0)
                    .backgroundColor($r('app.color.20FFFFFF'))
                    .onClick(()=>{
                      this.onSelectReporter(index)
                      this.currentReporterIndex = index;
                    })
                  }
                  .width('29%')
                  .height('100%')
                  .alignItems(HorizontalAlign.Start)
                  Column(){
                    Text(`用时占比`)
                      .fontColor($r('app.color.FFFFFF'))
                      .fontSize($r('app.float.fontSize_16'))
                      .fontWeight(FontWeight.Regular)
                      .height('30%')
                      .margin({left:'2%'})
                    Row(){
                      Text(item.workingHoursRate ? item.workingHoursRate * 100 + '%' : '0%')
                        .fontColor($r('app.color.FFFFFF'))
                        .fontSize($r('app.float.fontSize_24'))
                        .margin({left:'8%'})
                        .width('82%')
                        .textAlign(TextAlign.Start)
                      Text('>')
                        .fontColor($r('app.color.FFFFFF'))
                        .fontSize($r('app.float.fontSize_24'))
                        .textAlign(TextAlign.Start)
                        .width('10%')
                    }
                    .justifyContent(FlexAlign.Start)
                    .borderRadius($r('app.float.virtualSize_16'))
                    .height('70%')
                    .backgroundColor($r('app.color.20FFFFFF'))
                    .onClick(()=>{
                      this.onSelectWorkHourRate(index)
                    })
                  }
                  .width('29%')
                  .height('100%')
                  .alignItems(HorizontalAlign.Start)
                  .margin({left:'2%',right:'2%'})
                  Blank()
                  if(index > 0) {
                    Column(){
                      Image($r('app.media.process_delete_seq'))
                        .width($r('app.float.virtualSize_48'))
                        .height($r('app.float.virtualSize_48'))
                        .fillColor($r('app.color.FF453A'))
                        .margin({top:'35%'})
                        .onClick(()=>{
                          this.reporterList.splice(index,1)
                        })
                    }
                    .width('9%')
                    .alignItems(HorizontalAlign.Center)
                    .height('100%')
                  }
                }
                .height('100%')
                .width('100%')
              }
              .height('40.7%')
              .width('100%')
            })
          }
          .width('100%')
          .height('87%')
        }
        .height('48.6%')
        .width('100%')
        .justifyContent(FlexAlign.Center)
      }
      .justifyContent(FlexAlign.Start)
      .alignItems(HorizontalAlign.Start)
      .width('96%')
      .height('82.7%')

      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(async () => {
            if (!this.process || !this.process.id) {
              promptAction.showToast({
                message: '请先工序开工',
                duration: 2000
              });
              return;
            }
            let rateTotal = 0
            for (const reporter of this.reporterList) {
              if (!reporter.workingHoursRate) {
                promptAction.showToast({
                  message: `请给${reporter.userName!}选择用时占比`,
                  duration: 2000
                });
                return;
              }
              rateTotal += reporter.workingHoursRate
            }
            if (rateTotal > 1) {
              promptAction.showToast({
                message: `用时占比超过100%，请修改`,
                duration: 2000
              });
              return;
            } else if (rateTotal < 1) {
              promptAction.showToast({
                message: `用时占比少于100%，请修改`,
                duration: 2000
              });
              return;
            }
            // 报工
            let seqNos: string [] = []
            if (this.bindTaskSeq[0].reportSeqNos) {
              seqNos = seqNos.concat(this.bindTaskSeq[0].reportSeqNos)
            }
            if (this.bindTaskSeq[0].defectSeqNos) {
              seqNos = seqNos.concat(this.bindTaskSeq[0].defectSeqNos)
            }
            if (seqNos.length <= 0) {
              promptAction.showToast({
                message: `请选择报工流水号或者不良流水号`,
                duration: 2000
              });
              return;
            }
            await ProcessRequest.post('/api/v1/process/info/reporting', {
              processId: this.process.id!,
              processUserReportList: this.reporterList,
              seqList: seqNos
            } as ProcessReportTimeBased)
            // 删除已报工的seqNo，并保存到数据库中
            let seqNoList: string[] = []
            seqNoList = await preferencesUtil.get(CommonConstants.PREFERENCE_INSTANCE_NAME, this.selectWorkOder.workOrderCode!, seqNoList)
            if (seqNoList.length === seqNos.length) {
              preferencesUtil.put(CommonConstants.PREFERENCE_INSTANCE_NAME, this.selectWorkOder.workOrderCode!, [])
            } else {
              seqNoList = seqNoList.filter(item => !seqNos.includes(item));
              await preferencesUtil.put(CommonConstants.PREFERENCE_INSTANCE_NAME, this.selectWorkOder.workOrderCode!, seqNoList)
            }
            this.clearSelectData()
            this.controller.close();
          })
        }
      }
      .width('100%')
      .height('7.3%')
    }
    .height('71%')
    .width('62%')
    .backgroundColor($r('app.color.2A2A2A'))
    .justifyContent(FlexAlign.End)
    .alignItems(HorizontalAlign.Center)
    .borderRadius($r('app.float.virtualSize_16'))
  }
}