import { Button, Checkbox, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import React, { useMemo, useState } from 'react';
import { ComponentName, FormItem } from '../../node/judgeNode/mapServe';

const AddCondition = (props: any) => {
  const { items = [], formItems = '', onOk } = props;
  const [visible, setVisible] = useState(false);
  const [values, setValues] = useState([]);
  console.log(formItems, items);

  let formData = useMemo(() => {
    let formDat = formItems ? JSON.parse(formItems) : [];
    setValues(formDat.map((cur: any) => cur.props.id));
    return formDat;
  }, [formItems]);

  const data: FormItem[] = items
    .filter((item: FormItem) => {
      return (
        (item.componentName == ComponentName.Inner ||
          // item.componentName == ComponentName.Depart ||
          item.componentName == ComponentName.Select ||
          item.componentName == ComponentName.MultiSelect ||
          item.componentName == ComponentName.Number ||
          item.componentName == ComponentName.Money) &&
        item.props.required
      );
    })
    .map((item: any) => {
      return {
        label: item.props.label,
        ...item,
      };
    });

  const onChange = (values: any) => {
    setValues(values);
  };

  const handleOk = () => {
    let resultData: FormItem[] = [];
    values.map((value) => {
      const item = formData.find((cur: any) => cur.props.id == value);
      if (item) {
        resultData.push(item);
      } else {
        const item = items.find((cur: any) => cur.props.id == value);
        resultData.push(item);
      }
    });
    onOk(resultData);
    setVisible(false);
  };

  return (
    <>
      <div className={`group`}>
        <Button icon={<PlusOutlined />} onClick={() => setVisible(true)}>
          选择条件
        </Button>
        还有{data.length - values.length}组可用条件
      </div>
      <Modal
        title="选择条件"
        open={visible}
        onOk={handleOk}
        onCancel={() => setVisible(false)}
      >
        <p>请选择用来区分审批流程的条件字段 ，已选{values.length}个</p>
        <Checkbox.Group
          style={{ display: 'block' }}
          value={values}
          onChange={(values) => onChange(values)}
        >
          {data.map((item: FormItem) => (
            <Checkbox key={item.props.id} value={item.props.id}>
              {item.props.label}
            </Checkbox>
          ))}
        </Checkbox.Group>
      </Modal>
    </>
  );
};
export default AddCondition;
