import ProcessRequest from '../common/util/request/ProcessRequest'
import { MessageInfo, MessagePage } from '../viewmodel/MessageInfo'
import { UserInfo, WorkstationInfo } from '../viewmodel/UserInfo'
import RequestParamModel from '../viewmodel/RequestParamModel'
import { SwitchingStationDialog } from './SwitchingStationViews'
import CommonConstants from '../common/constants/CommonConstants'

@CustomDialog
export struct LoginInfoDialog {
  private scrollerList: Scroller = new Scroller()
  //当前工位
  @Consume('currentStation') currentStation: string
  //当前工位id
  @Consume('currentStationId') @Watch('loadStationMessage') currentStationId: string
  //当前部门
  @Consume('currentDept') currentDept: string
  //当前产线
  @Consume('currentProductLine') currentProductLine: string
  //当前产线code
  @Consume('currentPLCode') currentPLCode: string
  //当前用户
  @Consume('currentUserName') currentUserName: string
  //当前用户id
  @Consume('currentUserId') currentUserId: number
  //全部已读按钮缩放
  @State allReadClick:number = 1
  //消息列表
  @State messages: MessageInfo[] = [];
  //登录标志（1:工牌扫码 2:账号密码 3:已登录）
  @State loginFlag: number = 2
  // 用户名
  @State userName: string = ''
  // 密码
  @State password : string = ''
  // 人员工号
  @State employeeCode : string = ''
  // 登录用户信息
  @State loginUser: UserInfo = {}
  controller: CustomDialogController
  //查找部门
  searchDept: () => void = () => {}
  //查找产线
  searchProductLine: () => void = () => {}
  //查找工位
  searchStation: () => void = () => {}
  //请求登录并查询用户信息，刷新页面
  requestLoginAndRefresh = async ()=> {
    let token:string = await ProcessRequest.post('api/auth/aioLogin', {
      password: this.password,
      userName: this.userName,
      jobNumber: this.employeeCode,
    } as RequestParamModel) ;
    if (!token || token.length == 0) return
    CommonConstants.AUTH_TOKEN = token
    this.currentUserName = this.userName
    let res:UserInfo = await ProcessRequest.get('/api/auth') ;
    this.currentUserId = res.id!
    this.loginUser = await ProcessRequest.post('/api/v1/sys/user/get', {id: this.currentUserId} as RequestParamModel) as UserInfo
    if (this.loginUser.depts) {
      this.loginUser.deptNames = this.loginUser?.depts[0]?.deptName!
    }
    this.loginFlag = 3
  }

  async loadStationMessage() {
    let res = await ProcessRequest.post('/api/v1/sys/message/stationMessage', {
      stationId: this.currentStationId
    } as RequestParamModel) as MessagePage;
    this.messages=res?.records??[]
    this.messages = [...this.messages].sort((a, b) => {
      const stateA = a.readState ?? '1';
      const stateB = b.readState ?? '1';
      return parseInt(stateA) - parseInt(stateB);
    });
  }

  // 标记消息为已读
  markAsRead = async (item: MessageInfo) => {
    if (item.readState === '1') return // 已经是已读状态
    try {
      await ProcessRequest.post('http://192.168.1.3:20010/api/v1/sys/message/confirmMessage', {
        ids:[item.id]
      } as RequestParamModel);
      //this.loadStationMessage();
      item.readState = '1'
      this.messages = [...this.messages].sort((a, b) => {
        const stateA = a.readState ?? '1';
        const stateB = b.readState ?? '1';
        return parseInt(stateA) - parseInt(stateB);
      });
    } catch (e) {
      console.error('标记已读失败:', e)
    }
  }

