<template>
  <!-- #ifdef APP -->
  <scroll-view style="flex: 1">
  <!-- #endif -->
    <view>
      <page-head :title="title"></page-head>
      <view class="uni-padding-wrap uni-common-mt">
        <view class="uni-btn-v uni-common-mt">
          <button type="primary" @click="dbAdd">新增单条数据</button>
          <button type="primary" @click="dbBatchAdd">新增多条数据</button>
          <button type="primary" @click="dbUpdate">更新数据</button>
          <button type="primary" @click="dbGet">where传字符串获取数据</button>
          <button type="primary" @click="dbGetWithCommand">where传对象获取数据</button>
          <button type="primary" @click="dbRemove">删除数据</button>
          <button type="primary" @click="dbLookupInit">初始化联表查询数据</button>
          <button type="primary" @click="dbLookup">联表查询</button>
        </view>
      </view>
    </view>
  <!-- #ifdef APP -->
  </scroll-view>
  <!-- #endif -->
</template>
<script>
  export default {
    data() {
      return {
        title: 'ClientDB',
        addId: '',
        batchAddIds: [] as Array<string>,
        batchAddinserted: 0,
        updateUpdated: 0,
        getData: [] as Array<UTSJSONObject>,
        getWithCommandData: [] as Array<UTSJSONObject>,
        removeDeleted: 0,
        lookupData: [] as Array<UTSJSONObject>,
        isUniTest: false
      }
    },
    onLoad() {
    },
    onUnload() {
      if(this.isUniTest){
        uni.hideToast()
      }
    },
    methods: {
      notify(content : string, title : string) {
        if (!this.isUniTest) {
          uni.showModal({
            title,
            content,
            showCancel: false
          })
        } else {
          uni.showToast({
            title: content
          })
          console.log(title, content)
        }
      },
      dbAdd: function () {
        uni.showLoading({
          title: '加载中...'
        })
        const db = uniCloud.databaseForJQL()
        db.collection('type')
          .add({
            num: 1,
            tag: 'default-tag',
            date: new Date()
          })
          .then(res => {
            uni.hideLoading()
            console.log(res)
            this.addId = res.id
            this.notify(`新增成功，id: ${res.id}`, '提示')
          })
          .catch((err : any | null) => {
            uni.hideLoading()
            const error = err as UniCloudError
            this.notify(error.errMsg, '错误')
          })
      },
      dbBatchAdd() {
        uni.showLoading({
          title: '加载中...'
        })
        const db = uniCloud.databaseForJQL()
        db.collection('type')
          .add([{
            num: 2,
            tag: 'default-tag',
          }, {
            num: 3,
            tag: 'default-tag',
          }])
          .then((res) => {
            uni.hideLoading()
            console.log(res)
            console.log('JSON.stringify(res.inserted)', JSON.stringify(res.inserted))
            this.batchAddIds = res.ids
            this.batchAddinserted = res.inserted
            this.notify(`新增成功条数${res.inserted}, id列表: ${res.ids.join(',')}`, '提示')
          })
          .catch((err : any | null) => {
            uni.hideLoading()
            const error = err as UniCloudError
            this.notify(error.errMsg, '错误')
          })
      },
      dbGet() {
        uni.showLoading({
          title: '加载中...'
        })
        const db = uniCloud.databaseForJQL()
        db.collection('type')
          .where(
            'tag == "default-tag"'
          )
          .field('num, tag')
          .orderBy('num desc')
          .skip(1)
          .limit(2)
          .get()
          .then(res => {
            uni.hideLoading()
            console.log(res)
            this.getData = res.data
            this.notify(`获取成功，取到了${res.data.length}条数据`, '提示')
          })
          .catch((err : any | null) => {
            uni.hideLoading()
            const error = err as UniCloudError
            this.notify(error.errMsg, '错误')
          })
      },
      dbGetWithCommand() {
        uni.showLoading({
          title: '加载中...'
        })
        const db = uniCloud.databaseForJQL()
        db.collection('type')
          .where({
            num: db.command.gt(1)
          })
          .field('num, tag')
          .orderBy('num desc')
          .skip(1)
          .limit(2)
          .get()
          .then(res => {
            uni.hideLoading()
            console.log(res)
            this.getWithCommandData = res.data
            this.notify(`获取成功，取到了${res.data.length}条数据`, '提示')
          })
          .catch((err : any | null) => {
            uni.hideLoading()
            const error = err as UniCloudError
            this.notify(error.errMsg, '错误')
          })
      },
      dbUpdate() {
        uni.showLoading({
          title: '加载中...'
        })
        const db = uniCloud.databaseForJQL()
        db.collection('type')
          .where(
            'tag == "default-tag"'
          )
          .update({
            num: 4
          })
          .then(res => {
            uni.hideLoading()
            console.log(res)
            this.updateUpdated = res.updated
            this.notify(`更新成功，更新了${res.updated}条数据`, '提示')
          })
          .catch((err : any | null) => {
            uni.hideLoading()
            const error = err as UniCloudError
            this.notify(error.errMsg, '错误')
          })
      },
      dbRemove() {
        uni.showLoading({
          title: '加载中...'
        })
        const db = uniCloud.databaseForJQL()
        db.collection('type')
          .where(
            'tag == "default-tag"'
          )
          .remove()
          .then(res => {
            uni.hideLoading()
            console.log(res)
            this.removeDeleted = res.deleted
            this.notify(`删除成功，删掉了${res.deleted}条数据`, '提示')
          })
          .catch((err : any | null) => {
            uni.hideLoading()
            const error = err as UniCloudError
            this.notify(error.errMsg, '错误')
          })
      },
      dbLookupInit() {
        uni.showLoading({
          title: '加载中...'
        })
        const db = uniCloud.databaseForJQL()
        db.collection('local')
          .where('tag == "default-tag"')
          .remove()
          .then(() : Promise<UniCloudDBRemoveResult> => {
            return db.collection('foreign')
              .where('tag == "default-tag"')
              .remove()
          })
          .then(() : Promise<UniCloudDBBatchAddResult> => {
            return db.collection('local')
              .add([{
                id: "local_1",
                name: "local_1_name",
                tag: "default-tag",
                foreign_id: "foreign_1"
              }, {
                id: "local_2",
                name: "local_2_name",
                tag: "default-tag",
                foreign_id: "foreign_2"
              }])
          })
          .then(() : Promise<UniCloudDBBatchAddResult> => {
            return db.collection('foreign')
              .add([{
                id: "foreign_1",
                name: "foreign_1_name",
                tag: "default-tag"
              }, {
                id: "foreign_2",
                name: "foreign_2_name",
                tag: "default-tag"
              }])
          })
          .then((_) : void => {
            uni.hideLoading()
            this.notify('数据初始化成功', '提示')
          })
          .catch((err : any | null) => {
            uni.hideLoading()
            console.error(err)
            const error = err as UniCloudError
            this.notify(error.errMsg, '错误')
          })
      },
      dbLookup() {
        uni.showLoading({
          title: '加载中...'
        })
        const db = uniCloud.databaseForJQL()
        const local = db.collection('local')
          .where('tag == "default-tag"')
          .getTemp()
        const foreign = db.collection('foreign')
          .where('tag == "default-tag"')
          .getTemp()
        db.collection(local, foreign)
          .get()
          .then(res => {
            uni.hideLoading()
            console.log(res)
            this.lookupData = res.data
            this.notify(`联表查询成功，取到了${res.data.length}条数据`, '提示')
          })
          .catch((err : any | null) => {
            uni.hideLoading()
            const error = err as UniCloudError
            this.notify(error.errMsg, '错误')
          })
      }
    }
  }
</script>

<style>
</style>
