import React, { useEffect, useState } from "react";
import { Modal, Table, Button, Checkbox, Row, Col, Input, Select, Pagination, Form, Space } from "antd";

const { Option } = Select;

// mock 数据
const mockSuppliers = Array.from({ length: 25 }).map((_, i) => ({
  id: i + 1,
  name: `XXXX${i + 1}有限公司`,
  unit: "散运三级单位",
  dept: "采购部",
  category: ["燃油", "润滑油", "备件"][i % 3],
  evalLevel: ["A", "B", "C", "D"][i % 4],
}));

const evalOptions = [
  { value: "", label: "请选择" },
  { value: "A", label: "A" },
  { value: "B", label: "B" },
  { value: "C", label: "C" },
  { value: "D", label: "D" },
];

const categoryOptions = [
  { value: "", label: "请选择" },
  { value: "燃油", label: "燃油" },
  { value: "润滑油", label: "润滑油" },
  { value: "备件", label: "备件" },
];

const PAGE_SIZE = 5;

const SupplierSelectModal = ({
  visible,
  onOk,
  onCancel,
  selectedSuppliers,
}) => {
  // 查询表单
  const [form] = Form.useForm();
  // 选中
  const [leftSelected, setLeftSelected] = useState([]);
  const [rightSelected, setRightSelected] = useState([]);
  const [rightData, setRightData] = useState(selectedSuppliers || []);
  const [leftPage, setLeftPage] = useState(1);
  const [query, setQuery] = useState({});

  // 数据过滤
  const filteredSuppliers = mockSuppliers.filter(item => {
    const { name = "", evalLevel = "", category = "" } = query;
    return (
      (!name || item.name.includes(name)) &&
      (!evalLevel || item.evalLevel === evalLevel) &&
      (!category || item.category === category)
    );
  });
  const pagedSuppliers = filteredSuppliers.slice((leftPage - 1) * PAGE_SIZE, leftPage * PAGE_SIZE);

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

  // 查询
  const handleSearch = () => {
    setQuery(form.getFieldsValue());
    setLeftPage(1);
    setLeftSelected([]);
  };
  // 重置
  const handleReset = () => {
    form.resetFields();
    setQuery({});
    setLeftPage(1);
    setLeftSelected([]);
  };

  const leftColumns = [
    {
      title: <Checkbox
        checked={leftSelected.length === pagedSuppliers.length && pagedSuppliers.length > 0}
        indeterminate={leftSelected.length > 0 && leftSelected.length < pagedSuppliers.length}
        onChange={e => {
          setLeftSelected(e.target.checked ? pagedSuppliers.map(i => i.id) : []);
        }}
      >全选</Checkbox>,
      dataIndex: "select",
      width: 60,
      render: (_: any, record) => (
        <Checkbox
          checked={leftSelected.includes(record.id)}
          onChange={e => {
            setLeftSelected(e.target.checked
              ? [...leftSelected, record.id]
              : leftSelected.filter(id => id !== record.id));
          }}
        >选择</Checkbox>
      )
    },
    { title: "供应商名称", dataIndex: "name" },
    { title: "准入单位", dataIndex: "unit" },
    { title: "准入部门", dataIndex: "dept" },
    { title: "准入品类", dataIndex: "category" },
    { title: "最近一次评价等级", dataIndex: "evalLevel" }
  ];

  // 已选表格
  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: 60,
      render: (_: any, record) => (
        <Checkbox
          checked={rightSelected.includes(record.id)}
          onChange={e => {
            setRightSelected(e.target.checked
              ? [...rightSelected, record.id]
              : rightSelected.filter(id => id !== record.id));
          }}
        >选择</Checkbox>
      )
    },
    { title: "供应商名称", dataIndex: "name" },
    { title: "准入单位", dataIndex: "unit" },
    { title: "准入部门", dataIndex: "dept" },
    { title: "准入品类", dataIndex: "category" }
  ];

  // 添加
  const handleAdd = () => {
    const added = pagedSuppliers.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);
  };

  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 }}>
            {evalOptions.map(opt => <Option value={opt.value} key={opt.value}>{opt.label}</Option>)}
          </Select>
        </Form.Item>
        <Form.Item name="category" label="准入品类">
          <Select style={{ width: 140 }}>
            {categoryOptions.map(opt => <Option value={opt.value} key={opt.value}>{opt.label}</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 }}>备选供应商 <span style={{ color: "#1890ff" }}>{filteredSuppliers.length}</span></div>
          <Table
            columns={leftColumns}
            dataSource={pagedSuppliers}
            rowKey="id"
            pagination={false}
            size="small"
            bordered
          />
          <div style={{ textAlign: "right", marginTop: 8 }}>
            <Pagination
              simple
              current={leftPage}
              pageSize={PAGE_SIZE}
              total={filteredSuppliers.length}
              onChange={setLeftPage}
            />
          </div>
        </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
            columns={rightColumns}
            dataSource={rightData}
            rowKey="id"
            pagination={false}
            size="small"
            bordered
          />
        </Col>
      </Row>
    </Modal>
  );
};

export default SupplierSelectModal;
