<template>
  <div class="page">
    <search v-model="searchKeyWord"
            cancel-text="确定"
            :auto-fixed="false"
            @on-cancel="searchPassport"
            @on-submit="searchPassport">
      <div slot="left" class="qrcode-btn" @click.stop="scanQrcode"></div>
    </search>
    <scroller :lockX="true" :use-pulldown="true" :use-pullup="true"
      height="-44"
      :pulldown-config="{downContent: '下拉刷新', upContent: '释放后更新'}"
      :pullup-config="{upContent: '上拉加载更多', downContent: '释放后加载'}"
      @on-pullup-loading="loadMoreData"
      @on-pulldown-loading="refreshData"
      ref="myApplyList">
      <div class="content-area">
        <item-passport-item v-for="item in applyList" :key="item.releaseNumber"
                            user-type="staff"
                            :item="item" :translation-dict="itemTypesDict"
                            @on-passport-clic="onPassAction"
                            @on-pass-action="onPassAction"
                            @on-query-qrcode="onQueryQrCode"></item-passport-item>
        <div class="common-content-no-more-data-tip" v-if="!hasMoreData">{{noMoreDataTips}}</div>
      </div>
    </scroller>
    <loading v-model="loading" text="加载中"></loading>

    <div v-transfer-dom>
      <popup v-model="qrcodePopup" height="100%" class="qr-code-bg">
        <div class="popup qr-code-bg" @click.stop="hideQrcode">
          <qrcode :value="currQrcodeValue" type="img"></qrcode>
        </div>
      </popup>
    </div>
  </div>
</template>

