import React, { useEffect, useState } from 'react';
import { Table, Button } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { invoiceGetPage } from '../services';
import { useIntl } from 'umi';
import InvoiceFormModal from './InvoiceFormModal';

interface InvoiceInfo {
  id: string;
  taxpayerType: string;
  taxpayerCode: string;
  head: string;
  address: string;
  phone: string;
  bank: string;
  account: string;
  updateTime: string;
  certificateUrl: string;
}

interface InvoiceTabProps {
  viewType?: boolean;
  record?: string;
}

const InvoiceTab: React.FC<InvoiceTabProps> = (props) => {
  const userId = sessionStorage.getItem('userId') || '';
  const { viewType = false, record = userId } = props;
  //语言切换
  const intl = useIntl();
  //列表渲染数据
  const [data, setData] = useState<InvoiceInfo[]>([]);
  //列表加载
  const [loading, setLoading] = useState(false);
  //列表分页
  const [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10, total: 0 });

  //列表方法
  const getList = async (pageNo = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const { code, data } = await invoiceGetPage({ pageNo, pageSize, supplierId: record });
      if (code === 200) {
        setData(data.records);
        setPagination({ current: pageNo, pageSize, total: data.total });
      }
    } finally {
      setLoading(false);
    }
  };

  //增改查
  const [formVisible, setFormVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState<InvoiceInfo | null>(null);
  const [isViewMode, setIsViewMode] = useState(false);
  const handleFormSubmit = () => {
    setFormVisible(false);
    getList();
  };
  const handleAdd = () => {
    setEditingRecord(null);
    setIsViewMode(false);
    setFormVisible(true);
  };

  const handleEdit = (record: InvoiceInfo) => {
    setEditingRecord(record);
    setIsViewMode(false);
    setFormVisible(true);
  };

  const handleView = (record: InvoiceInfo) => {
    setEditingRecord(record);
    setIsViewMode(true);
    setFormVisible(true);
  };

  //初始化
  useEffect(() => {
    if(record) {
      getList();
    }
  }, [record]);

  const columns: ColumnsType<InvoiceInfo> = [
    { title: 'page.workbench.invoice.index', dataIndex: 'index', width: 80, key: 'index', render: (_: any, __: any, index: number) => index + 1 },
    { title: 'page.workbench.invoice.taxpayerType', dataIndex: 'taxpayerType', ellipsis: true },
    { title: 'page.workbench.invoice.taxpayerCode', dataIndex: 'taxpayerCode', ellipsis: true },
    { title: 'page.workbench.invoice.head', dataIndex: 'head', ellipsis: true },
    { title: 'page.workbench.invoice.address', dataIndex: 'address', ellipsis: true },
    { title: 'page.workbench.invoice.phone', dataIndex: 'phone', ellipsis: true },
    { title: 'page.workbench.invoice.bank', dataIndex: 'bank', ellipsis: true },
    { title: 'page.workbench.invoice.account', dataIndex: 'account', ellipsis: true },
    { title: 'page.workbench.invoice.updateTime', dataIndex: 'updateTime', ellipsis: true },
    {
      title: 'page.workbench.invoice.qualificationCertificate',
      width: '180px',
      dataIndex: 'qualificationCertificate',
      render: (val: string) => (val ? <a href={val} target="_blank" rel="noreferrer">查看附件</a> : '-'),
    },
    ...(viewType ? [] : [
      {
        title: 'page.workbench.attachments.action',
        dataIndex: 'option',
        width: 120,
        render: (_: any, record: InvoiceInfo) => (
          <>
            <a style={{ marginRight: 8 }} onClick={() => handleView(record)}>查看</a>
            <a onClick={() => handleEdit(record)}>修改</a>
          </>
        ),
      },
    ]),
  ];
  return (
    <div style={{ padding: '0 30px 0 0' }}>
      <div style={{ marginBottom: 16 }}>
        {!viewType && (
          <Button type="primary" onClick={handleAdd}>新增</Button>
        )}
      </div>
      <Table
        className="custom-table"
        rowKey="id"
        columns={columns.map(column => ({
          ...column,
          title: intl.formatMessage({ id: column.title as string })
        }))}
        dataSource={data}
        pagination={pagination}
        loading={loading}
        onChange={(pagination) => getList(pagination.current!, pagination.pageSize!)}
      />
      <InvoiceFormModal
        visible={formVisible}
        onOk={handleFormSubmit}
        onCancel={() => setFormVisible(false)}
        initialValues={editingRecord || undefined}
        readOnly={isViewMode}
      />
    </div>
  );
};

export default InvoiceTab;