import dayjs from 'dayjs'
import { noteDB } from '../database/NoteDB'
import { DeleteDialog } from '../dialog/DeleteDialog'
import { NoteDBInfo } from '../models/Note'
import { systemShare } from '@kit.ShareKit'
import { uniformTypeDescriptor } from '@kit.ArkData'
import { promptAction } from '@kit.ArkUI'
import common from '@ohos.app.ability.common'


@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()
  // }
  deleteId:number=0

  dialogController: CustomDialogController = new CustomDialogController({
    builder: DeleteDialog({
      delete:(isDelete:boolean)=>{
        if(isDelete){
          let ids=[] as number[]
          ids.push(this.deleteId)
          this.deleteData(ids)
          this.deleteId=0

        }else{

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




  private colors:string[]=[
    'rgba(254, 222, 155, 1)',
    'rgba(255, 191, 220,1)',
    'rgba(211, 227, 253,1)'
  ]

  private heights:number[]=[
    100,
    150,
    130
  ]

  // 分享


  shareData() {
    try {
      // 构造ShareData，需配置一条有效数据信息
      const data = new systemShare.SharedData({
        utd: uniformTypeDescriptor.UniformDataType.PLAIN_TEXT,
        title: this.title,
        content: this.content
      })
      const controller = new systemShare.ShareController(data)
      const context = getContext() as common.UIAbilityContext;
      // 进行分享面板显示
      controller.show(context, {
        previewMode: systemShare.SharePreviewMode.DETAIL,
        selectionMode: systemShare.SelectionMode.SINGLE
      })
    } catch (error) {
      promptAction.showToast({ message: '当前设备不支持分享' })
    }
  }

  // 获取列表
  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(16)
            .fontColor('rgba(117, 104, 96, 1)')

          Text('保存')
            .width(77)
            .height(30)
            .borderRadius(6)
            .textAlign(TextAlign.Center)
            .fontColor('rgba(255, 255, 255, 1)')
            .border({ width: 1, color: 'rgba(117, 104, 96, 1)' })
            .fontSize(12)
            .backgroundColor('rgba(117, 104, 96, 1)')
            .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('rgba(254, 222, 155, 1)')
          .border({ width: 1, color: Color.Black, radius: 6 })
          .padding({ left: 10 })
          .onChange((text) => {
            if(text.length>6){
              promptAction.showToast({
                message:"标题不能超过6个字"
              })
              this.title=text.slice(0,6)
              return
            }
            this.title = text
          })
        //
        Text('内容')
          .fontSize(14)
          .fontColor('rgba(117, 104, 96, 1)')
          .width('100%')
        TextArea({ placeholder: '请输入笔记内容', text: this.content })
          .backgroundColor('rgba(254, 222, 155, 1)')
          .border({ width: 1, color: Color.Black, radius: 6 })
          .layoutWeight(1)
          .padding(10)
          .onChange((text) => {
            this.content = text
          })
      }
      .padding({ bottom: 160 })

      if (this.noteId) {
      // 底部按钮
      Row({ space: 10 }) {
        Button('分享')
          .type(ButtonType.Normal)
          .backgroundColor('rgba(254, 222, 155, 1)')
          .borderRadius(10)
          .layoutWeight(1)
          .onClick(() => {
            this.shareData()
          })
        // }

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

  build() {
      Stack({ alignContent: Alignment.BottomEnd }) {
        if (this.list.length!=0) {
          Column() {
            WaterFlow() {
              ForEach(this.list, (item: NoteDBInfo,index:number) => {
                FlowItem() {
                  Column({space:30}) {
                    Column() {
                      Row() {
                        Text(item.title)
                          .fontSize(16)
                          .fontColor(Color.Black)

                          Image($r('app.media.delete'))
                            .width(20)
                            .aspectRatio(1)
                            .onClick(()=>{
                              this.dialogController.open()
                              this.deleteId=item.id as number

                              // let ids=[] as number[]
                              // ids.push(item.id as number)
                              // this.deleteData(ids)

                            })

                      }.width('100%')
                      .justifyContent(FlexAlign.SpaceBetween)

                      Text(item.content)
                        .fontSize(12)
                        .fontColor(Color.Gray)
                        .textIndent(10)
                        .maxLines(2)
                        // 超长文本使用省略号代替
                        .textOverflow({overflow: TextOverflow.Ellipsis})

                      Text(dayjs(item.date_added)
                        .format('YYYY年MM月DD日'))
                        .fontSize(12)
                        .fontColor(Color.Gray)
                        .lineHeight(25)
                    }
                    .height('100%')
                    .justifyContent(FlexAlign.SpaceAround)
                    .alignItems(HorizontalAlign.Start)

                  }
                  // .width('100%')
                  .borderRadius(20)
                  .width('50%')
                  .height(this.heights[index%3])
                  .backgroundColor(this.colors[index%3])
                  .justifyContent(FlexAlign.SpaceBetween)
                  .padding({ left: 15, right: 15,top:10 })
                  .shadow({
                    // 模糊半径
                    radius: 10,
                    // 阴影类型
                    type: ShadowType.COLOR,
                    // 阴影颜色
                    color: 'rgba(181, 228, 255,0.5)',
                    // X 轴偏移
                    offsetX: -3,
                    // Y 轴偏移
                    offsetY: 10,
                    // 是否内部填充，值为布尔型，默认为flase
                    fill: false
                  })
                  .onClick(() => {
                    this.isShow=true
                    this.noteId=item.id as number
                    this.title=item.title
                    this.content=item.content
                  })
                }
                .transition({ type: TransitionType.Delete, opacity: 0 })
                // .swipeAction({
                //   end: {
                //     builder:this.swipeActionEnd(item.id),
                //   },
                //   edgeEffect: SwipeEdgeEffect.None
                // })
              })
              // 底部占位
              FlowItem()
                .height(126)
            }
            // 每行之间的分界线
            // .divider({
            //   strokeWidth: 1,
            //   color: Color.Pink,
            //   startMargin: 15,
            //   endMargin: 15
            // })
            .width('100%')
            .height('100%')
            .columnsTemplate('1fr 1fr')
            .columnsGap(8)
            .rowsGap(10)
          }
          .height('100%')
        } else {
         //还没有笔记
          Column(){


            Text('去添加')
              .padding({left:16,right:16,top:10,bottom:10})
              .backgroundColor('#d1fd45')
              .borderRadius(15)
              .onClick(()=>{
                this.isShow=true
                this.noteId=null
                this.title=""
                this.content=""

              })

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

        }

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