import { get } from './request'

/**
 * Creates a mixin for paginated list pages.
 *
 * Eliminates the repeated data/computed/methods boilerplate for:
 *   - records[], total, page, pageSize, totalPages
 *   - loadList(), onPage(), onSearch()
 *
 * Usage:
 *   import { listMixin } from '../../utils/useList'
 *
 *   export default {
 *     mixins: [listMixin('/api/v1/admin/devices')],
 *     methods: {
 *       reload() {
 *         this.loadList({ keyword: this.keyword })
 *       }
 *     }
 *   }
 *
 * @param {string} apiPath - API endpoint path (passed to get())
 * @param {object} opts
 * @param {number} [opts.pageSize=20] - Items per page
 */
export function listMixin(apiPath, opts = {}) {
  return {
    data() {
      return {
        records: [],
        total: 0,
        page: 1,
        pageSize: opts.pageSize || 20
      }
    },
    computed: {
      totalPages() {
        return Math.ceil(this.total / this.pageSize) || 1
      }
    },
    methods: {
      async loadList(extraParams = {}) {
        try {
          var params = { page: this.page, page_size: this.pageSize }
          // Merge extra params, dropping falsy values to keep request clean
          var keys = Object.keys(extraParams)
          for (var i = 0; i < keys.length; i++) {
            var k = keys[i]
            if (extraParams[k] !== '' && extraParams[k] != null) {
              params[k] = extraParams[k]
            }
          }
          var data = await get(apiPath, params)
          this.records = data.records || []
          this.total = data.total || 0
          this.onListLoaded(data)
        } catch (e) {
          uni.showToast({ title: '加载失败', icon: 'none' })
        }
      },
      /**
       * Override in page to handle extra response data (e.g. stats).
       */
      onListLoaded(_data) {},
      onPage(p) {
        this.page = p
        this.reload()
      },
      onSearch() {
        this.page = 1
        this.reload()
      },
      /**
       * Override in page to call loadList() with current filters.
       */
      reload() {
        this.loadList()
      }
    }
  }
}
