<template>
  <CollapseContainer
    class="sys-container"
    title="账目管理"
    :canExpan="false"
    helpMessage="账目管理"
  >
    <BasicTable
      ref="tableRef"
      @register="registerTable"
      rowKey="id"
      @selectionChange="selectionChange"
      @rowClick="rowClick"
      @rowDbClick="handleEdit"
      showTableSetting
      :canResize="true"
      :pagination="{
        pageSize: 10,
        defaultPageSize: 10,
        showSizeChanger: false,
      }"
    >
      <template #toolbar>
        <div class="tool-btn-wrap">
          <a-button type="primary" @click="addRole"> 添加 </a-button>
          <a-button @click="openModal"> 导出 </a-button>
        </div>
      </template>
      <template #form-custom> custom-slot </template>
      <template #action="{ record }">
        <TableAction :actions="createActions(record)" stopButtonPropagation />
      </template>
    </BasicTable>
    <ExpExcelModel @register="register" @success="defaultHeader" />
    <Popup @register="addRegister" :popupData="popupData" @saveData="saveData" />
  </CollapseContainer>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref, toRefs, unref } from 'vue';
  import { CollapseContainer } from '/@/components/Container/index';
  import Popup from './popup.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { jsonToSheetXlsx, ExpExcelModel, ExportModalResult } from '/@/components/Excel';
  import { getFormConfig, columns } from './data';
  import moment from 'moment';
  import { getBillList, addBill, getBill, editBill } from '/@/api/sys/money';
  import {
    BasicTable,
    useTable,
    TableAction,
    ActionItem,
    EditRecordRow,
    TableActionType,
  } from '/@/components/Table';

  interface PopupData {
    title: string;
  }

  interface Btn {
    disable_btn: boolean;
  }

  export default defineComponent({
    name: 'Bill',
    components: { CollapseContainer, BasicTable, TableAction, Popup, ExpExcelModel },
    setup() {
      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({
        rowSelection: { type: 'checkbox' },
        columns: columns,
        // clickToRowSelect: false, // 点击行不勾选
        api: getBillList,
        useSearchForm: true,
        tableSetting: {
          redo: false,
          size: false,
        },
        beforeFetch: beforeFetch,
        afterFetch: afterFetch,
        formConfig: getFormConfig(),
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
        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 !== 'type' &&
            k !== 'typename' &&
            k !== 'account' &&
            k !== 'member'
          ) {
            if (params[k] === '') {
              delete params[k];
            } else {
              if (!params.filter) {
                params.filter = {};
              }
              if (params.tradetime) {
                params.tradetime = moment(params.tradetime).format('YYYY-MM-DD');
              } else {
                delete params.tradetime;
              }
              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 addRole() {
        popupData.title = '添加';
        openPopup(true, { id: 0, year: '' });
      }

      async function handleEdit(record: EditRecordRow) {
        popupData.title = '编辑';
        getBill({ id: record['bill.id'] }).then((res) => {
          const data = res.row;
          console.log(`edit data`, data);
          openPopup(true, data);
        });
      }

      function selectionChange() {
        const keys = getTableAction().getSelectRowKeys();
        if (keys.length) {
          btn.disable_btn = false;
        } else {
          btn.disable_btn = true;
        }
      }
      function rowClick() {
        const keys = getTableAction().getSelectRowKeys();
        if (keys.length) {
          btn.disable_btn = false;
        } else {
          btn.disable_btn = true;
        }
      }

      async function saveData(params: any) {
        const data = params.data;
        const closeModel = params.closeModal;
        console.log(`save----------data`, data);
        if (!data.id) {
          await addBill(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
            success('创建成功!');
          });
          console.log('----------add---');
        } else {
          await editBill(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
            success('修改成功!');
          });
          console.log('----------edit---');
        }
      }

      function defaultHeader({ filename, bookType }: ExportModalResult) {
        // 默认Object.keys(data[0])作为header
        const jsondata = getTableAction().getDataSource();
        const excelData: object[] = [];
        const options = ['会费', '收入', '支出', '内部转账'];
        jsondata.map((item, i) => {
          let data = {
            No: 0,
            id: '',
            type: '',
            typename: '',
            account: '',
            money: '',
            member: '',
            isCode: '',
            remark: '',
            tradetime: '',
          };
          data.No = i + 1;
          data.id = item.id;
          data.type = options[item.type];
          data.typename = item.typename;
          data.account = item.account;
          data.money = item.money.toFixed(2);
          data.member = item.member;
          data.isCode = item.isCode ? '是' : '否';
          data.remark = item.remark;
          data.tradetime = moment(item.tradetime).format('YYYY-MM-DD');
          excelData.push(data);
        });
        jsonToSheetXlsx({
          data: excelData,
          header: {
            No: 'No.',
            id: 'ID',
            type: '交易类型',
            typename: '交易名称',
            account: '交易账户',
            money: '金额',
            member: '相关会员',
            isCode: '是否开票',
            remark: '备注',
            tradetime: '交易日期',
          },
          filename,
          write2excelOpts: {
            bookType,
          },
        });
      }

      function createActions(record: EditRecordRow): ActionItem[] {
        return [
          {
            label: '编辑',
            icon: 'ant-design:edit-outlined',
            color: 'warning',
            onClick: handleEdit.bind(null, record),
          },
        ];
      }
      return {
        popupData,
        tableRef,
        registerTable,
        addRole,
        handleEdit,
        createActions,
        getTableAction,
        rowClick,
        selectionChange,
        addRegister,
        saveData,
        defaultHeader,
        openModal,
        register,
        ...toRefs(btn),
      };
    },
  });
</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 {
    flex: 1;
  }

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