import React, { useState, useEffect, forwardRef, useImperativeHandle, useRef } from 'react';
import { Drawer, Form, Space, Button, Input, Select, Divider, Tooltip, message } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { GetSubEventFlows, GetFlowMapFields } from '@/services/workflow/workflow';
import lodash from 'lodash';

const { Option, OptGroup } = Select;

const ConfigSubprocess = (props, ref) => {
  const [form] = Form.useForm();
  const { editMsg, flowID, nodeChage } = props;
  const [currentNodeField, setCurrentNodeField] = useState([]);
  const [childNodeField, setChildNodeField] = useState([]);
  const [flowList, setFlowList] = useState([]);
  const SubFlowInfo = useRef();
  useImperativeHandle(ref, () => ({
    getParmar,
  }));
  useEffect(() => {
    GetSubEventFlows().then(res => {
      const list = new Map();

      // res.data.forEach(item => {
      //   if (!list.has(item.EventName)) {
      //     list.set(item.EventName, [item]);
      //   } else {
      //     console.log(list.get(item.EventName));
      //     list.set(item.EventName, [...list.get(item.EventName), item]);
      //   }
      // });
      setFlowList(
        res.data.map(item => ({
          label: `${item.FlowName}(${item.EventName})`,
          key: `${item.SubFlowEventConfigID}-${item.SubFlowId}`,
        })),
      );
      console.log(list, 'listnlistst');
    });
  }, []);
  useEffect(() => {
    console.log(editMsg, 'editMsg');
    form.setFieldsValue({ flowKey: '', MapFields: [] });
    if (editMsg.SubFlowInfo) {
      GetFlowMapFields({
        flowID,
        subFlowID: editMsg.SubFlowInfo?.SubFlowID,
        subFlowID: editMsg.SubFlowInfo?.SubFlowEventConfigID,
      }).then(res => {
        if (res.code === 0) {
          res.data.ParentFlowMapList.forEach(item => {
            item.TableFieldNames = item.TableFieldNames.map(ele => ({
              value: `${item.TableName}-${ele}-${item.TableType}`,
              label: ele,
            }));
          });
          res.data.SubFlowMapInfo.TableFieldNames = res.data.SubFlowMapInfo.TableFieldNames.map(
            item => ({
              value: `${res.data.SubFlowMapInfo.TableName}-${item}`,
              label: item,
            }),
          );
          console.log(res.data.ParentFlowMapList, 'res.data.ParentFlowMapList');
          setCurrentNodeField(res.data.ParentFlowMapList);
          setChildNodeField(res.data.SubFlowMapInfo.TableFieldNames);
        } else {
          message.error(res.msg);
        }
      });

      form.setFieldsValue({
        flowKey: editMsg.SubFlowInfo
          ? `${editMsg.SubFlowInfo?.SubFlowEventConfigID}-${editMsg.SubFlowInfo?.SubFlowID}`
          : null,
        MapFields: editMsg.SubFlowInfo?.MapFields?.map(item => ({
          nodeField: item.ParentFlowMapTableName
            ? `${item.ParentFlowMapTableName}-${item.ParentFlowMapFieldName}-${
                item.ParentFlowMapTableType
              }`
            : '',
          subNodeField: `${item.SubFlowMapTableName}-${item.SubFlowMapFieldName}`,
        })),
      });
    }
  }, [editMsg]);
  const getParmar = () => ({ SubFlowInfo: SubFlowInfo.current });
  const changeValue = (changedFields, allFields) => {
    console.log(changedFields, 'changedFields');
    let MapFields = [];
    if (changedFields[0].name[0] === 'MapFields') {
      MapFields = allFields[1]?.value?.map(item => ({
        ParentFlowMapTableName: item?.nodeField?.split('-')[0],
        ParentFlowMapFieldName: item?.nodeField?.split('-')[1],
        ParentFlowMapTableType: item?.nodeField?.split('-')[2],
        SubFlowMapTableName: item?.subNodeField?.split('-')[0],
        SubFlowMapFieldName: item?.subNodeField?.split('-')[1],
      }));
    }
    const msg = {
      SubFlowEventConfigID: Number(allFields[0]?.value?.split('-')[0]),
      SubFlowID: Number(allFields[0]?.value?.split('-')[1]),
      MapFields: MapFields,
    };
    SubFlowInfo.current = msg;
    nodeChage('SubFlowInfo', SubFlowInfo.current);
  };
  // 选择流程
  const flowChage = e => {
    console.log(e);
    form.setFieldsValue({ MapFields: [] });
    const subFlowID = e.split('-')[1];
    const SubFlowEventConfigID = e.split('-')[0];
    console.log(subFlowID, 'afsdfsda');
    GetFlowMapFields({ flowID, subFlowID, SubFlowEventConfigID }).then(res => {
      if (res.code === 0) {
        res.data.ParentFlowMapList.forEach(item => {
          item.TableFieldNames = item.TableFieldNames.map(ele => ({
            value: `${item.TableName}-${ele}-${item.TableType}`,
            label: ele,
          }));
        });
        res.data.SubFlowMapInfo.TableFieldNames = res.data.SubFlowMapInfo.TableFieldNames.map(
          item => ({
            value: `${res.data.SubFlowMapInfo.TableName}-${item}`,
            label: item,
          }),
        );
        console.log(res.data.ParentFlowMapList, 'res.data.ParentFlowMapList');

        setCurrentNodeField(res.data.ParentFlowMapList);
        setChildNodeField(res.data.SubFlowMapInfo.TableFieldNames);
      } else {
        message.error(res.msg);
      }
    });
  };
  // 添加映射
  const addMap = add => {
    if (form.getFieldValue('flowKey')) {
      add();
    } else {
      message.error('请选择子流程');
    }
  };
  return (
    <div>
      <Divider
        orientation="left"
        style={{
          borderTopColor: '#99bbe8',
          color: '#15428b',
          fontWeight: 700,
        }}
      >
        子流程配置
      </Divider>
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        onFieldsChange={changeValue}
      >
        <Form.Item label="选择流程" name="flowKey">
          <Select
            showSearch
            optionFilterProp="children"
            onChange={flowChage}
            filterOption={(input, option) =>
              option.children.toLowerCase().includes(input.toLowerCase())
            }
          >
            {flowList.map(item => (
              <Option key={item.key} value={item.key}>
                {item.label}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item wrapperCol={{ span: 24 }}>
          <Form.List name="MapFields">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }) => (
                  <div
                    key={key}
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      marginBottom: 8,
                    }}
                  >
                    <Form.Item
                      {...restField}
                      name={[name, 'nodeField']}
                      style={{ margin: '0 5px 0 0px', width: '40%' }}
                      rules={[
                        {
                          required: true,
                          message: '请填选择字段',
                        },
                      ]}
                    >
                      <Select placeholder="字段名" showSearch>
                        {currentNodeField?.map((item, index) => (
                          <OptGroup key={index} label={item.TableName}>
                            {item.TableFieldNames.map(ele => (
                              <Option value={ele.value} key={ele.value}>
                                {ele?.label}
                              </Option>
                            ))}
                          </OptGroup>
                        ))}
                      </Select>
                    </Form.Item>
                    <img
                      // eslint-disable-next-line global-require
                      src={require('@/assets/images/icons/值映射.png')}
                      style={{ height: '24px' }}
                      alt=""
                    />
                    <Form.Item
                      {...restField}
                      name={[name, 'subNodeField']}
                      style={{ margin: '0 5px 0 5px', width: '40%' }}
                      rules={[
                        {
                          required: true,
                          message: '请填选择字段',
                        },
                      ]}
                    >
                      <Select placeholder="字段名" showSearch>
                        {childNodeField?.map((item, index) => (
                          <Option value={item.value} key={item.value}>
                            {item.label}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </div>
                ))}
                <Form.Item>
                  <Button type="dashed" onClick={() => addMap(add)} block icon={<PlusOutlined />}>
                    添加映射字段
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form.Item>
      </Form>
    </div>
  );
};

export default forwardRef(ConfigSubprocess);
