import React, { useEffect, useState } from "react";
import {
  Modal, Table, Button, Checkbox, Row, Col, Input, Select, Form, Space, message
} from "antd";
import { getSupplierCategoryPage } from '../services';

const { Option } = Select;

interface Supplier {
  id: number;
  supplierId: string;
  categoryId: string;
  supplierName: string;

  unit: string;         // 准入部门
  accessTime: string;   // 准入时间
  categoryName: string; // 准入品类
  lastEval: string;     // 最近一次评价
  lastEvalDate: string; // 评价时间
  
}

interface SupplierSelectModalProps {
  visible: boolean;
  selectedSuppliers: Supplier[];
  onOk: (suppliers: Supplier[]) => void;
  onCancel: () => void;
}


const SupplierSelectModal: React.FC<SupplierSelectModalProps> = ({
  visible,
  selectedSuppliers,
  onOk,
  onCancel,
}) => {
  const [form] = Form.useForm();
  const [leftSelected, setLeftSelected] = useState<number[]>([]);
  const [rightSelected, setRightSelected] = useState<number[]>([]);
  const [rightData, setRightData] = useState<Supplier[]>([]);
  const [data, setData] = useState<Supplier[]>([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 5, total: 0 });
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      setRightData(selectedSuppliers || []);
      fetchData();
    }
  }, [visible]);

  const fetchData = async (params: any = {}, pageNo = 1, pageSize = 5) => {
    setLoading(true);
    try {
      const res = await getSupplierCategoryPage({ ...params, pageNo, pageSize });
      if (res.code === 200) {
        setData(res.data.records);
        setPagination({ current: pageNo, pageSize: pageSize, total: res.data.total });
      } else {
        message.error('获取数据失败');
      }
    } catch {
      message.error('获取数据异常');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    const values = form.getFieldsValue();
    fetchData(values, 1, pagination.pageSize);
  };

  const handleReset = () => {
    form.resetFields();
    fetchData({}, 1, pagination.pageSize);
  };

  const handleAdd = () => {
    const added = data.filter(s => leftSelected.includes(s.id));
    const combined = [...rightData, ...added.filter(i => !rightData.some(r => r.id === i.id))];
    setRightData(combined);
    setLeftSelected([]);
  };

  const handleRemove = () => {
    setRightData(rightData.filter(i => !rightSelected.includes(i.id)));
    setRightSelected([]);
  };

  const handleOk = () => {
    onOk(rightData);
  };

  const columns = [
    {
      title: <Checkbox
        checked={leftSelected.length === data.length && data.length > 0}
        indeterminate={leftSelected.length > 0 && leftSelected.length < data.length}
        onChange={e => {
          setLeftSelected(e.target.checked ? data.map(i => i.id) : []);
        }}
      >全选</Checkbox>,
      dataIndex: "select",
      width: 80,
      render: (_: any, record: Supplier) => (
        <Checkbox
          checked={leftSelected.includes(record.id)}
          onChange={e => {
            setLeftSelected(e.target.checked
              ? [...leftSelected, record.id]
              : leftSelected.filter(id => id !== record.id));
          }}
        >选择</Checkbox>
      )
    },
    { title: "供应商名称", dataIndex: "supplierName" },
    { title: "准入单位", dataIndex: "deptId" },
    { title: "准入部门", dataIndex: "deptId" },
    { title: "准入品类", dataIndex: "categoryName" }
  ];

  const rightColumns = [
    {
      title: <Checkbox
        checked={rightSelected.length === rightData.length && rightData.length > 0}
        indeterminate={rightSelected.length > 0 && rightSelected.length < rightData.length}
        onChange={e => {
          setRightSelected(e.target.checked ? rightData.map(i => i.id) : []);
        }}
      >全选</Checkbox>,
      dataIndex: "select",
      width: 80,
      render: (_: any, record: Supplier) => (
        <Checkbox
          checked={rightSelected.includes(record.id)}
          onChange={e => {
            setRightSelected(e.target.checked
              ? [...rightSelected, record.id]
              : rightSelected.filter(id => id !== record.id));
          }}
        >选择</Checkbox>
      )
    },
    { title: "供应商名称", dataIndex: "supplierName" },
    { title: "准入单位", dataIndex: "deptId" },
    { title: "准入部门", dataIndex: "deptId" },
    { title: "准入品类", dataIndex: "categoryName" }
  ];

  return (
    <Modal
      title="选择供应商"
      visible={visible}
      onCancel={onCancel}
      onOk={handleOk}
      width={1000}
      destroyOnClose
      okText="确认"
      cancelText="取消"
      bodyStyle={{ padding: 24 }}
    >
      <Form layout="inline" form={form} style={{ marginBottom: 16 }}>
        <Form.Item name="name" label="供应商名称">
          <Input style={{ width: 180 }} allowClear />
        </Form.Item>
        <Form.Item name="evalLevel" label="最近一次评价等级">
          <Select style={{ width: 140 }} allowClear>
            {['A', 'B', 'C', 'D'].map(level => (
              <Option key={level} value={level}>{level}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="category" label="准入品类">
          <Select style={{ width: 140 }} allowClear>
            {['燃油', '润滑油', '备件'].map(cat => (
              <Option key={cat} value={cat}>{cat}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" onClick={handleSearch}>查询</Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>

      <Row gutter={32}>
        <Col span={11}>
          <div style={{ marginBottom: 8 }}>备选供应商</div>
          <Table
            rowKey="id"
            dataSource={data}
            columns={columns}
            loading={loading}
            pagination={pagination}
            onChange={(pag) => {
              const values = form.getFieldsValue();
              fetchData(values, pag.current!, pag.pageSize!);
            }}
            size="small"
            bordered
          />
        </Col>
        <Col span={2} style={{ textAlign: "center", display: "flex", flexDirection: "column", justifyContent: "center" }}>
          <Button type="primary" disabled={!leftSelected.length} onClick={handleAdd} style={{ marginBottom: 16 }}>{">"}</Button>
          <Button disabled={!rightSelected.length} onClick={handleRemove}>{"<"}</Button>
        </Col>
        <Col span={11}>
          <div style={{ marginBottom: 8 }}>已选供应商</div>
          <Table
            rowKey="id"
            dataSource={rightData}
            columns={rightColumns}
            pagination={false}
            size="small"
            bordered
          />
        </Col>
      </Row>
    </Modal>
  );
};

export default SupplierSelectModal;
