import React, { useEffect, useState } from 'react';
import { Modal, Table, Button, Checkbox, Popconfirm, message, Descriptions, Spin } from 'antd';
import { getSupplierPage, detail, apply } from "../services";
import type { ColumnsType } from 'antd/es/table';
// 供应商类型
interface Supplier {
  id: string;
  name: string;
  region?: string;
  creditCode?: string;
  type?: string;
  inStore?: boolean; // 已入库
}

// 基本信息类型
interface CategoryInfo {
  name?: string;
  validDate?: string;
  manager?: string;
  structure?: string;
}

const SupplierAddModal: React.FC<{
  visible: boolean;
  storeId: string;
  onCancel: () => void;
  onSuccess: () => void;
}> = ({ visible, storeId, onCancel, onSuccess }) => {
  // 供应商数据
  const [suppliers, setSuppliers] = useState<Supplier[]>([]);
  // 已勾选的供应商 id
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  // 品类库基本信息
  const [categoryInfo, setCategoryInfo] = useState<CategoryInfo>({});
  // loading
  const [loading, setLoading] = useState(false);

  // 分页
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 拉数据
  const fetchSuppliers = async (page = 1, pageSize = 10) => {
    setLoading(true);
    const res = await getSupplierPage({ basePageRequest: { pageNo: page, pageSize } });
    setLoading(false);
    if (res.code === 200 && res.data) {
      setSuppliers((res.data.records || []).map((s: any) => ({
        ...s,
        inStore: s.inStore ?? false, // 若接口无此字段，可自己加逻辑判断
      })));
      setPagination(p => ({
        ...p,
        total: res.data.total || 0,
        current: res.data.current || page,
        pageSize: res.data.size || pageSize,
      }));
    }
  };

  // 拉取基本信息
  const fetchCategoryInfo = async () => {
    if (!storeId) return;
    const res = await detail({ id: storeId });
    if (res.code === 200 && res.data) setCategoryInfo(res.data);
  };

  useEffect(() => {
    if (visible) {
      fetchSuppliers(pagination.current, pagination.pageSize);
      fetchCategoryInfo();
    }
    // eslint-disable-next-line
  }, [visible, storeId]);

  // 分页变更
  const handleTableChange = (pag: any) => {
    setPagination({ ...pagination, current: pag.current, pageSize: pag.pageSize });
    fetchSuppliers(pag.current, pag.pageSize);
  };

  // 选择供应商 checkbox 变化
  const handleSelect = (checked: boolean, id: string) => {
    setSelectedIds(checked
      ? [...selectedIds, id]
      : selectedIds.filter(i => i !== id)
    );
  };

  // “移除”操作
  const handleRemove = (id: string) => {
    setSuppliers(suppliers.map(s =>
      s.id === id ? { ...s, inStore: false } : s
    ));
    message.success('移除成功');
  };

  // 确认入库
  const handleOk = () => {
    apply({ categoryLibraryId: storeId ,supplierIds: selectedIds  })
    setSelectedIds([]);
    onSuccess && onSuccess();
  };

  // 列表列 
  const columns: ColumnsType<Supplier> = [
    { title: '序号', dataIndex: 'id', align: 'center', width: 60, render: (t: any, r: any, i: number) => (pagination.current - 1) * pagination.pageSize + i + 1 },
    { title: '供应商名称', dataIndex: 'name', align: 'center' },
    { title: '境内/境外', dataIndex: 'region', align: 'center' },
    { title: '统一社会信用代码', dataIndex: 'creditCode', align: 'center' },
    { title: '供应商分类', dataIndex: 'type', align: 'center' },
    {
      title: '操作',
      align: 'center',
      render: (text: any, record: Supplier) => {
        if (record.inStore) {
          return (
            <>
              <span style={{ color: '#aaa' }}>已入库</span>
              <Popconfirm
                title="确认移除该供应商？"
                onConfirm={() => handleRemove(record.id)}
                okText="确认"
                cancelText="取消"
              >
                <Button size="small" type="link" danger style={{ marginLeft: 6 }}>移除</Button>
              </Popconfirm>
            </>
          );
        }
        return (
          <Checkbox
            checked={selectedIds.includes(record.id)}
            onChange={e => handleSelect(e.target.checked, record.id)}
          >
            选择
          </Checkbox>
        );
      }
    }
  ];

  return (
    <Modal
      title="添加供应商"
      visible={visible}
      onCancel={onCancel}
      footer={[
        <Button key="ok" type="primary" onClick={handleOk}>确认入库</Button>,
        <Button key="cancel" onClick={onCancel}>取消</Button>,
      ]}
      width={820}
      bodyStyle={{ padding: 24 }}
      destroyOnClose
    >
      {/* 基本信息区 */}
      <div style={{ marginBottom: 18 }}>
        <Descriptions
          title="品类库基本信息"
          bordered
          column={2}
          size="small"
          style={{ marginBottom: 18, background: '#fff', borderRadius: 4 }}
          labelStyle={{ width: 110, fontWeight: 500 }}
        >
          <Descriptions.Item label="品类库名称">
            {categoryInfo?.name || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="有效期至">
            {categoryInfo?.validDate || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="负责人">
            {categoryInfo?.manager || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="品类结构">
            {categoryInfo?.structure || '-'}
          </Descriptions.Item>
        </Descriptions>
      </div>
      {/* 供应商表格 */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        padding: '8px 0 8px 0',
        fontSize: 16,
        fontWeight: 500,
      }}>
        <span>选择供应商</span>
      </div>
      <Spin spinning={loading}>
        <Table
          columns={columns}
          dataSource={suppliers}
          rowKey="id"
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            onChange: (page, pageSize) => handleTableChange({ current: page, pageSize }),
          }}
          bordered
        />
      </Spin>
    </Modal>
  );
};

export default SupplierAddModal;
