<template>
  <BasicTable
    ref="tableRef"
    @register="registerTable"
    rowKey="id"
    @selectionChange="selectionChange"
    :rowSelection="{ type: 'radio' }"
    @rowClick="rowClick"
    :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" @saveData="saveData" />
</template>
<script lang="ts">
  import { defineComponent, ref, unref, watch } from 'vue';
  import Popup from './popup.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { getFormConfig, columns } from './data';
  import { getTypeList, addType } from '/@/api/sys/money';
  import moment from 'moment';
  import { BasicTable, useTable, EditRecordRow, TableActionType } from '/@/components/Table';
  const props = {
    value: { type: Object, default: '' },
    placeholder: { type: String, default: '' },
    type: { type: Number, default: 1 },
  };
  export default defineComponent({
    name: 'Type',
    components: { BasicTable, Popup },
    props,
    emits: ['select'],
    setup(props, { emit }) {
      const { createMessage } = useMessage();
      const { success /*, error*/ } = createMessage;
      const tableRef = ref<Nullable<TableActionType>>(null);
      const [registerTable] = useTable({
        columns: columns,
        // clickToRowSelect: false, // 点击行不勾选
        api: getTypeList,
        useSearchForm: true,
        showTableSetting: true,
        tableSetting: {
          redo: false,
          size: false,
        },
        beforeFetch: beforeFetch,
        afterFetch: afterFetch,
        formConfig: getFormConfig(),
        maxHeight: 190,
        showIndexColumn: false,
        bordered: true,
      });
      const [addRegister, { openModal: openPopup }] = useModal();
      function getTableAction() {
        // 获取组件
        const tableAction = unref(tableRef);
        if (!tableAction) {
          throw new Error('tableAction is null');
        }
        return tableAction;
      }

      function beforeFetch(params) {
        console.log(`props.type2`, props.type);
        params.inOut = props.type;
        for (let k in params) {
          if (k !== 'page' && k !== 'pageSize' && k !== 'field' && k !== 'order') {
            if (params[k] === '') {
              delete params[k];
            } else {
              if (!params.filter) {
                params.filter = {};
              }
              if (params.birthday) {
                params.birthday = moment(params.birthday).format('YYYY-MM-DD');
              } else {
                delete params.birthday;
              }
              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 afterFetch(result) {
        console.log(`result`, result);
        // tableData.result = result;
      }

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

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

      function handleAdd() {
        // 开启弹窗
        openPopup(true, {});
      }

      async function saveData(params: any) {
        const data = params.data;
        const closeModel = params.closeModal;
        console.log(`data`, data);
        await addType(data).then((res) => {
          console.log(res);
          getTableAction().reload();
          closeModel();
          success('创建成功!');
        });
      }

      watch(
        () => props.type,
        () => {
          getTableAction().reload(); // 交易类型变化刷新表格
        }
      );

      return {
        tableRef,
        registerTable,
        handleAdd,
        getTableAction,
        selectionChange,
        rowClick,
        addRegister,
        saveData,
      };
    },
  });
</script>
<style>
  .ant-calendar-picker {
    width: 100%;
  }

  /* @media (max-width: 639px) {
    .sys-container .vben-basic-table-header__toolbar > * {
      padding: 6px !important;
      margin-right: 3px;
      font-size: 12px !important;
    }

    .sys-container .vben-basic-table .ant-table-wrapper {
      padding: 3px;
    }
  } */
  .vben-basic-table-header__toolbar {
    justify-content: space-between;
  }

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