import { useEffect, useMemo, useState } from 'react';
import { Modal, Select, Table } from 'antd';

const RelModal = (props) => {
  const { item, formList = [], visible, onCancel, onChange } = props;
  // const [linked, setLined] = useState([]);
  const [data, setData] = useState([]);

  useEffect(() => {
    let result = [];
    if (!item) {
      result = [];
    } else {
      const { componentName, props } = item;
      const selects = formList
        .filter(
          (curItem) => curItem.props?.required && curItem.props.id !== props.id,
        )
        .map((item) => item.props);
      result = props.options?.map((cur) => {
        const linked = props.linked ? props.linked[cur] : [];
        return { name: cur, selects, linked };
      });
    }
    setData(result);
  }, [item, formList]);

  const columns = [
    {
      title: '当选项为',
      dataIndex: 'name',
      key: 'name',
      width: '30%',
    },
    {
      title: '显示以下控件',
      render: (record) => (
        <Select
          value={record.linked}
          mode="multiple"
          placeholder="请选择"
          style={{ width: '100%' }}
          onChange={(value) => {
            const item = { ...record, linked: value };
            const newData = JSON.parse(JSON.stringify(data));
            const index = data.findIndex((item) => item.name == record.name);
            newData[index] = item;
            setData(newData);
          }}
          options={record.selects.map((item) => {
            return { label: item.label, value: item.id };
          })}
        />
      ),
    },
  ];
  return (
    <Modal
      title="单选框-选项关联"
      open={visible}
      onCancel={onCancel}
      onOk={() => {
        const linked = {};
        data?.forEach((cur) => {
          linked[cur.name] = cur.linked;
        });
        onChange?.({ linked });
      }}
      width={1000}
      pagination={false}
    >
      <div>根据选择的选项，显示其他控件，当前控件和上级选项不能被关联显示</div>
      <Table dataSource={data} columns={columns}></Table>
    </Modal>
  );
};
export default RelModal;
