import React, { useState, useEffect, useMemo } from 'react';
import { FlowchartFormWrapper } from '@antv/xflow';
import {
  Position,
  Size,
  ColorPicker,
  InputNumberField,
  InputField,
  SelectField,
} from '../fields';
import { PREFIX } from '../constants';
import { connect } from 'umi';
import { UnityAction } from '@/utils/utils';
import { Button, Card } from 'antd';
import AddCondition from '../../components/judgeModal';
import RenderJudge, { JudgeType } from '../../components/judgeComponent';
import { TYPE } from '../auditNode/mapServe';
import { CloseOutlined, PlusOutlined } from '@ant-design/icons';

// export const enum TYPE {
//   AUDIT,
//   INITIATOR,
//   COPYMAN,
// }

export const enum ComponentName {
  Inner = 'InnerContactField',
  Depart = 'DepartmentField',
  Select = 'DDSelectField',
  Money = 'MoneyField',
  MultiSelect = 'DDMultiSelectField',
  Number = 'NumberField',
}

export interface IConfig {
  label?: string;
  x?: number;
  y?: number;
  width?: number;
  height?: number;
  count?: number;
  fontSize?: number;
  fontFill?: string;
  fill?: string;
  stroke?: string;
  flow_id?: string;
  flow_node_id?: string;
  process_code?: string;
  type: TYPE;
  // 条件  【此字段存在是为了兼容旧格式】
  formItems: string;
  // 条件组 【新版用此字段】 formItems和formItemsOr同时只能存在一个
  formItemsOr: string[];
  priority?: number; //优先级
}

export interface FormItem {
  componentName: string;
  props: {
    label: string;
    id: string;
    options?: string[];
    required: boolean;
    placeholder?: string;
  };
  judge?: JudgeType;
}

