
import { ReNameInput } from "../components/ReNameInput"
import { TaskItemDialog } from "../dialog/TaskItemDialog"
import { ITaskItem, TaskItem } from "../models/Task"
import { ITaskCategory, TaskCategory } from "../models/TaskCategory"
import dayjs from 'dayjs'
import { promptAction } from "@kit.ArkUI"
import { taskItemDB } from "../database/TaskDataBase"
import { YTAvoid } from "../utils/YTAvoid"


@Extend(Text) function textTitle() {
  .fontSize(20)
  .width('100%')
  .margin({ left: 12})
  .textAlign(TextAlign.Start)
}

@Component
export struct Main {
  @State taskList: Array<TaskItem> = []
  @State categoryList: Array<ITaskCategory> = [
    {
      color:'#000000',
      name:'默认清单',
      id: 1,
    },
    {
      id:2,
      name:"学习清单",
      color:"#fff"
    },
    {
      id:2,
      name:"生活清单",
      color:"#fff"
    },
    {
      id:2,
      name:"其他清单",
      color:"#fff"
    },

  ]

  @StorageProp(YTAvoid.SAFE_TOP_KEY)
  top:number=0
  @State isEditing: boolean = true
  @State dialogIsAddNew: boolean = true
  @State
  taskEditItem:ITaskItem={} as ITaskItem
  taskEditId:number=0
  taskCategoryCount:number=0

  dialogController: CustomDialogController = new CustomDialogController({
    builder: TaskItemDialog({
      taskItem:this.taskEditItem,
      categoryList:this.categoryList,
      confirm:(item:ITaskItem)=>{
        // this.taskList.push(item)
        if(item.id==null){
          //新增
          this.taskList.push(new TaskItem(item))
          //新增
          this.insertTaskData({
            id:null,
            taskName:item.taskName,
            detail:item.detail,
            startDate:item.startDate,
            dueDate:item.dueDate,
            isCompleted:item.isCompleted,
            category:item.category,
            categoryName:item.categoryName,
            topped:item.topped
          } as ITaskItem)
        }else{
          //先更新task列表的数据
         this.taskList.forEach((itemD,index)=>{
           if(itemD.id==this.taskEditId){
             this.taskList[index]=new TaskItem(item)
           }
         })
          //再更新数据库数据
          this.updateTaskData({
            id:item.id,
            taskName:item.taskName,
            detail:item.detail,
            startDate:item.startDate,
            dueDate:item.dueDate,
            isCompleted:item.isCompleted,
            category:item.category,
            categoryName:item.categoryName,
            topped:item.topped
          } as ITaskItem)
        }

      }

    }),
    alignment: DialogAlignment.Bottom,
    customStyle: true
  })