<script>
import ItemPassportItem from './../../components/itemPassport/itemPassportItem'
import roomLogic from './logic/bindRoomLogic.js'
import {
  getBaseData,
  queryItemPassportList,
  cancelItemPassportApply,
  queryItemPassprotQrcode
} from './../../service/itemPassportService.js'
export default {
  components: {
    ItemPassportItem,
  },
  name: 'MyItemPassportApplyList',

  data () {
    return {
      searchKeyWord: '',
      roomUtil: new roomLogic(),
      itemTypesDict: null, // 放行条物品类型字典
      defaultRoom: null, // 默认路址
      applyList: [],
      size: 10, // 每页数量
      page: 1, // 页码
      total: 0,
      hasMoreData: true,
      noMoreDataTips: '已无更多数据',
      loading: false,
      qrcodePopup: false,
      currQrcodeValue: '',
    }
  },

  created () {
    this.util.title("物品放行");
    try {
      EbeiPlugins.setBackButtonHidden(false);
    }
    catch (e) {

    }
    this.refreshData()
    // this.initData()
  },

  methods: {
    /**
     * 1.查询物品放行字典
     * 2.查询业主绑定的路址
     * 3.根据默认路址业主id查询放行条列表
     */
    initData () {
      this.loading = true

      let that = this
      getBaseData({dictCode: 'decPassType'}).then((res) => {
        if (res.status === '200') {
          that.itemTypesDict = res.data
        }
        return that.roomUtil.makeRoomQueryParams()
      }).then((res) => {
        that.util.debugLog(JSON.stringify(res))
        return that.roomUtil.queryBindRoomList(res)
      }).then((rooms) => {
        that.loading = false
        if (rooms.length === 0) {
          that.showAuthAlert()
        } else {
          let defaultRooms = rooms.filter(room => room.isDefault.toString() === '1')
          if (defaultRooms.length === 0) {
            that.showTips('请先设置默认路址')
          } else {
            that.defaultRoom = defaultRooms[0]

            that.page = 1
            that.hasMoreData = true
            let params = that.makeListQueryParams()
            return queryItemPassportList(params)
          }
        }
      }).then((res) => {
        if (res.status === "200" || res.status === "10200") {
          let data = res.data
          that.total = data.total
          that.applyList = data.records
          that.checkDataList()
        } else {
          that.showTips(res.message)
        }
        that.loading = false
      }).catch((err) => {
        that.util.debugLog(err)
        that.loading = false
        that.showTips('网络错误')
      })
    },

    refreshData () {
      this.loading = true

      this.page = 1

      let params = this.makeListQueryParams()
      let that = this
      queryItemPassportList(params).then((res) => {
        if (res.status === "200" || res.status === "10200") {
          let data = res.data
          that.total = data.total
          that.applyList = data.records
          that.checkDataList()
        } else {
          that.showTips(res.message)
        }
        that.loading = false
        that.donePulldown()
      }).catch((err) => {
        that.util.debugLog(err)
        that.loading = false
        that.donePulldown()
        that.showTips('网络错误')
      })
    },

    loadMoreData () {
      this.page += 1

      let that = this
      let params = this.makeListQueryParams()
      queryItemPassportList(params).then((res) => {
        if (res.status === "200" || res.status === "10200") {
          let data = res.data
          that.total = data.total
          that.applyList = that.applyList.concat(data.records)
          that.checkDataList()
        } else {
          that.showTips(res.message)
        }
        that.donePullup()
      }).catch((err) => {
        that.util.debugLog(err)
        that.donePullup()
        that.showTips('网络错误')
      })
    },

    onPassAction(item) {
      try {
        let number = item.releaseNumber
        this.$router.push({
          path: '/itemPassportDetail',
          query: {id: number}
        })
      } catch (error) {
        this.showTips('放行条信息错误')
      }
    },

    onQueryQrCode (item) {
      this.util.debugLog('打印放行条')
      try {
        this.currQrcodeValue = item.releaseNumber
        this.qrcodePopup = true
      } catch (error) {
        this.showTips('放行条信息错误')
      }
    },

    hideQrcode () {
      this.qrcodePopup = false
    },

    makeListQueryParams () {
      let params = {
        Index: this.page.toString(),
        size: this.size.toString(),
        projectId: localStorage.getItem('projectId')
        // submitter: localStorage.getItem('memberId')
        // ownerId: this.defaultRoom.ownerId
      }
      return params
    },

    checkDataList () {
      if (this.applyList.length >= this.total) {
        this.hasMoreData = false
      } else {
        this.hasMoreData = true
      }
    },

    searchPassport () {
      this.util.debugLog('搜索')
    },

    scanQrcode () {
      this.util.debugLog('扫一扫')
      let that = this
      EbeiPlugins.scanQRCode((string) => {
        that.goToDetail(string)
      }, () => {
        that.showTips('扫码失败')
      })
    },

    goToDetail (releaseNumber) {
      try {
        let number = releaseNumber
        this.$router.push({
          path: '/itemPassportDetail',
          query: {id: number}
        })
      } catch (error) {
        this.showTips('放行条信息错误')
      }
    },

    donePulldown() {
      this.$refs.myApplyList.donePulldown()
      this.$refs.myApplyList.reset({ top: 0 });
    },

    donePullup() {
      this.$refs.myApplyList.donePullup()
      this.$refs.myApplyList.reset()
    },

    showTips (tip) {
      this.$vux.toast.show({
        type: 'text',
        text: tip,
        position: 'bottom'
      })
    },

    showAuthAlert () {
      this.$vux.confirm.show({
        title: '提示',
        content: '业主专享功能，业主请移步认证',
        confirmText: '去认证',
        cancelText: '暂不认证',
        onConfirm () {
          //弹窗显示时触发
          location.href = "#/HouseAuthAddAddress"; //跳转到认证地址页面
        },
        onCancel () {
          //弹窗关闭时触发
          history.back(-1);
        }
      })
    },
  },

  watch: {
    hasMoreData: function (newVal) {
      if (newVal) {
        this.$refs.myApplyList.enablePullup()
      } else {
        this.$refs.myApplyList.disablePullup()
      }
    },

    searchKeyWord: function (newVal) {
      this.util.debugLog(newVal)
    },
  }
}
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100%;
  background-color: #f9f9f9;
}

.content-area {
  width: 100%;
  min-height: calc(100vh - 44px);
}

.popup {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  width:100%;
  height:100%;
}

.qr-code-bg {
  background-color: rgba($color: #000000, $alpha: 0.3)
}

.qrcode-btn {
  height: 28px;
  width: 28px;
  margin-right: 10px;
  background: url('./../../assets/images/DecorationPassport/icon_scan.png') center no-repeat;
  background-size: 100%;
}
</style>
