<template>
  <BasicTable
    ref="tableRef"
    @register="registerTable"
    rowKey="id"
    @selectionChange="selectionChange"
    :rowSelection="{ type: 'radio' }"
    @rowClick="rowClick"
    @rowDbClick="handleEdit"
    :canResize="true"
    :pagination="{
      pageSize: 10,
      defaultPageSize: 10,
      showSizeChanger: false,
    }"
  >
    <template #toolbar>
      <div class="tool-btn-wrap">
        <a-button type="primary" @click="handleAdd"> 添加 </a-button>
      </div>
    </template>
    <template #form-custom> custom-slot </template>
  </BasicTable>
  <Popup @register="addRegister" :popupData="popupData" @saveData="saveData" />
</template>
<script lang="ts">
  import { defineComponent, reactive, ref, toRefs, unref } from 'vue';
  import Popup from './popup.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { getFormConfig, columns } from './data';
  import moment from 'moment';
  import { getMemberList, addMember } from '/@/api/sys/member';
  import { BasicTable, useTable, EditRecordRow, TableActionType } from '/@/components/Table';

  interface PopupData {
    title: string;
  }

  interface Btn {
    disable_btn: boolean;
  }

  export default defineComponent({
    name: 'Member',
    components: { BasicTable, Popup },
    emits: ['select'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const { success /*, error*/ } = createMessage;
      const tableRef = ref<Nullable<TableActionType>>(null);
      const popupData = reactive<PopupData>({
        title: '添加',
      });
      const btn = reactive<Btn>({
        disable_btn: true,
      });
      const [registerTable] = useTable({
        columns: columns,
        // clickToRowSelect: false, // 点击行不勾选
        api: getMemberList,
        useSearchForm: true,
        beforeFetch: beforeFetch,
        showTableSetting: true,
        tableSetting: {
          redo: false,
          size: false,
        },
        formConfig: getFormConfig(),
        maxHeight: 190,
        showIndexColumn: false,
        bordered: true,
      });
      const [register, { openModal }] = useModal();
      const [addRegister, { openModal: openPopup }] = useModal();
      function getTableAction() {
        // 获取组件
        const tableAction = unref(tableRef);
        if (!tableAction) {
          throw new Error('tableAction is null');
        }
        return tableAction;
      }
      // 请求之前处理参数
      function beforeFetch(params) {
        for (let k in params) {
          if (k !== 'page' && k !== 'pageSize' && k !== 'field' && k !== 'order' && k !== 'name') {
            if (params[k] === '') {
              delete params[k];
            } else {
              if (!params.filter) {
                params.filter = {};
              }
              if (params.jointime) {
                params.jointime = moment(params.jointime).format('YYYY-MM-DD');
              } else {
                delete params.jointime;
              }
              params.filter[k] = params[k];
              delete params[k];
            }
          }
        }
        params.filter = JSON.stringify(params.filter);
        params.offset = params.page;
        params.limit = params.pageSize;
        delete params.page;
        delete params.pageSize;
      }

      function handleAdd() {
        popupData.title = '添加会员';
        openPopup(true, { family: [] });
      }

      function selectionChange(evt) {
        emit('select', evt.rows[0]);
      }

      function rowClick(record: EditRecordRow) {
        emit('select', record);
      }

      async function saveData(params: any) {
        const data = params.data;
        const closeModel = params.closeModal;
        console.log(`data`, data);
        await addMember(data).then((res) => {
          console.log(res);
          getTableAction().reload();
          closeModel();
          success('创建成功!');
        });
      }
      return {
        popupData,
        tableRef,
        registerTable,
        handleAdd,
        getTableAction,
        rowClick,
        selectionChange,
        addRegister,
        saveData,
        openModal,
        register,
        ...toRefs(btn),
      };
    },
  });
</script>
<style>
  .ant-calendar-picker {
    width: 100%;
  }

  .vben-basic-table-header__toolbar {
    justify-content: space-between;
  }

  .tool-btn-wrap button {
    margin-right: 5px;
  }
</style>
