<!-- @format -->

<template>
  <div :key="'table_' + $route.name">
    <page-title :title="getTitle" v-if="showTitle" />
    <ns-table ref="nsTableRef" v-bind="getBindValue">
      <template #[item]="data" v-for="item in Object.keys($slots)" :key="item">
        <slot :name="item" v-bind="data"> </slot>
      </template>
    </ns-table>
  </div>
</template>

<script lang="ts">
  import { computed, defineComponent, unref, ref } from 'vue';
  import { tableProps } from '/nerv-lib/component/table/props';
  import { PropTypes } from '/nerv-lib/util/type';
  import { cloneDeep, isArray, isUndefined } from 'lodash-es';
  import { useRoute } from 'vue-router';

  export default defineComponent({
    name: 'NsViewListTable',
    props: {
      ...tableProps,
      title: PropTypes.string,
      tableTitle: PropTypes.func,
      showTitle: {
        type: Boolean,
        default: true,
      },
    },
    setup(props, { attrs }) {
      const nsTableRef = ref();
      const route = useRoute();

      const formatFilterSearch = (key, filter) => {
        let selector = filter.filter((item) => {
          return item.name.startsWith(key);
        });
        let selectorValue = selector.map((item) => {
          item.name = item.name.replace(key, '');
          console.log('item.value', item.value);
          if (item.name) return `${item.name}=${item.value.join('|')}`;
          return `${item.value.join('|')}`;
        });
        return selectorValue.join(',');
      };

      const getFormConfig = computed(() => {
        const formConfig = cloneDeep(props.formConfig);

        if (formConfig) {
          if (isUndefined(formConfig.showAction)) {
            formConfig.showAction = false;
          }
          if (!isArray(formConfig.schemas)) {
            formConfig.schemas = [];
          }
          formConfig['formLayout'] = 'flex';
          //过滤标签搜索组件
          if (formConfig.keyFilter === true) {
            formConfig.schemas.push(
              {
                field: 'selector',
                component: 'NsInputText',
                show: false,
              },
              {
                field: 'labels',
                component: 'NsInputText',
                show: false,
              },
              {
                field: 'search',
                component: 'NsInputText',
                show: false,
              },
            );
            formConfig.schemas.push({
              field: 'filter',
              label: '关键字',
              component: 'NsInputFilter',
              rules: [],
              componentProps: {
                maxlength: 50,
                allowClear: true,
                api: formConfig.api,
                terraceType:
                  typeof formConfig.terraceType != 'undefined'
                    ? formConfig.terraceType
                    : 'dataSource',
                isNeedHttpGet:
                  typeof formConfig.isNeedHttpGet != 'undefined' ? formConfig.isNeedHttpGet : true,
                filterList: formConfig.filterList ? formConfig.filterList : [],
                type: typeof formConfig.type != 'undefined' ? formConfig.type : '',
                defaultFilterList:
                  typeof formConfig.defaultFilterList != 'undefined'
                    ? formConfig.defaultFilterList
                    : false,
                onSearch: () => {
                  let filter = unref(nsTableRef)?.formElRef.model.filter;
                  if (!filter) {
                    let list = ['selector', 'labels', 'search'];
                    list.map((elem) => {
                      unref(nsTableRef).formElRef.setFormModel(elem, null);
                    });
                    unref(nsTableRef)?.formElRef?.triggerSubmit();
                    return;
                  }
                  filter = JSON.parse(decodeURIComponent(filter));
                  let selectorValue = formatFilterSearch('selector=', filter);
                  let labelValue = formatFilterSearch('labels=', filter);
                  let searchValue = formatFilterSearch('search=', filter);
                  unref(nsTableRef).formElRef.model.selector = selectorValue || null;
                  unref(nsTableRef).formElRef.model.labels = labelValue || null;
                  unref(nsTableRef).formElRef.model.search = searchValue || null;
                  unref(nsTableRef).formElRef.model.filter = null;
                  console.log('www',unref(nsTableRef))
                  unref(nsTableRef)?.formElRef?.triggerSubmit();
                },
                onChange: (text) => {},
                placeholder: '请输入关键字',
              },
            });
          } else if (formConfig.keySearch !== false) {
            formConfig.schemas.push({
              field: 'search',
              label: '关键字',
              component: 'NsInputSearch',
              rules: [
                {
                  message: '请输入关键字',
                  trigger: 'change',
                },
              ],
              componentProps: {
                maxlength: 50,
                onSearch: () => {
                  unref(nsTableRef)?.formElRef?.triggerSubmit();
                },
                onKeydown: (event: KeyboardEvent) => {
                  //fix 单个input回车会提交表单 造成重复提交
                  if (event.key === 'Enter' || event.code === 'Enter') {
                    event.preventDefault();
                  }
                },
                placeholder: '请输入关键字',
              },
            });
          }
        }
        return formConfig;
      });
      const getBindValue = computed(() => ({
        // scroll: { x: 1000 },
        ...attrs,
        ...props,
        enableTableSession: true,
        formLayout: 'flex',
        title: null,
        formConfig: getFormConfig.value,
      }));
      const getTitle = computed(() => {
        const {
          params: { pageTitle },
        } = route;
        if (pageTitle) return pageTitle;
        const { title } = props;
        if (title) return title;
      });
      return { getBindValue, nsTableRef, getTitle };
    },

    methods: {
      onBack() {
        this.$router.go(-1);
      },
    },
  });
</script>

<style lang="less" scoped>
  :deep(.ns-form-item) {
    min-width: 220px !important;
  }

  :deep(.ns-operate-expand) {
    display: inline-block;
    padding: 4px 2px !important;
    border: unset !important;
  }

  :deep(.ns-table) {
    position: relative;
    .ns-table-main {
      padding: 0 24px;
    }
    .ns-table-search {
      padding: 18px 24px 0 24px;
    }
    //tableList组件
    .ns-table-header {
      width: auto;
      min-width: 100px;
      user-select: none;
      margin-bottom: 12px;
      margin-top: 18px;
      text-align: left;
      position: absolute !important;
      left: 0;
      top: -80px;

      .ant-btn {
        margin-left: 0;
        margin-right: 6px;
      }
    }
    .ns-form-item label {
      display: none;
    }
    &.ns-table-no-search {
      .ns-table-search {
        display: none;
      }

      .ns-table-header {
        position: relative !important;
        top: 0;
      }
    }
  }

  :deep(.ns-line) {
    display: none;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(
          .ant-table-row-expand-icon-cell
        ):not([colspan])::before
    ) {
    display: none;
  }
</style>
