import React, { useEffect, useState, useRef, forwardRef, useImperativeHandle } from 'react';
import { Input, Select, Divider, Tooltip, message, Form, Button, Radio } from 'antd';
import { PlusOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { loadEventTypeTable, loadEventFields, loadFeedbackType } from '@/services/flow/flow';
import Fieldselection from '../../../../workFlow/flowNode/flowNodeComponents/nodeEditComponents/Fieldselection';
import styles from '../NodeModal.less';
const { Option } = Select;

const ConfigNodeMsg = (props, ref) => {
  const { nodeChage, editMsg, flowID } = props;
  const [form] = Form.useForm();
  const [eventTable, setEventTable] = useState([]); // 表名
  const [filedList, setFiledList] = useState([]); // 当前选择表的所有字段
  const [fieldList, setFieldList] = useState([]); // 当前选择库字段列表
  const [showField, setShowField] = useState(false); // 选择字段弹窗
  const [fieldName, setFieldName] = useState(); // 编辑的字段
  const [filedData, setFiledData] = useState([]); // 已选字段列表
  const [backType, setBackType] = useState([]); // 反馈类型

  const [nodeMsg, setNodeMsg] = useState({
    NodeName: '',
    NodeType: '',
    SerialNo: '',
    aheadHandle: 1,
    NodeHandling: 1,
    roleList: [],
    nodeDetail: {},
    RuleList: {},
    CarbonCopyPeopleList: [],
  });
  useImperativeHandle(ref, () => ({
    getParmar,
  }));
  useEffect(() => {
    form.resetFields();
    getTableName();
    // 获取反馈类型
    // getFeedbackName();
    getFormData();
  }, [editMsg]);
  const getParmar = () => form.getFieldsValue();
  // 获取表单回显
  const getFormData = () => {
    const { aheadHandle, NodeHandling } = editMsg;

    form.setFieldsValue({
      ...editMsg,
      aheadHandle: aheadHandle || aheadHandle === 0 ? aheadHandle : 1,
      NodeHandling: NodeHandling || NodeHandling === 0 ? NodeHandling : 1,
    });
    setNodeMsg(editMsg);
    if (!editMsg.TableName) {
      return;
    }
    loadEventFields({ eventTableName: editMsg.TableName }).then(res => {
      if (res.code === 0) {
        let initList = [];
        res.data.forEach(item => {
          item.root.forEach(ele => {
            initList.push(ele.fieldName);
          });
        });
        // 处理外部字段
        Object.keys(form.getFieldsValue()).forEach(key => {
          saveOutFieldsLength(key, initList);
        });
        setFiledList(initList);
      }
    });
  };
  // 获取表名
  const getTableName = () => {
    loadEventTypeTable({ flowNodeId: editMsg.ActivityId, NodeType: Number(editMsg.NodeType) }).then(
      res => {
        if (res.code === 0) {
          setEventTable(res.data);
        }
      },
    );
  };
  // 表切换
  const changTable = val => {
    loadEventFields({ eventTableName: val }).then(res => {
      if (res.code === 0) {
        let initList = [];
        res.data.forEach(item => {
          item.root.forEach(ele => {
            initList.push(ele.fieldName);
          });
        });
        // 处理外部字段
        Object.keys(form.getFieldsValue()).forEach(key => {
          saveOutFieldsLength(key, initList);
        });
        setFiledList(initList);
      }
    });
  };
  // 保存外部字段个数
  const saveOutFieldsLength = (key, initList) => {
    switch (key) {
      case 'Fields':
        form.setFieldsValue({ OutFields: dealExternal(key, initList) });
        break;
      case 'SeeFields':
        form.setFieldsValue({ OutSeeFields: dealExternal(key, initList) });
        break;
      default:
        break;
    }
  };
  // 处理外部字段
  const dealExternal = (fileds, list) => {
    let isExternal;
    let externalLength = 0;
    if (form.getFieldValue(fileds)) {
      form
        .getFieldValue(fileds)
        .split(',')
        .forEach(item => {
          isExternal = list.some(val => val === item);
          if (!isExternal && item !== '') {
            // eslint-disable-next-line no-plusplus
            externalLength++;
          }
        });
    }
    return externalLength;
  };
  // 字段配置
  const deployField = val => {
    let value = form.getFieldsValue(true);
    if (!value.TableName) {
      message.error('请先选择表');
      return;
    }
    setFieldName(val);
    loadEventFields({ eventTableName: value.TableName }).then(res => {
      if (res.code === 0) {
        let defaultCheckedList = value[val] ? value[val].split(',') : [];

        // 保存所有的字段用于右侧显示
        setFiledData(defaultCheckedList);
        let allFields = []; // 所有得字段用来判断是否为外部字段
        // 处理树形结构
        let checkList = res.data.map(item => {
          let plainOptions = [];
          // 存入没个组得字段
          item.root.forEach(ele => {
            plainOptions = [...plainOptions, ele.fieldName];
          });
          // 存所有得字段
          allFields = [...allFields, ...plainOptions];
          return {
            groupName: item.groupName,
            plainOptions,
            defaultCheckedList: [],
          };
        });
        let externalFields = {
          groupName: '外部字段',
          indeterminate: false,
          checkAll: true,
          plainOptions: [],
          defaultCheckedList: [],
        }; // 外部字段
        defaultCheckedList.forEach(item => {
          // 添加外部字段
          let isExternal = allFields.some(checkName => checkName === item);
          if (!isExternal) {
            externalFields.plainOptions.push(item);
            externalFields.defaultCheckedList.push(item);
          }
          checkList.forEach(element => {
            // 当前得模块是否有当前字段
            let indeterminate = element.plainOptions.some(checkName => checkName === item);
            // 处理已选中的字段
            if (indeterminate) {
              element.defaultCheckedList.push(item);
            }
            if (
              element.defaultCheckedList.length > 0 &&
              element.defaultCheckedList.length < element.plainOptions.length
            ) {
              element.indeterminate = true;
            } else {
              element.indeterminate = false;
            }
            // 处理是否全选字段
            if (element.defaultCheckedList.length === element.plainOptions.length) {
              element.checkAll = true;
            } else {
              element.checkAll = false;
            }
          });
        });
        // 添加外部字段
        if (externalFields.plainOptions.length > 0) {
          checkList.push(externalFields);
        }
        setFieldList(checkList);
        setTimeout(() => {
          setShowField(true);
        }, 0);
      }
    });
  };
  // 字段修改后回调函数
  const setFiled = val => {
    let Fields = '';
    val.forEach((item, index) => {
      if (index === val.length - 1) {
        Fields = `${Fields + item}`;
      } else {
        Fields = `${Fields + item},`;
      }
    });
    let obj = {};
    obj[fieldName] = Fields;
    console.log(obj, fieldName, filedList, 'ojoafds');
    nodeChage(fieldName, Fields);
    form.setFieldsValue(obj);
    saveOutFieldsLength(fieldName, filedList);
    setShowField(false);
  };
  // 获取反馈类型
  const getFeedbackName = () => {
    loadFeedbackType().then(res => {
      if (res.code === 0) {
        setBackType(res.data);
      }
    });
  };
  // 节点配置表单监听
  const changeValue = (changedFields, allFields) => {
    // 新增节点时节点名称跟别名同步
    if (changedFields[0].name[0] === 'NodeName') {
      nodeChage('NodeAliasName', changedFields[0].value);
    }
    nodeChage(changedFields[0].name[0], changedFields[0].value);
  };

  return (
    <div>
      <Divider
        orientation="left"
        style={{
          borderTopColor: '#99bbe8',
          color: '#15428b',
          fontWeight: 700,
          marginTop: '0px',
        }}
      >
        {nodeMsg.NodeType === '20' || nodeMsg.NodeType === '21' || nodeMsg.NodeType === '22'
          ? '网关'
          : nodeMsg.NodeType === '30'
          ? `子流程`
          : `节点`}
        信息
      </Divider>
      <div className={styles.titleBox}>
        <p style={{ display: form?.getFieldValue('NodeType') === '30' ? 'block' : 'none' }}>
          在主流程流转过程中可以创建一个新的流程并执行，子流程结束后返回主流程继续运行。
        </p>
        {/* 条件网关 */}
        <p style={{ display: form?.getFieldValue('NodeType') === '20' ? 'block' : 'none' }}>
          条件网关：客户端填写表单内容，根据设置的条件规则以及出口的目标节点，进行全规则匹配，确定最终流转节点。
        </p>
        {/* 汇合网关 */}
        <p style={{ display: form?.getFieldValue('NodeType') === '21' ? 'block' : 'none' }}>
          汇合网关：等待所有的入口分支流程全部完成，自动移交到下一节点，汇合网关支持规则配置。
        </p>
        {/* 并行网关 */}
        <p style={{ display: form?.getFieldValue('NodeType') === '22' ? 'block' : 'none' }}>
          并行网关：根据网关的连接情况，强制所有出口分支流程必须流转。
        </p>
      </div>
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        onFieldsChange={changeValue}
        labelAlign="left"
      >
        {/* <Form.Item label="排序" name="SerialNo" rules={[{ required: true, message: '请输入排序' }]}>
          <Input placeholder="请输入序号" disabled />
        </Form.Item> */}
        {/* 第一次填写显示，如果是网关、子节点一直显示 */}
        <Form.Item
          label={`${
            nodeMsg.NodeType === '20' || nodeMsg.NodeType === '21' || nodeMsg.NodeType === '22'
              ? '网关'
              : nodeMsg.NodeType === '30'
              ? `流程`
              : '节点'
          }名称`}
          name="NodeName"
          rules={[{ required: true, message: '请输入名称' }]}
        >
          <Input
            disabled={
              editMsg.ActivityId &&
              nodeMsg.NodeType !== '20' &&
              nodeMsg.NodeType !== '21' &&
              nodeMsg.NodeType !== '22' &&
              nodeMsg.NodeType !== '30'
            }
            placeholder={`请输入${
              nodeMsg.NodeType === '20' || nodeMsg.NodeType === '21' || nodeMsg.NodeType === '22'
                ? '网关'
                : '节点'
            }名称`}
          />
        </Form.Item>

        <div style={{ display: 'none' }}>
          <Form.Item label="检查前面在办" name="aheadHandle">
            <Select>
              <Option value={1}>前面有在办不能移交</Option>
              <Option value={0}>前面有在办可以移交</Option>
            </Select>
          </Form.Item>
        </div>

        <div
          style={{
            display:
              editMsg.NodeType === '20' ||
              editMsg.NodeType === '21' ||
              editMsg.NodeType === '22' ||
              editMsg.NodeType === '30'
                ? 'none'
                : 'block',
          }}
        >
          <Form.Item
            style={{
              display: editMsg.ActivityId ? 'flex' : 'none',
            }}
            label="展示名称"
            name="NodeAliasName"
          >
            <Input placeholder="请输展示名称" />
          </Form.Item>
          <Form.Item
            label="移交方式"
            name="Handover"
            style={{
              display: editMsg.NodeType === '2' ? 'none' : 'flex',
            }}
          >
            <Radio.Group>
              <Radio value="移交选择人">
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  移交选择人
                  <Tooltip title="根据人员选择面板，自主选择移交的人员">
                    <InfoCircleOutlined style={{ color: '#1890ff', marginLeft: '3px' }} />
                  </Tooltip>
                </div>
              </Radio>
              <Radio
                value="自处理"
                style={{
                  display: editMsg.NodeType === '1' ? 'none' : 'flex',
                }}
              >
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  自处理
                  <Tooltip title="下一个节点，默认由自己继续办理">
                    <InfoCircleOutlined style={{ color: '#1890ff', marginLeft: '3px' }} />
                  </Tooltip>
                </div>
              </Radio>
              <Radio value="移交默认人">
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  移交默认人
                  <Tooltip title="自动移交给权限配置中的默认承办人">
                    <InfoCircleOutlined style={{ color: '#1890ff', marginLeft: '3px' }} />
                  </Tooltip>
                </div>
              </Radio>
              <Radio
                value="移交发起人"
                style={{ display: editMsg.NodeType === '1' ? 'none' : 'flex' }}
              >
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  移交发起人
                  <Tooltip title="自动移交给流程发起人">
                    <InfoCircleOutlined style={{ color: '#1890ff', marginLeft: '3px' }} />
                  </Tooltip>
                </div>
              </Radio>
              <Radio value="跨站移交">
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  跨站移交
                  <Tooltip title="人员选择面板，会忽略当前处理站点，展示配置权限所有人员">
                    <InfoCircleOutlined style={{ color: '#1890ff', marginLeft: '3px' }} />
                  </Tooltip>
                </div>
              </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label={
              editMsg.NodeType === '1' ? (
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  {/* <Tooltip title="首节点的表必须包含事件编号和工单编号">
                    <InfoCircleOutlined style={{ color: '#1890ff', marginLeft: '3px' }} />
                  </Tooltip> */}
                  节点表名
                </div>
              ) : (
                <div>节点表名</div>
              )
            }
            name="TableName"
            rules={[{ required: true, message: '请选择节点表名' }]}
          >
            <Select placeholder="请选择节点表名" onChange={changTable} showSearch>
              {eventTable.map(item => (
                <Option value={item.Name} key={item.Name}>
                  {item.Name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label={
              <div className={styles.formData_label}>
                {form.getFieldValue('OutFields') ? (
                  <Tooltip title={`外部字段${form.getFieldValue('OutFields')}个`}>
                    <InfoCircleOutlined style={{ color: 'red', padding: '0.2rem 0.2rem 0 0' }} />
                  </Tooltip>
                ) : (
                  ''
                )}
                <span style={{ marginRight: '4px', color: 'red' }}>*</span>
                <span>字段编辑</span>
              </div>
            }
          >
            <div className={styles.filedListItem}>
              <Tooltip title={form.getFieldValue('Fields')}>
                <Form.Item
                  name="Fields"
                  style={{ marginBottom: 0, width: '100%' }}
                  rules={[{ required: true }]}
                >
                  <Input
                    placeholder="请选编辑字段"
                    readOnly
                    onClick={() => {
                      deployField('Fields');
                    }}
                  />
                </Form.Item>
              </Tooltip>
              <Button
                style={{ margin: 0, borderLeft: 0 }}
                icon={<PlusOutlined />}
                onClick={() => {
                  deployField('Fields');
                }}
              />
            </div>
          </Form.Item>

          {/* <Form.Item label="前端视图" name="WebPage">
            <Input placeholder="请配置前端视图" />
          </Form.Item>
          <Form.Item label="反馈类型" name="FeedbackName">
            <Select placeholder="请选择反馈类型" allowClear>
              {backType.map(item => (
                <Option value={item.value} key={item.value}>
                  {item.value}
                </Option>
              ))}
            </Select>
          </Form.Item> */}
        </div>
        <div
          style={{
            display:
              editMsg.NodeType === '1' ||
              editMsg.NodeType === '2' ||
              editMsg.NodeType === '20' ||
              editMsg.NodeType === '21' ||
              editMsg.NodeType === '22' ||
              editMsg.NodeType === '30'
                ? 'none'
                : 'block',
          }}
        >
          <Form.Item label="办理方式" name="NodeHandling">
            <Select>
              <Option value={1}>多人接收，一人办理（抢占）</Option>
              <Option value={0}>多人接收，多人办理（会签）</Option>
              <Option value={2}>一人接收，一人办理（独占）</Option>
            </Select>
          </Form.Item>
        </div>
      </Form>
      {/* 字段集选择 */}
      <Fieldselection
        visible={showField}
        handleCancel={() => setShowField(false)}
        fieldList={fieldList}
        onSubumit={val => setFiled(val)}
        filedData={filedData}
      />
    </div>
  );
};

export default forwardRef(ConfigNodeMsg);