const Component = (props: any) => {
  const { config, plugin = {}, formData } = props;
  const { updateNode } = plugin;

  // const formData: FormItem[] = [
  //   {
  //     componentName: 'InnerContactField',
  //     props: {
  //       label: '申请人',
  //       id: 'InnerContactField-JEQRQ5VH',
  //       required: true,
  //     },
  //   },
  //   {
  //     componentName: 'DepartmentField',
  //     props: {
  //       label: '选择部门',
  //       id: 'DepartmentField_1VALX0GTRNVK0',
  //       required: true,
  //     },
  //   },
  //   {
  //     componentName: 'DDSelectField',
  //     props: {
  //       id: 'DDSelectField_LWFCJRK508W0',
  //       label: '文件类型',
  //       options: [
  //         '{"value":"新增|FT008","key":"option_1IXTB1VDV9EO0"}',
  //         '{"value":"补充|FT009","key":"option_1DVWNV9BNZNK0"}',
  //       ],
  //       required: true,
  //     },
  //   },
  //   {
  //     componentName: 'DDSelectField',
  //     props: {
  //       id: 'DDSelectField_21WUQ0OWR7R40',
  //       label: '是否外带',
  //       options: [
  //         '{"value":"是","key":"option_DUSP6XANFKO0"}',
  //         '{"value":"否","key":"option_CC5VQ63ZLJK0"}',
  //       ],
  //       required: true,
  //     },
  //   },
  //   {
  //     componentName: 'MoneyField',
  //     props: {
  //       id: 'MoneyField-JSCUC2GG',
  //       label: '文件金额（元）',
  //       placeholder: '请输入金额',
  //       required: true,
  //     },
  //   },
  // ];

  const [nodeConfig, setNodeConfig] = useState<IConfig>({
    ...config,
  });
  const formItemsGroup = nodeConfig.formItemsOr || [];

  const onNodeConfigChange = (key: string, value: number | string | object) => {
    if (key) {
      setNodeConfig({
        ...nodeConfig,
        [key]: value,
      });
      updateNode({
        type: TYPE.JUDGE,
        [key]: value,
      });
    } else if (value instanceof Object) {
      setNodeConfig({
        ...nodeConfig,
        ...value,
      });
      updateNode({
        type: TYPE.JUDGE,
        ...value,
      });
    }
  };

  const onSave = () => {
    UnityAction.emit('NODE_SAVE', nodeConfig);
  };

  const onAddConditionGroup = () => {
    onNodeConfigChange('formItemsOr', [...formItemsGroup, '[]']);
  };
  const onRemoveConditionGroup = (index: number) => {
    let tempGroup = [...formItemsGroup];
    tempGroup.splice(index, 1);
    onNodeConfigChange('formItemsOr', [...tempGroup]);
  };

  const onAddCondition = (values: FormItem[], index: number) => {
    const getFormItemsStr = (formItems: string) => {
      let newFormItems: FormItem[] = [];
      let oldFormItems = JSON.parse(formItems || '[]');
      values.forEach((item) => {
        let id = item.props.id;
        // 判断是否含有旧的item
        let oldItem = oldFormItems.find(
          (formItem: FormItem) => formItem.props.id == id,
        );
        if (oldItem) {
          newFormItems.push(oldItem);
        } else {
          newFormItems.push(item);
        }
      });
      return JSON.stringify(newFormItems);
    };
    let tempGroup = [...formItemsGroup];
    // 更新条件组
    tempGroup[index] = getFormItemsStr(tempGroup[index]);
    onNodeConfigChange('formItemsOr', tempGroup);
  };

  const renderCondition = () => {
    let Cards: any = [];
    formItemsGroup.forEach((formItems: string, index: number) => {
      Cards.push(
        <Card
          key={index}
          title={`条件组${index + 1}`}
          extra={
            <CloseOutlined onClick={() => onRemoveConditionGroup(index)} />
          }
        >
          <AddCondition
            items={formData}
            formItems={formItems}
            onOk={(values: FormItem[]) => onAddCondition(values, index)}
          />
          <RenderJudge
            formItems={formItems}
            onChange={(values: FormItem[]) => {
              let tempGroup = [...formItemsGroup];
              tempGroup[index] = JSON.stringify(values);
              onNodeConfigChange('formItemsOr', tempGroup);
            }}
          />
        </Card>,
      );
      if (index != formItemsGroup.length - 1) {
        Cards.push(<div>或</div>);
      }
    });
    return Cards;
  };

  useEffect(() => {
    setNodeConfig({
      ...config,
    });
  }, [config]);

  return (
    <div className={`${PREFIX}-panel-body`}>
      <div className={`${PREFIX}-panel-group`}>
        <h5>内容</h5>
        <InputField
          label="标题"
          value={nodeConfig.label}
          onChange={(value) => {
            onNodeConfigChange('label', value);
          }}
        />
      </div>
      <div className={`${PREFIX}-panel-group`}>
        <h5>样式</h5>
        <Position
          x={nodeConfig.x}
          y={nodeConfig.y}
          onChange={(key, value) => {
            onNodeConfigChange(key, value);
          }}
        />
        <Size
          width={nodeConfig.width}
          height={nodeConfig.height}
          onChange={(key, value) => {
            onNodeConfigChange(key, value);
          }}
        />
        <ColorPicker
          label="填充"
          value={nodeConfig.fill}
          onChange={(value: string) => {
            onNodeConfigChange('fill', value);
          }}
        />
        <ColorPicker
          label="边框"
          value={nodeConfig.stroke}
          onChange={(value: string) => {
            onNodeConfigChange('stroke', value);
          }}
        />
        <InputNumberField
          label="消息数量"
          value={nodeConfig.count}
          onChange={(value) => {
            onNodeConfigChange('count', value);
          }}
        />
        <div className={`${PREFIX}-node-text-style`}>
          <InputNumberField
            label="字号"
            value={nodeConfig.fontSize}
            width={68}
            onChange={(value) => {
              onNodeConfigChange('fontSize', value);
            }}
          />
          <ColorPicker
            value={nodeConfig.fontFill}
            onChange={(value: string) => {
              onNodeConfigChange('fontFill', value);
            }}
          />
        </div>
        <InputNumberField
          label="优先级"
          value={nodeConfig.priority}
          width={68}
          onChange={(value) => {
            onNodeConfigChange('priority', value);
          }}
        />

        <Button icon={<PlusOutlined />} onClick={() => onAddConditionGroup()}>
          新增条件组
        </Button>

        {renderCondition()}
      </div>

      <Button style={{ marginTop: 20 }} type="primary" onClick={onSave}>
        保存
      </Button>
    </div>
  );
};

function RecthServe(props: any) {
  return (
    <FlowchartFormWrapper {...props}>
      {(config, plugin) => (
        <Component {...props} plugin={plugin} config={config} />
      )}
    </FlowchartFormWrapper>
  );
}

export default connect(({ xflow }: any) => ({
  auditList: xflow.auditList,
  formData: xflow.formData,
}))(RecthServe);