  //删除单个
  @Builder
  itemEnd(taskItem:TaskItem) {
    Row() {
        Text("完成")
          .fontSize(16)
          .backgroundColor('#F59A23')
          .fontColor(Color.Black)
          .textAlign(TextAlign.Center)
          .width(60)
          .height('100%')
          .borderRadius({
            topRight: 10,
            bottomRight: 10
          })
          .onClick(() => {
            //将当前设置为已完成
            //如果时已办事项，就提示已经完成  不能完成

          })
      Text("删除")
        .fontSize(16)
        .backgroundColor('#FF3B30')
        .fontColor(Color.White)
        .textAlign(TextAlign.Center)
        .width(60)
        .height('100%')
        .borderRadius({
          topRight: 10,
          bottomRight: 10
        })
        .onClick(() => {
          //先删除本地数组数据
         // const a= this.taskList.slice(index,1)
         //  this.taskList=[]
         //  this.taskList=a
         //
          const arr=this.taskList.filter(item=>item.id!=taskItem.id)
          this.taskList=[]
          this.taskList=arr
          // promptAction.showToast({
          //   message:JSON.stringify(taskItem)
          // })
          //再删除数据里面的数据
          let ids=[] as number[]
          ids.push(taskItem.id as number)
          this.deleteTaskData(ids)
        })
    }.padding(0).justifyContent(FlexAlign.SpaceEvenly)
  }
  @Builder
  TaskList_ListItem(taskItem:TaskItem) {
    Row() {
      Text(taskItem.taskName)
        .textOverflow({overflow: TextOverflow.Ellipsis })
        .maxLines(1)


      Blank()

      Row() {
        Text(dayjs(taskItem.startDate).format('YYYY-MM-DD'))
          .margin({right: 10})


        Text(taskItem.categoryName)
          .fontSize(14)
          .borderRadius(10)
          .backgroundColor('#f1f2f3')
          .margin({right: 8})
          .padding({left: 6, right: 6, top: 4, bottom: 4})

        Column(){

        }.width(12)
        .height(12)
        .backgroundColor(taskItem.getTaskColor())
        .borderRadius('50%')
      }
      // if (this.isEditing) {
      //   Toggle({ type: ToggleType.Checkbox, isOn: false })
      //     .onChange((isOn: Boolean) => {
      //       if (isOn) this.deleteTarget.push(item)
      //       else {
      //         let this_id_index = this.deleteTarget.indexOf(item)
      //         this.deleteTarget.splice(this_id_index, 1)
      //       }
      //     })
      // }
    }
    .height(56)
    .borderRadius(10)
    .width('100%')
    .backgroundColor('#eef6f0')
    .padding({ left: 12, right: 12 })
    .border({ width: 1, color: '#756860' })
    .shadow({
      // 模糊半径
      radius: 10,
      // 阴影类型
      type: ShadowType.COLOR,
      // 阴影颜色
      color: 'rgba(181, 228, 255,0.5)',
      // X 轴偏移
      offsetX: -3,
      // Y 轴偏移
      offsetY: 10,
      // 是否内部填充，值为布尔型，默认为flase
      fill: false
    })
    .onClick(()=>{
      this.taskEditItem=
        {
          id:taskItem.id,
          taskName:taskItem.taskName,
          detail:taskItem.detail,
          startDate:taskItem.startDate,
          dueDate:taskItem.dueDate,
          category:taskItem.category,
          categoryName:taskItem.categoryName,
          isCompleted:taskItem.isCompleted,
          topped:taskItem.topped
      }
      // promptAction.showToast({
      //   message:JSON.stringify(this.taskEditItem),
      //   offset:{
      //     dx:10,
      //     dy:10
      //   }
      // })
      this.taskEditId=taskItem.id as number
      this.dialogController.open()
    })
  }
  /**
   * 任务api
   */
  //获取task数据
  async getTaskData(){
    const list= await taskItemDB.query()  as ITaskItem[]
    list.map((item)=>{
     this.taskList.push(new TaskItem(item))
    })
    promptAction.showToast({
      message:JSON.stringify(this.taskList)
    })
  }
  //添加数据
  async insertTaskData(item:ITaskItem){
    const a=await taskItemDB.insert(item)
  }
  async updateTaskData(item:ITaskItem){
    await taskItemDB.update(item)
  }
  async deleteTaskData(ids:number[]){
    await taskItemDB.delete(ids)
  }
  aboutToAppear(): void {
    this.getTaskData()
  }
  build() {
    Column() {
      Stack({ alignContent: Alignment.BottomEnd }) {
        Column() {
          Search()
            .width('100%')
            .height(40)
            .onSubmit((value: string) => {
              // this.querySearchTask(value)
            })


          Scroll() {
            Column({space:20}) {
              Column({ space: 10 }) {
                Text('未办事项')
                  .textTitle()
                List({ space: 5 }) {
                  ForEach(this.taskList, (item: TaskItem, index:number) => {
                    if(item.isCompleted==0) {
                      ListItem() {
                        this.TaskList_ListItem(item)
                      }.swipeAction({
                        end: this.itemEnd.bind(this, item)
                      })
                    }
                  })
                  //,(item:TaskItem,index)=>{return item.id+index.toString()}
                }
                .width('100%')
                .height(250)
                .scrollBar(BarState.Off)
                .nestedScroll({
                  scrollForward: NestedScrollMode.SELF_FIRST,
                  scrollBackward: NestedScrollMode.PARENT_FIRST
                })
              }.width('100%')
              .height(300)
              .padding({ left: 10, right: 10 })
              .borderRadius(20)

              Column({ space: 10 }) {
                Text('已办事项')
                  .textTitle()

                Column() {
                  List({ space: 5 }) {
                    ForEach(this.taskList, (item: TaskItem, index) => {
                      if(item.isCompleted==1) {

                        ListItem() {
                          this.TaskList_ListItem(item)
                        }.swipeAction({
                          end: this.itemEnd.bind(this, item),
                        })
                      }
                    })
                  }
                }.width('100%')
                .layoutWeight(1)

              }.width('100%')
              .padding({ left: 10, right: 10 })
              .borderRadius(20)

            }
          }.width('100%')
          .layoutWeight(1)
          .scrollBar(BarState.Off)
        }.width('100%')
        .height('100%')
        // UI 右下角的 Fab
        Button({ type: ButtonType.Circle }) {
         Image($r('app.media.home_add'))
        }
        .backgroundColor(this.isEditing ? 0x0A59F7 : 0xE84026)
        .width(60)
        .height(60)
        .margin({ bottom: 12, right: (this.isEditing ? 0 : 12) })
        .onClick(() => {
          this.taskEditItem={} as ITaskItem
          this.dialogController.open()
        })
      }.layoutWeight(1)
    }.width('100%')
    .height('100%')
    .padding({ left: 10, right: 10})
  }
}


