import {
  defineComponent,
  h,
  reactive,
  ref,
  watch,
  onMounted,
  toRefs
} from 'vue';
import { ElTable, ElTableColumn, ElPagination, ElLoading } from 'element-plus';
import { debounce } from 'lodash';

export default defineComponent({
  setup(props, { attrs, slots, expose }) {
    const {
      request = () => { },
      pagination: _pagination = {},
      column = [],
      params = {},
      loading = {},
      debug = false,
      border = true,
      ...attr
    } = attrs;

    const pagination = {
      page: 1,
      background: true,
      layout: 'prev,pager,next,jumper,total,sizes',
      ..._pagination
    };

    const log = (type, ...msg) => {
      debug && console.log(`[ DataTable ] ${type} => `, ...msg);
    };
    log('setup', {
      props,
      attrs,
      slots
    });

    const tableRef = ref(null);

    const tableData = ref({
      msg: '加载中...',
      data: [],
      count: 0
    });

    const _params = reactive({
      ...toRefs(params),
      page: 1,
      limit: 10
    });

    // 请求数据
    const fetchData = debounce(async v => {
      const _loading = ElLoading.service({
        target: tableRef.value,
        ...loading
      });
      // setTimeout(async () => {
      log('fetchData', _params, params);
      try {
        const { code, data, count, msg } = await request(_params);

        if (code == 0) {
          tableData.value.data = data;
          tableData.value.count = count;
          if (count === 0) {
            tableData.value.msg = '暂无数据';
          }
        } else {
          tableData.value.msg = msg;
          tableData.value.data.length = 0;
          tableData.value.count = 0;
        }
      } catch (error) {
        tableData.value.msg = error.message || '服务器返回异常';
      } finally {
        _loading.close();
      }
      // });
    }, 1000);

    expose({
      reload: fetchData
    });

    // watch(attrs.params, (v) => {
    //   log("watch attr.params", v);
    // });

    // watch(params, (v) => {
    //   log("watch params", v);
    //   fetchData();
    // });
    watch(_params, v => {
      log('watch _params', v);
      fetchData();
    });
    // watch(
    //   params,
    //   (v) => {
    //     log("watch deep params", v);
    //     fetchData();
    //   },
    //   {
    //     deep: true,
    //   }
    // );
    // watch(
    //   _params,
    //   (v) => {
    //     log("watch deep _params", v);
    //     fetchData();
    //   },
    //   {
    //     deep: true,
    //   }
    // );

    // onActivated(() => {
    //   log("onActivated");
    // });

    onMounted(() => {
      log('onMounted');
      fetchData();
    });
    return () => (
      <div ref={tableRef}>
        <ElTable
          {...attr}
          border={border}
          data={tableData.value.data}
          emptyText={tableData.value.msg}
        >
          {column.map(v => {
            const { prop } = v;
            const slotsProp = slots[prop];
            let temp = null;
            if (slotsProp) {
              temp = {
                default: slotsProp
              };
            }
            return h(ElTableColumn, v, temp);
          })}
        </ElTable>
        {_pagination === false ? (
          ''
        ) : (
          <ElPagination
            {...pagination}
            onCurrentChange={val => (_params.page = val)}
            onSizeChange={val => (_params.limit = val)}
            total={tableData.value.count}
            pageSize={_params.limit}
          ></ElPagination>
        )}
      </div>
    );
  }
});
