import { promptAction } from "@kit.ArkUI"
import { ITaskItem, TaskItem } from "../models/Task"
import { ITaskCategory, TaskCategory } from "../models/TaskCategory"
import dayjs from 'dayjs'

//添加，详情弹窗
@CustomDialog
export struct TaskItemDialog {

  // taskItem: TaskItem=new TaskItem({} as ITaskItem)
  @Prop
  taskItem:ITaskItem={} as ITaskItem
  // @Link prefData: PreferenceData
  @Prop categoryList: ITaskCategory[]=[]
  controller: CustomDialogController
  confirm=(taskItem:ITaskItem) => {

  }

  @State title:string=""

  @State startDate:Date=new Date()
  @State dueDate:Date=new Date()
  @State taskName:string=""
  @State detail:string=""
  @State isCompleted:number=0
  @State category:number=1
  @State topped:number=0
  @State showedTaskCategory: string = '默认清单'


  @State taskCategoryColor: string = '#000000'
  @State handlePopup: boolean = false
  aboutToAppear(): void {
    if(this.taskItem.id==null){
      this.title='新增事项'
      this.category=1
      this.showedTaskCategory='默认清单'

    }else{
      this.title='编辑事项'
      this.startDate=new Date(this.taskItem.startDate)
      this.dueDate=new Date(this.taskItem.dueDate)
      this.taskName=this.taskItem.taskName
      this.detail=this.taskItem.detail
      this.isCompleted=this.taskItem.isCompleted
      this.category=this.taskItem.category
      this.topped=this.taskItem.topped
      this.showedTaskCategory=this.taskItem.categoryName
    }
  }


  @Builder DatePickerMenu(date: Date, str: string) {
    Menu() {
      MenuItem() {
        DatePicker({
          start: new Date('1970-01-01'),
          selected: date,
          end: new Date('2100-01-01')
        }).onDateChange((value:Date)=>{
           date=value
          if(str=='start'){
            this.startDate=date
          }else{
            this.dueDate=date
          }
        })
          .backgroundColor(0xffffff)
      }
    }
  }
  @Builder CategoryPickerMenu() {
    Menu() {
      ForEach(this.categoryList, (item:ITaskCategory,index:number) => {
        MenuItem({content: item.name}) {
          Text(item.name)
        }
          .onClick(() => {
            this.showedTaskCategory = item.name
            this.category=item.id as number
          })
      })
    }
  }


  // aboutToAppear() {
  //   this.taskName = this.taskItem.task_name
  //   this.taskSubject = this.taskItem.subject
  //   this.taskDetailText = this.taskItem.detail
  //   this.taskDdlDetail = this.taskItem.ddl_detail
  //   this.taskDate = new Date()
  //   this.startDate = new Date()
  //   this.taskDate.setSeconds(0)
  //   this.startDate.setSeconds(0)
  //   Logger.debug('TaskItemDialog new date = ' + this.taskDate.toLocaleString())
  //   if (this.taskItem.start_date_stamp) this.startDate.setTime(this.taskItem.start_date_stamp)
  //   if (this.taskItem.due_date_stamp) this.taskDate.setTime(this.taskItem.due_date_stamp)
  //   this.startTask[0] = getDateString(this.startDate.getTime())
  //   this.startTask[1] = getTimeString(this.startDate.getTime())
  //   this.endTask[0] = getDateString(this.taskDate.getTime())
  //   this.endTask[1] = getTimeString(this.taskDate.getTime())
  //   this.showedTaskDDL = getDDLPresetFromDetail(this.taskDdlDetail)
  //   this.taskCategoryID = this.taskItem.category
  //   for (let i = 0; i < this.categoryList.length; ++i) {
  //     if (this.categoryList[i].id == this.taskCategoryID) {
  //       this.showedTaskCategory = this.categoryList[i].name
  //       this.taskCategoryColor = this.categoryList[i].color
  //       break;
  //     }
  //     if (i == this.categoryList.length - 1) {
  //       this.taskCategoryID = this.categoryList[0].id
  //       this.showedTaskCategory = this.categoryList[0].name
  //       this.taskCategoryColor = this.categoryList[0].color
  //     }
  //   }
  // }

