import React, { useState, useEffect } from 'react';
import { Modal, Input, Select, Row, Col, Table, Button, Form, Tooltip  } from 'antd';
import { RightOutlined, LeftOutlined } from '@ant-design/icons';
import { coscoSupplierBase } from '../services';

const { Option } = Select;

const SupplierSelector: React.FC<{ visible: boolean; onCancel: () => void; onSelect?: (selected: any[]) => void; }> = ({ visible, onCancel, onSelect }) => {
  // 查询
  const [form] = Form.useForm();
  //列表渲染数据
  const [tableListData, setTableListData] = useState([]);
  //列表分页
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  //列表加载
  const [loading, setLoading] = useState(false);
  //已选供应商
  const [leftSelected, setLeftSelected] = useState<React.Key[]>([]);
  //选择供应商
  const [rightSelected, setRightSelected] = useState<React.Key[]>([]);
  //确认 已选供应商
  const [chosenSuppliers, setChosenSuppliers] = useState<any[]>([]);
  //已选供应商 去重
  const filteredData = (chosenSuppliers:any, selected:any) => {
    const ids = new Set(chosenSuppliers.map((item:any) => item.id));
    // 只把 selected 里没出现过的加进去
    const newSelected = selected.filter((item:any) => !ids.has(item.id));
    return [...chosenSuppliers, ...newSelected];
  };
  //获取已选供应商
  const moveToRight = () => {
    const selected = tableListData.filter((item:any) => leftSelected.includes(item.id));
    const chosenSuppliersNew = filteredData(chosenSuppliers, selected);
    setChosenSuppliers(chosenSuppliersNew);
    setLeftSelected([]);
  };
  // 删除已选供应商
  const moveToLeft = () => {
    const remaining = chosenSuppliers.filter((item:any) => !rightSelected.includes(item.id));
    setChosenSuppliers(remaining);
    setRightSelected([]);
  };
  // 列表方法
  const getTableList = async (values: any = {}, pageNo: number = 1, pageSize: number = 10) => {
    setLoading(true);
    try {
      const { code, data } = await coscoSupplierBase({ ...values, basePageRequest: { pageNo, pageSize}  });
      if (code === 200) {
        setTableListData(data.records);
        setPagination({ current: pageNo, pageSize, total: data.total });
      }
    } finally {
      setLoading(false);
    }
  };
  // 初始化
  useEffect(() => {
    if(visible) {
      const values = form.getFieldsValue();
      getTableList(values,1 , 10)
    }
  }, [visible])
  //供应商名称
  const columns = [
    { title: '供应商名称', dataIndex: 'name',  ellipsis: true,  render: (name: string) => (
      <Tooltip placement="topLeft" title={name}>
        {name}
      </Tooltip>
    ), },
    { title: '境内/境外', dataIndex: 'supplierType', render: (supplierType: string) =>  supplierType === 'dvs' ? '境内' : '境外'},
  ];
  return (
    <Modal title="选择供应商" visible={visible} onCancel={onCancel} footer={null} width="80%">

      <Form layout="inline" form={form} onFinish={getTableList} style={{ marginBottom: 16 }}>
        <Form.Item name="accessType" label="供应商名称">
          <Input placeholder="供应商名称" allowClear />
        </Form.Item>
        <Form.Item name="deptId" label="境内/境外">
          <Select placeholder="境内/境外" allowClear >
            <Option value="境内">境内</Option>
            <Option value="境外">境外</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={() => form.resetFields()}>重置</Button>
        </Form.Item>
      </Form>


      <Row gutter={16}>
        <Col span={10}>
          <div>待选供应商</div>
          <Table
            rowSelection={{ type: 'checkbox', onChange: setLeftSelected, selectedRowKeys: leftSelected }}
            rowKey="id"
            dataSource={tableListData}
            columns={columns}
            loading={loading}
            pagination={pagination} 
            onChange={(pagination) => {
              const values = form.getFieldsValue();
              getTableList(values, pagination.current!, pagination.pageSize!)
            }}
            scroll={{ y: 300 }}
          />
        </Col>

        <Col span={4} style={{ textAlign: 'center', paddingTop: 100 }}>
          <Button onClick={moveToRight} disabled={leftSelected.length === 0}>
            <RightOutlined />
          </Button>
          <br />
          <br />
          <Button onClick={moveToLeft} disabled={rightSelected.length === 0}>
            <LeftOutlined />
          </Button>
        </Col>

        <Col span={10}>
          <div>已选供应商</div>
          <Table
            rowSelection={{ type: 'checkbox', onChange: setRightSelected, selectedRowKeys: rightSelected }}
            columns={columns}
            dataSource={chosenSuppliers}
            rowKey="id"
            pagination={false}
            scroll={{ y: 300 }}
          />
        </Col>
      </Row>

      <div style={{ textAlign: 'right', marginTop: 16 }}>
        <Button style={{ marginRight: 8 }} onClick={onCancel}>
          取消
        </Button>
        <Button
          type="primary"
          onClick={() => {
            onSelect?.(chosenSuppliers);
            onCancel();
          }}
        >
          确认
        </Button>
      </div>
    </Modal>
  );
};

export default SupplierSelector;
