import dayjs from 'dayjs'
import { noteDB } from '../database/NoteDB'
import { NoteDBInfo } from '../models/Note'

@Component
export struct Note {
  // 笔记列表
  @State list: NoteDBInfo[] = []

  // 标题
  @State noteId:number| null=null
  @State title: string = ''
  // 内容
  @State content: string = ''

  @State isShow:boolean=false

  // onPageShow(): void {
  //   this.getList()
  // }

  // 获取列表
  async getList() {
    this.list = await noteDB.query()
  }

  // 删除数据
  async deleteData(ids: number[]) {
    await noteDB.delete(ids)
    this.getList()
  }

  // 获取笔记详情-回显到页面中
  async getDetail() {
    // 根据 id 查找笔记
    const list = await noteDB.query(this.noteId as number)
    // 提取出笔记详情
    const detail = list[0]
    // 如果有笔记详情，回显到页面中
    if (detail) {
      this.title = detail.title
      this.content = detail.content
    }
  }

  async update(){
    await noteDB.update({
      id: this.noteId,
      title: this.title,
      content: this.content,
      date_added: Date.now()
    })
    this.getList()
  }

  async insert(){
    await noteDB.insert({
      id: null,
      title: this.title,
      content: this.content,
      date_added: Date.now()
    })
    this.getList()
  }

  @Builder
  swipeActionEnd(id: number) {
    Row() {
      Button("删除")
        .type(ButtonType.Normal)
        .height('100%')
        .aspectRatio(1)
        .backgroundColor('#FF5E5D')
        .onClick(() => {
          // TODO：删除
          let ids=[] as number[]
          ids.push(id)
          this.deleteData(ids)
        })
    }
    .height('100%')
    .justifyContent(FlexAlign.SpaceEvenly)
  }
  aboutToAppear(): void {
    this.getList()
  }

  @Builder
  AddOrEditBuilder(){
    Stack({ alignContent: Alignment.Bottom }) {
      Column({ space: 10 }) {
        Row() {
          Text('标题')
            .fontSize(14)
            .fontColor(Color.Black)

          Text('保存')
            .fontSize(14)
            .fontColor(Color.Black)
            .onClick(()=>{
              //修改笔记内容，新增笔记内容
              //todo:
              if(this.noteId!=null){
                this.update()
              }else{
                this.insert()
              }
              this.isShow=false
              this.noteId=null
              this.title=""
              this.content=""

            })

        }.width('100%')
        .justifyContent(FlexAlign.SpaceBetween)
        TextInput({ placeholder: '请输入笔记标题', text: this.title })
          .backgroundColor(Color.White)
          .border({ width: 1, color: Color.Black, radius: 6 })
          .padding({ left: 10 })
          .onChange((text) => {
            this.title = text
          })
          //
        Text('内容')
          .fontSize(14)
          .fontColor(Color.White)
          .width('100%')
        TextArea({ placeholder: '请输入笔记内容', text: this.content })
          .backgroundColor(Color.White)
          .border({ width: 1, color: Color.Black, radius: 6 })
          .layoutWeight(1)
          .padding(10)
          .onChange((text) => {
            this.content = text
          })
      }
      .padding({ bottom: 160 })

      // if (this.routerParams.id) {
        // 底部按钮
        Row({ space: 10 }) {
          Button('分享')
            .type(ButtonType.Normal)
            .backgroundColor(Color.Pink)
            .borderRadius(10)
            .layoutWeight(1)
            .onClick(() => {
              // this.shareNote()
            })
        // }

      }.width('100%')
        .padding({ bottom: 80 })
    }
    .padding({ left: 15, right: 15, top: 20 })
  }

  build() {
      Stack({ alignContent: Alignment.BottomEnd }) {
        if (this.list.length!=0) {
          Column() {
            List() {
              ForEach(this.list, (item: NoteDBInfo) => {
                ListItem() {
                  Row() {
                    Column() {
                      Text(item.title)
                        .fontSize(16)
                        .fontColor(Color.Black)
                      Text(dayjs(item.date_added)
                        .format('YYYY年MM月DD日'))
                        .fontSize(12)
                        .fontColor(Color.Black)
                        .lineHeight(25)
                    }
                    .alignItems(HorizontalAlign.Start)

                    Column() {
                      Image($r('app.media.icon'))
                        .width(22)
                        .aspectRatio(1)
                    }
                    .justifyContent(FlexAlign.Center)
                    .height('100%')
                  }
                  .width('100%')
                  .justifyContent(FlexAlign.SpaceBetween)
                  .padding({ left: 15, right: 15 })
                  .onClick(() => {
                    this.isShow=true
                    this.noteId=item.id as number
                    this.title=item.title
                    this.content=item.content
                  })
                }
                .height(72)
                .transition({ type: TransitionType.Delete, opacity: 0 })
                .swipeAction({
                  end: {
                    builder:this.swipeActionEnd(item.id),
                  },
                  edgeEffect: SwipeEdgeEffect.None
                })
              })
              // 底部占位
              ListItem()
                .height(126)
            }
            // 每行之间的分界线
            .divider({
              strokeWidth: 1,
              color: Color.Pink,
              startMargin: 15,
              endMargin: 15
            })
            .width('100%')
            .height('100%')
          }
          .height('100%')
        } else {
         //还没有笔记
          Column(){


            Text('去添加')
              .padding({left:16,right:16,top:10,bottom:10})
              .backgroundColor('#d1fd45')
              .borderRadius(15)

          }.width('100%')
          .height('100%')
          .justifyContent(FlexAlign.Center)

        }

        Column() {
          Image($r("app.media.home_add"))
            .width(56)
            .aspectRatio(1)
            .onClick(() => {
              this.isShow=true
              this.noteId=null
              this.title=""
              this.content=""
            })
        }
        .width('100%')
        .height(126)
        .justifyContent(FlexAlign.Center)
        .padding({ left: 15, right: 15 })
      }
      .bindSheet($$this.isShow,this.AddOrEditBuilder(),{
        height:400,
        showClose:false
      })
      .height('100%')
  }
}