  build() {
    Column() {
      Image($r('app.media.half'))
        .width(64)
        .height(24)
        .onClick(() => {
          this.controller?.close();
        })
      .margin({top: 5})
      Column() {
        Column() {
          Row() {
            Text(this.title)
              .fontSize(20)
              .alignSelf(ItemAlign.Start)
              .fontColor('#564F4A')
            Button() {
              Text(this.showedTaskCategory).fontColor('#564F4A')
            }.backgroundColor('#f1f2f3')
            .borderRadius(5)
            .padding({left: 12, right: 12, top: 8, bottom: 8})
            .bindMenu(this.CategoryPickerMenu())
          }
          .margin({ left: 24, bottom: 20, right: 24 })
          .width('100%')
          .justifyContent(FlexAlign.SpaceBetween)

          TextInput({
            placeholder: '事项名称',
            text: this.taskItem.taskName
          })
            .borderRadius(10)
            .backgroundColor('rgba(254, 222, 155, 1)')
            .placeholderColor('rgba(86, 79, 74, 1)')
            .fontColor('rgba(86, 79, 74, 1)')
            .onChange((value: string) => {
              // this.taskItem.taskName = value
              this.taskName=value
            })
            .margin({ bottom: 10 })
            .height(50)
          TextArea({ placeholder: '详细信息', text: this.taskItem.detail })
            .borderRadius(10)
            .backgroundColor('rgba(254, 222, 155, 1)')
            .placeholderColor('rgba(86, 79, 74, 1)')
            .fontColor('rgba(86, 79, 74, 1)')
            .onChange((value: string) => {
              this.detail=value
            })
            .height(50 * 3)
          .margin({ bottom: 10 })
          // Row(){
          //   Button('任务紧急程度：' + this.showedTaskDDL)
          //     // .bindMenu(this.DDLDetailPickerMenu)
          //     .width('60%')
          //     .margin({ right: 15 })
          //     .backgroundColor(0xf1f2f3)
          //     .fontColor(0x000000)
          //   Button({type: ButtonType.Circle}) {
          //     Image($r('app.media.ic_public_help_filled'))
          //       .height(25)
          //       .width(25)
          //   }
          //     .onClick(() => {this.handlePopup = !this.handlePopup})
          //     .height(25)
          //     .width(25)
          //     .backgroundColor(0xffffff)
          //     .bindPopup(this.handlePopup, {
          //       message: '任务紧急程度会决定指示颜色变化的快慢，任务紧急程度越高，指示颜色越早变红。',
          //       placementOnTop: true,
          //       primaryButton: {
          //         value: '明白了',
          //         action: () => {this.handlePopup = false}
          //       }
          //     })
          // }
        }.padding({ left: 16, right: 16})
        .margin({ bottom: 16})
        Row() {
          Button('布置日期：   ' + dayjs(this.startDate).format('YYYY-MM-DD'))
            .width(200)
            .bindMenu(this.DatePickerMenu(new Date(this.startDate), 'start'))
            .backgroundColor('#adc1e2')
            .fontColor('rgba(86, 79, 74, 1)')
            .borderRadius(5)
            .margin({right: 10})

            Image($r('app.media.confim'))
              .onClick(() => {this.handlePopup = !this.handlePopup})
              .height(25)
              .width(25)
              .backgroundColor(0xffffff)
              .bindPopup(this.handlePopup, {
                message: '距离截至时间越近，指示的警告颜色就会加深',
                placementOnTop: true,
                primaryButton: {
                  value: '明白了',
                  action: () => {this.handlePopup = false}
                }
              })

          // Button(this.startTask[1])
          //   .bindMenu(this.TimePickerMenu(this.startDate, this.startTask))
          //   .backgroundColor(0xf1f2f3)
          //   .fontColor(0x000000)
        }.margin({bottom: 8})
        Row() {
          Button('截止日期：   ' +dayjs(this.dueDate).format('YYYY-MM-DD'))
            .width(200)
            .bindMenu(this.DatePickerMenu(new Date(this.dueDate),'due'))
            .backgroundColor('#adc1e2')
            .borderRadius(5)
            .fontColor('rgba(86, 79, 74, 1)')
            .margin({right: 10})

          Column(){

          }.width(25)
          .height(25)




          //
          // Button(this.endTask[1])
          //   .bindMenu(this.TimePickerMenu(this.taskDate,this.endTask))
          //   .backgroundColor(0xf1f2f3)
          //   .fontColor(0x000000)
        }
      }.margin({bottom: 16})
          // .margin({ bottom: 10 })
      Row({space:20}) {
            Text('取消')
              .fontSize(18)
              .fontWeight(500)
              .fontColor('rgba(86, 79, 74, 1)')
              .width(154)
              .height(44)
              .padding({left:58,right:58,top:10,bottom:10})
              .border({
                width:1,
                color:'rgba(86, 79, 74, 1)'
              })
              .borderRadius(8)
              .backgroundColor('rgba(254, 222, 155, 1)')
              .onClick(() => {
                this.controller.close()
              })
        Text('保存')
          .fontSize(18)
          .fontWeight(500)
          .fontColor('rgba(86, 79, 74, 1)')
          .width(154)
          .height(44)
          .padding({left:58,right:58,top:10,bottom:10})
          .border({
            width:1,
            color:'rgba(86, 79, 74, 1)'
          })
          .borderRadius(8)
          .backgroundColor('rgba(254, 222, 155, 1)')
          .onClick(() => {
            if (this.taskItem.taskName == '') {
              promptAction.showToast({message: '任务名称不能为空'})
              return
            }
            if (this.dueDate.getTime() < this.startDate.getTime()) {
              promptAction.showToast({message: '结束日期不能在开始日期之前'})
              return
            }
            this.taskItem={
              id:this.taskItem.id,
              taskName:this.taskName,
              detail:this.detail,
              startDate:this.startDate.getTime(),
              dueDate:this.dueDate.getTime(),
              isCompleted:this.isCompleted,
              category:this.category,
              categoryName:this.showedTaskCategory,
              topped:this.topped
            }
            this.confirm(this.taskItem)


            // this.taskItem.subject = this.taskSubject
            // this.taskItem.task_name = this.taskName
            // this.taskItem.detail = this.taskDetailText
            // this.taskItem.due_date_stamp = this.taskDate.getTime()
            // this.taskItem.start_date_stamp = this.startDate.getTime()
            // this.taskItem.ddl_detail = this.taskDdlDetail
            // this.taskItem.category = this.taskCategoryID
            // Logger.debug(`TaskItemDialog ddlDetail = ${this.taskItem.ddl_detail}`)
            // // Logger.debug(`TaskItemDialog due_date(stamp): ${this.taskItem.due_date_stamp}, date: ${this.taskDate.toDateString()}`)
            // this.confirm(this.dialogIsAddNew, this.taskItem)
            this.controller.close()
          })
      }.margin({ bottom: 20 })
    }.backgroundColor('#fdf8ec')
    .width('100%')
    // .height('60%')
    .borderRadius(24)
    .justifyContent(FlexAlign.SpaceBetween)
  }
}

function getTimeString(date_stamp: number): string {
  let date: Date = new Date()
  date.setTime(date_stamp)
  // Logger.debug(`TaskList: datestamp = ${date_stamp}, time = ${date.toLocaleTimeString()}`)
  return date.toLocaleTimeString()
}

function getDateString(date_stamp: number): string {
  let date: Date = new Date()
  date.setTime(date_stamp)
  // Logger.debug(`TaskList: datestamp = ${date_stamp}, date = ${date.toLocaleDateString()}`)
  let ds: string[] = date.toLocaleDateString().split('/')
  let res: string = `${ds[2]}/${ds[0]}/${ds[1]}`
  return res
}

// function getDDLPresetFromDetail(detail: string): string {
//   for (let i = 0; i < 5; ++i) {
//     Logger.debug('getDDL: ' + CommonConstants.DDL_DETAIL_PRESET[i].detail)
//     if (CommonConstants.DDL_DETAIL_PRESET[i].detail == detail) return CommonConstants.DDL_DETAIL_PRESET[i].hint
//   } return ''
// }