import { Component, OnInit } from '@angular/core';
import { TrackingService } from '../services/tracking.service';
import { ActivatedRoute, Router } from '@angular/router';
import { NavController, ToastController } from '@ionic/angular';
import Parse from "parse";
Parse.initialize("dev"); // 设置applicationId
Parse.serverURL = "http://web2023.fmode.cn:9999/parse"; // 设置serverURL

@Component({
  selector: 'app-request',
  templateUrl: './request.page.html',
  styleUrls: ['./request.page.scss']
})
export class RequestPage implements OnInit {
  orderInfo: any = {
    consignee: '',
    address: '',
    phone: '',
    title: '',
    remark: '',
    authors: ""
  };
  
  bookInfo:any;
  constructor(
    private navController: NavController,
    private toastController: ToastController,
    private router: Router,
    private route:ActivatedRoute,
    private trackingService: TrackingService
  ) {}
  ngOnInit() {
    this.loadBookById();
  }

  save() {
    // 创建 Parse 表对象
    const Order = Parse.Object.extend('AWOrder');
    let deliveryTime = new Date();
    let status = '准备中';
    let trackingNumber: string = this.trackingService.generateTrackingNumber();
    let orderNumber = trackingNumber;
    
    // 创建
    const newOrder = new Order();
    newOrder.set('consignee', this.orderInfo.consignee);
    newOrder.set('address', this.orderInfo.address);
    newOrder.set('phone', this.orderInfo.phone);
    newOrder.set('title', this.orderInfo.title);
    newOrder.set('remark', this.orderInfo.remark);
    newOrder.set('authors', this.orderInfo.authors);
    newOrder.set('deliveryTime', deliveryTime);
    newOrder.set('status', status);
    newOrder.set('orderNumber', orderNumber);

    // 保存新的 Book 对象到 Parse 表中
    newOrder.save().then((savedOrder: Parse.Object) => {
      console.log('New order added successfully:', savedOrder);
    }).catch((error: Error) => {
      console.error('Error adding new order:', error);
    });
  }

  

  async loadBookById(){
    // let id = location.pathname.split("/").pop();
    let id = this.route.snapshot.params["id"]
    
    if(id){
      let query = new Parse.Query("AWBook");
      this.bookInfo = await query.get(id);
    }

    this.orderInfo.title = this.bookInfo.get("title");
    this.orderInfo.authors = this.bookInfo.get("authors");
    
  }

  public alertButtons = [
    {
      text: '取消',
      role: 'cancel',
      // handler: () => {
      //   console.log('Alert canceled');
      // },
    },
    {
      text: '确定',
      role: 'confirm',
      handler: () => {
        this.router.navigate(['/tabs/tab3']);
      },
    },
  ];


  async presentToast() {
    const toast = await this.toastController.create({
      message: '已超过最大字数限制',
      duration: 1000, // 显示时长为1秒
      position: 'middle', // 在页面中部显示
      cssClass: 'toast-center'
    });
    toast.present();
  }
  updateCharacterCount(event: any) {
    const maxLength = 50;
    let currentLength = event.target.value.length; 
  
    const characterCountElement = document.querySelector('.character-count');

    if (characterCountElement) {
      characterCountElement.textContent = currentLength;
    }

    if (currentLength > maxLength) {
      this.presentToast();
      const trimmedValue = event.target.value.substring(0, maxLength);
      event.target.value = trimmedValue;
      currentLength = maxLength;
    }
    this.orderInfo.remark = event.target.value;
  }
}