  markAllAsRead = async () => {
    try {
      const messageIds = this.messages
        .filter(item => item.readState === '0' && item.id)
        .map(item => item.id);
      if (messageIds.length === 0) return;
      await ProcessRequest.post('http://192.168.1.3:20010/api/v1/sys/message/confirmMessage', {
        ids:messageIds as string[]
      } as RequestParamModel);
      //this.loadStationMessage();
      this.messages = this.messages.map(item => {
        return {
          readState: '1',
          content: item.content,
          created: item.created,
        } as MessageInfo;
      });
      this.messages = this.messages.slice().sort((a, b) => {
        const stateA = a.readState ?? '1';
        const stateB = b.readState ?? '1';
        return parseInt(stateA) - parseInt(stateB);
      });
    } catch (e) {
      console.error('全部已读操作失败:', e);
    }
  }

  async aboutToAppear() {
    if (this.currentUserName) {
      if (this.currentStationId) {
        this.loadStationMessage()
      }
      this.loginUser = await ProcessRequest.post('/api/v1/sys/user/get', {id: this.currentUserId!} as RequestParamModel) as UserInfo
      if (this.loginUser.depts) {
        this.loginUser.deptNames = this.loginUser?.depts[0]?.deptName!
      }
      this.loginFlag = 3
    }
  }

