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 } from 'antd';
import AddCondition from '../../components/judgeModal';
import RenderJudge, { JudgeType } from '../../components/judgeComponent';
import { TYPE } from '../auditNode/mapServe';

// 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;
  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 = {}, formItems } = 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 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);
  };

  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);
          }}
        />
        <AddCondition
          items={formItems}
          formItems={nodeConfig.formItems}
          onOk={(values: FormItem[]) => {
            console.log('===formItems===', values);
            let newFormItems = [];
            let oldFormItems = JSON.parse(nodeConfig.formItems || '[]');
            values.forEach(item => {
              let id = item.props.id;
              // 判断是否含有旧的item
              let oldItem = oldFormItems.find(formItem => formItem.props.id == id);
              if (oldItem) {
                newFormItems.push(oldItem);
              } else {
                newFormItems.push(item);
              }
            });
            onNodeConfigChange('formItems', JSON.stringify(newFormItems));
          }}
        />
        <RenderJudge
          formItems={nodeConfig.formItems}
          onChange={(values: FormItem[]) => {
            console.log('===formItems===', values);
            onNodeConfigChange('formItems', JSON.stringify(values));
          }}
        />
      </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 }) => ({ auditList: xflow.auditList, formItems: xflow.formData }))(
  RecthServe
);
