import {
  MyButtons,
  MyColumns,
  MyImportModal,
  MyPageContainer,
  MyProTableProps,
  MyTableActions,
  MyToolBarActions,
} from '@/common';

import { MyExport } from '@/components/MyExport';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import {
  ApprovalTemplatesTypeEnum,
  HouseBillsBillStatusEnum,
  HouseBillsTypeEnum,
  RefundsTypeEnum,
} from '@/gen/Enums';
import { ProTable } from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import { useState } from 'react';
import BillCreate from './modals/BillCreate';
import BIllInfo from './modals/BIllInfo';
import BillRefund from './modals/BillRefund';
import BillUpdate from './modals/BillUpdate';
import PayCreate from './modals/Pay';
import ShowQrCode from './modals/QrCode';
import RefundComplete from './modals/RefundComplete';

export default function Index({ title = '账单明细' }) {
  const navigate = useNavigate();
  const [getParams, setParams] = useState({});

  return (
    <MyPageContainer
      title={title}
      enableTabs={true}
      tabKey="house_bills"
      tabLabel={title}
    >
      <ProTable
        {...MyProTableProps.props}
        headerTitle={title}
        request={async (params, sort) => {
          setParams(params);
          return MyProTableProps.request(
            params,
            sort,
            Apis.Bill.HouseBills.List,
          );
        }}
        toolBarRender={(action: any) => [
          <MyToolBarActions
            key="toolbar"
            actions={{
              import: (
                <MyImportModal
                  key="ImportHouse"
                  title="应收导入"
                  type="default"
                  size="middle"
                  templateApi={Apis.Bill.HouseBills.DownloadTemplate}
                  importApi={Apis.Bill.HouseBills.Import}
                  reload={action?.reload}
                />
              ),
              import2: (
                <MyImportModal
                  key="import"
                  title="收款单导入"
                  type="default"
                  size="middle"
                  templateApi={
                    Apis.HouseOrder.HouseOrders.DownloadOfflinePaymentTemplate
                  }
                  importApi={Apis.HouseOrder.HouseOrders.ImportOfflinePayment}
                  reload={action?.reload}
                />
              ),
              export: (
                <MyExport
                  key="export"
                  title="账单导出"
                  item={getParams}
                  download={Apis.Bill.HouseBills}
                />
              ),
              add: <BillCreate key="Create" reload={action?.reload} title={title} />,
            }}
          />,
        ]}
        columns={[
          MyColumns.ID({ search: false }),
          Selects?.AssetProjects({
            title: '选择项目',
            key: 'asset_projects_id',
            hidden: true,
          }),
          {
            key: 'year',
            title: '账单年',
            valueType: 'date',
            fieldProps: {
              picker: 'year',
              format: 'YYYY',
              valueFormat: 'YYYY',
              style: {
                width: '100%',
              },
            },
            hidden: true,
          },
          {
            key: 'month',
            title: '账单月',
            valueType: 'date',
            fieldProps: {
              picker: 'month',
              format: 'YYYY-MM',
              valueFormat: 'YYYY/MM',
              style: {
                width: '100%',
              },
            },
            search: {
              transform: (value) => {
                let month = value.split('-');
                return { year: month[0], month: month[1] };
              },
            },
            hidden: true,
          },
          {
            title: '关联房屋',
            dataIndex: ['asset_house', 'full_name'],
            search: {
              transform: (value) => {
                return { full_name: value };
              },
            },
            render: (_, record) => {
              return record.asset_houses_id ? (
                <MyButtons.View
                  title={`${record?.asset_house?.full_name || '-'}`}
                  type="link"
                  onClick={() => {
                    navigate(`/bills/summary/show/${record.asset_houses_id}`);
                  }}
                />
              ) : (
                '车位｜ ' + record.asset_car_port.full_name
              );
            },
          },

          {
            title: '账单月份',
            render: (_, record) => {
              return `${record.year}-${String(record.month).padStart(2, '0')}`;
            },
            search: false,
          },

          MyColumns.EnumTag({
            title: '类型',
            dataIndex: 'type',
            valueEnum: HouseBillsTypeEnum,
          }),
          MyColumns.EnumTag({
            title: '状态',
            dataIndex: 'bill_status',
            valueEnum: HouseBillsBillStatusEnum,
            search: {
              transform: (value) => {
                return { bill_status: [value] };
              },
            },
          }),
          {
            title: '账单金额',
            dataIndex: 'amount',
            search: false,
          },
          {
            title: '优惠金额',
            dataIndex: 'discount_amount',
            search: false,
          },
          {
            title: '滞纳金',
            dataIndex: 'late_fee',
            search: false,
          },
          {
            title: '应收金额',
            dataIndex: 'total_payable_amount',
            search: false,
          },
          {
            title: '已收金额',
            dataIndex: 'total_paid_amount',
            search: false,
          },
          MyColumns.Boolean({
            title: '退款申请',
            dataIndex: 'has_refunding',
          }),
          {
            title: '计费周期',
            dataIndex: 'start_date',
            render: (_, record) => {
              return `${record.start_date} 至 ${record.end_date}`;
            },
            search: false,
          },

          MyColumns.Option({
            render: (_, item: any, _index, action) => (
              <MyTableActions
                actions={{
                  show: (
                    <BIllInfo
                      item={{ ...item, type: 'primary' }}
                      reload={action?.reload}
                      title="查看"
                    />
                  ),
                  qrcode: <ShowQrCode key="ShowQrCode" item={item} title="收款码" />,
                  pay: (
                    <PayCreate
                      item={{ ...item, size: 'small' }}
                      reload={action?.reload}
                      title={title}
                    />
                  ),
                  update: <BillUpdate item={item} reload={action?.reload} title={title} />,
                  complete: (
                    <RefundComplete
                      item={{ ...item, id: item?.refunds[0]?.id }}
                      reload={action?.reload}
                      title={title}
                    />
                  ),
                  refund: (
                    <BillRefund
                      item={{
                        ...item,
                        type: RefundsTypeEnum.HouseBill.value,
                        approval_type: ApprovalTemplatesTypeEnum.Refund.value,
                        total_paid_amount: item.total_paid_amount,
                      }}
                      reload={action?.reload}
                      title={title}
                    />
                  ),
                  delete: (
                    <MyButtons.Delete
                      disabled={
                        item.bill_status !==
                          HouseBillsBillStatusEnum.PartiallyPaid.value &&
                        item.bill_status !== HouseBillsBillStatusEnum.Paid.value
                      }
                      onConfirm={() =>
                        Apis.Bill.HouseBills.Delete({ id: item.id }).then(() =>
                          action?.reload(),
                        )
                      }
                    />
                  ),
                }}
              />
            ),
          }),
        ]}
      />
    </MyPageContainer>
  );
}
