import BaseSearch from '@/components/McSearch/index.vue'
import BaseTable from '@/components/McTable/index.vue'


export function FormTableMixin(service, defaultProps = {}) {
  const pagination = defaultProps && {
    current: 1,
    size: 10,
    total: 0,
    ...defaultProps,
  }

  return {
    components: {
      BaseSearch,
      BaseTable,
    },
    data() {
      return {
        form: {
          value: null,
          onSubmit: () => {
            this.table.pagination.pageNo = 1
            this.getList()
          },
          onInput: val => {
            this.form.value = val
          },
        },
        table: {
          data: [],
          pagination,
          loading: false,
          onChange: pagination => {
            Object.assign(this.table.pagination, pagination)
            this.getList()
          },
        },
      }
    },
    mounted() {

      // let parent = this.$options.parent
      // // 定位到第一个 keep-alive 父组件
      // while (parent && parent.$options._componentTag !== 'keep-alive') {
      //   parent = parent.$parent
      // }
      // if (!parent) {
      //   this.getList()
      // }

      this.getList()

    },
    activated() {
      // 由于 keep-alive 组件的缓存机制，这里需要在 activated 生命周期中
      console.log('activated');
      this.getList()
    },
    computed: {
      params() {
        const { pagination } = this.table
        return {
          ...this.form.value,
          current: pagination.current,
          size: pagination.size,
        }
      },
    },
    methods: {
      async getList() {
        this.table.loading = true
        try {
          console.log(this.params,'请求参数')
          const { data = [], total = 0 } = (await service?.call(this, this.params, this)) || {}
          this.table.loading = false
          this.table.data = data

          if (this.table.pagination) {
            this.table.pagination.total = total * 1
          }

        } catch (error) {
          console.error(error);
          this.table.loading = false
        }

      },
    },
  }

}
