import React, { useEffect, useState } from 'react';
import { Table, Button, Switch, message } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { invoiceGetPage, invoiceEdit } from '../services';
import { useIntl } from 'umi';
import InvoiceFormModal from './InvoiceFormModal';
import { getDictList } from '@/servers/api/dicts';
interface InvoiceInfo {
  id: string;
  taxpayerType: string;
  taxpayerCode: string;
  head: string;
  address: string;
  phone: string;
  bank: string;
  account: string;
  updateTime: string;
  certificateUrl: string;
  delFlag: 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);
  };
  //是否作废
  const handleObsoleteChange = async (checked: boolean, id: string) => {
    // 调用你的作废接口
    const res = await invoiceEdit({ id, delFlag: checked ? 'normal' : 'deleted' });
    if (res.code === 200) {
      message.success('操作成功');
      getList(pagination.current, pagination.pageSize);  // 刷新列表
    } else {
      message.error('操作失败');
    }
  }
   const [taxpayerTypeMap, setTaxpayerTypeMap] = useState<{ [code: string]: string }>({});
  //初始化
  useEffect(() => {
    if (record) {
      getDictList('taxpayer_type').then((res) => {
        if (res.code === 200) {
          const map: { [code: string]: string } = {};
          res.data.forEach((item: { code: string, dicName: string }) => {
            map[item.code] = item.dicName;
          });
          setTaxpayerTypeMap(map);
        }
      });
      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, render: (code: string) => taxpayerTypeMap[code] || code },
    { 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: '是否作废',
      dataIndex: 'delFlag',
      align: 'center',
      width: 100,
      render: (value, record) => {
        let checkedType = value === 'normal' ? true : false;
        return (
          <Switch
            checked={checkedType}
            disabled={viewType}
            onChange={(checked) => handleObsoleteChange(checked, record.id)}
          />
        )

      },
    },
    {
      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>
            {record.delFlag === 'normal' && (
              <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;