  build() {
    Column() {
      Column() {
        Text('登录信息')
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_30'))
          .fontWeight(FontWeight.Medium)
      }
      .height('10%')
      .width('100%')
      .justifyContent(FlexAlign.Center)

      Row(){
        Column() {
          if (this.loginFlag === 3) {
            Column() {
              Stack() {
                Image(this.loginUser?.avatar ? CommonConstants.FILE_URL_PREFIX + this.loginUser.avatar : $r('app.media.process_user_default_avatar'))
                  .objectFit(ImageFit.Auto)
                Column({space: 1}) {
                  Text(this.loginUser?.userName!)
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_24'))
                    .fontWeight(FontWeight.Medium)
                  Text(this.loginUser?.deptNames!)
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Lighter)
                }
                .height('72%')
                .justifyContent(FlexAlign.Center)
              }
              .height('78%')
              .width('68.4%')
              .alignContent(Alignment.Top)
              Divider()
                .vertical(false)
                .strokeWidth(1)
                .color($r('app.color.15FFFFFF'))
                .width('100%')
              Button('登出', {type: ButtonType.Normal })
                .height('16.8%')
                .width('100%')
                .fontColor($r('app.color.0A84FF'))
                .fontSize($r('app.float.fontSize_24'))
                .fontWeight(FontWeight.Medium)
                .borderRadius({bottomRight: $r('app.float.virtualSize_16'), bottomLeft: $r('app.float.virtualSize_16')})
                .backgroundColor($r('app.color.5FFFFFF'))
                .onClick(async () => {
                  await ProcessRequest.post('/api/auth/loginOut')
                  this.currentUserName = ''
                  this.currentUserId = 0
                  CommonConstants.AUTH_TOKEN = ''
                  this.loginUser = {}
                  this.loginFlag = 2
                })
            }
            .width('69%')
            .height('57.2%')
            .justifyContent(FlexAlign.End)
            .borderRadius($r('app.float.virtualSize_16'))
            .backgroundColor($r('app.color.5FFFFFF'))
            Blank().height('9.6%')
          } else {
            Row({space: 24}) {
              Text('工牌扫码')
                .fontColor(this.loginFlag === 1 ? $r('app.color.0A84FF') : $r('app.color.FFFFFF'))
                .fontSize($r('app.float.fontSize_24'))
                .fontWeight(FontWeight.Medium)
                .onClick(()=>{
                  this.loginFlag = 1
                })
              Text('账号密码')
                .fontColor(this.loginFlag === 2 ? $r('app.color.0A84FF') : $r('app.color.FFFFFF'))
                .fontSize($r('app.float.fontSize_24'))
                .fontWeight(FontWeight.Medium)
                .onClick(()=>{
                  this.loginFlag = 2
                })
            }
            .width('66.7%')
            .height('6%')
            Divider()
              .vertical(false)
              .strokeWidth(1)
              .color($r('app.color.15FFFFFF'))
              .width('69%')
            if (this.loginFlag === 1) {
              Column() {
                Row() {
                  Row().width('3.4%')
                  // 左侧二维码图标
                  Image($r('app.media.material_qr_code')) // 请替换为您的二维码图片资源
                    .width($r('app.float.virtualSize_24'))
                    .height($r('app.float.virtualSize_24'))
                    .fillColor($r('app.color.FFFFFF'))
                  // 扫码输入框
                  TextInput({ placeholder: '请录入工牌号', text: this.employeeCode })
                    .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)
                    .onChange((value: string) => {
                      this.employeeCode = value
                    })
                }
                .height('15.8%')
                .width('100%')
                .borderRadius($r('app.float.virtualSize_16'))
                .backgroundColor($r('app.color.000000'))
                .justifyContent(FlexAlign.Start)

                Button('登录', {type: ButtonType.Normal })
                  .height('15.8%')
                  .width('100%')
                  .fontColor($r('app.color.0A84FF'))
                  .fontSize($r('app.float.fontSize_24'))
                  .fontWeight(FontWeight.Medium)
                  .backgroundColor($r('app.color.20FFFFFF'))
                  .borderRadius($r('app.float.virtualSize_16'))
                  .opacity(this.employeeCode ? 1 : 0.3)
                  .onClick(async () => {
                    this.requestLoginAndRefresh()
                  })
              }
              .height('60.8%')
              .width('69%')
              .justifyContent(FlexAlign.SpaceAround)
            } else if (this.loginFlag === 2) {
              Column() {
                Row() {
                  Image($r('app.media.process_user_name'))
                    .width($r('app.float.virtualSize_40'))
                    .height($r('app.float.virtualSize_40'))
                    .fillColor($r('app.color.FFFFFF'))
                    .margin({left:'2%'})

                  TextInput({text: this.userName, placeholder:'请录入账户'})
                    .width('85%')
                    .height('100%')
                    .backgroundColor('#000000')
                    .fontSize($r('app.float.fontSize_16'))
                    .placeholderFont({size:$r('app.float.fontSize_16')})
                    .placeholderColor($r('app.color.30FFFFFF'))
                    .fontColor($r('app.color.FFFFFF'))
                    .onChange((value: string) => {
                      this.userName = value;
                    })
                }
                .backgroundColor($r('app.color.000000'))
                .height('15.8%')
                .width('100%')
                .borderRadius($r('app.float.virtualSize_16'))

                Row() {
                  Image($r('app.media.process_password'))
                    .width($r('app.float.virtualSize_40'))
                    .height($r('app.float.virtualSize_40'))
                    .fillColor($r('app.color.FFFFFF'))
                    .margin({left:'2%'})
                  TextInput({text:this.password, placeholder:'请录入密码'} )
                    .width('85%')
                    .height('100%')
                    .placeholderFont({size:$r('app.float.fontSize_16')})
                    .placeholderColor($r('app.color.30FFFFFF'))
                    .backgroundColor('#000000')
                    .fontSize($r('app.float.fontSize_16'))
                    .fontColor($r('app.color.FFFFFF'))
                    .type(InputType.Password)
                    .onChange((value: string) => {
                      this.password = value;
                    })
                }
                .height('15.8%')
                .width('100%')
                .backgroundColor($r('app.color.000000'))
                .borderRadius($r('app.float.virtualSize_16'))

                Button('登录', {type: ButtonType.Normal })
                  .height('15.8%')
                  .width('100%')
                  .fontColor($r('app.color.0A84FF'))
                  .fontSize($r('app.float.fontSize_24'))
                  .fontWeight(FontWeight.Medium)
                  .backgroundColor($r('app.color.20FFFFFF'))
                  .borderRadius($r('app.float.virtualSize_16'))
                  .opacity((this.userName && this.password) ? 1 : 0.3)
                  .onClick(async () => {
                    if (!this.userName || !this.password) {
                      return
                    }
                    this.requestLoginAndRefresh()
                  })
              }
              .height('60.8%')
              .width('69%')
              .justifyContent(FlexAlign.SpaceEvenly)
            }
          }
          Divider()
            .vertical(false)
            .strokeWidth(1)
            .color($r('app.color.15FFFFFF'))
            .width('69%')
          Column({space: 6}) {
            Text('工位')
              .fontColor($r('app.color.FFFFFF'))
              .fontSize($r('app.float.fontSize_16'))
              .fontWeight(FontWeight.Regular)
              .width('95%')
              .textAlign(TextAlign.Start)
            Row(){
              Text(this.currentStation)
                .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.Center)
            .borderRadius($r('app.float.virtualSize_16'))
            .width('100%')
            .height('51.6%')
            .backgroundColor($r('app.color.20FFFFFF'))
            .onClick(()=>{
              this.searchStation()
            })
          }
          .height('26.6%')
          .width('69%')
          .justifyContent(FlexAlign.Center)
        }
        .justifyContent(FlexAlign.Start)
        .alignItems(HorizontalAlign.Center)
        .height('100%')
        .width('46.6%')
        Divider()
          .vertical(true)
          .strokeWidth(1)
          .color($r('app.color.15FFFFFF'))
        Column(){
          Row(){
            Text('工位通知')
              .fontColor($r('app.color.FFFFFF'))
              .fontSize($r('app.float.fontSize_24'))
              .textAlign(TextAlign.Start)
              .width('80%')
            Row(){
              Text('全部已读')
                .fontColor($r('app.color.FFFFFF'))
                .fontSize($r('app.float.fontSize_16'))
            }
            .backgroundColor($r('app.color.20FFFFFF'))
            .width('20%')
            .height('80%')
            .borderRadius($r('app.float.virtualSize_16'))
            .justifyContent(FlexAlign.Center)
            .scale({ x: this.allReadClick, y: this.allReadClick })
            .animation({
              duration: 200,
              curve: Curve.Linear
            })
            .onClick(()=>{
              this.allReadClick = 0.9;
              setTimeout(() => {
                this.allReadClick = 1;
                this.markAllAsRead()
              }, 200);
            })
          }
          .width('100%')
          .height('8%')
           Column(){
             List({scroller:this.scrollerList}) {
               ForEach(this.messages, (item:MessageInfo) => {
                 ListItem() {
                   Row() {
                     Column(){
                       Text(item.content)
                         .fontSize($r('app.float.fontSize_16'))
                         .fontColor($r('app.color.FFFFFF'))
                         .width('85%')
                         .textAlign(TextAlign.Start)
                       Text(item.created)
                         .fontSize($r('app.float.fontSize_12'))
                         .fontColor($r('app.color.FFFFFF'))
                         .width('85%')
                         .textAlign(TextAlign.Start)
                         .margin({top:'1%'})
                         .fontWeight(FontWeight.Lighter)
                     }
                     Row(){
                       Text(item.readState=='1'?`已读`:'已读确认')
                         .fontSize($r('app.float.fontSize_16'))
                         .fontColor(item.readState=='1'?$r('app.color.FFFFFF'):$r('app.color.0A84FF'))
                         .width('15%')
                         .textAlign(TextAlign.End)
                         .onClick(() => this.markAsRead(item))
                     }
                   }.width('100%').justifyContent(FlexAlign.SpaceEvenly)
                   .padding(5)
                 }
               })
             }
             .width('100%')
             .height('100%')
             .divider({
               strokeWidth: 1,
               color: $r('app.color.20FFFFFF')
             })
           }
          .height('90%')


        }
        .width('46.6%')
        .height('100%')
      }
      .justifyContent(FlexAlign.SpaceEvenly)
      .width('100%')
      .height('76%')

      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(() => {
            this.controller.close();
          })
        }
      }
      .width('100%')
      .height('8%')
    }
    .height('71%')
    .width('62%')
    .backgroundColor($r('app.color.2A2A2A'))
    .justifyContent(FlexAlign.SpaceBetween)
    .alignItems(HorizontalAlign.Start)
    .borderColor($r('app.color.000000'))
    .borderWidth(1)
    .borderRadius($r('app.float.virtualSize_16'))
  }
}


