import React, { useState, useEffect } from 'react';
import { FlowchartFormWrapper } from '@antv/xflow';
import { Position, Size, ColorPicker, InputNumberFiled, InputFiled, SelectField } from '../fields';
import { PREFIX } from '../constants';
import { connect } from 'dva';
import { UnityAction } from '@/utils/utils';
import { Button, Select, TreeSelect } from 'antd';

const { Option } = Select;

export const enum TYPE {
  AUDIT = 1,
  INITIATOR,
  COPYMAN,
}

export const typeOption = [
  { label: '审批人', value: TYPE.AUDIT },
  { label: '发起人', value: TYPE.INITIATOR },
  { label: '抄送人', value: TYPE.COPYMAN },
];

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;
  roleID: number;
  audits: { type: string; value: number; origin?: string | number; name?: string }[];
}

const Component = (props: any) => {
  const defaultConfig = {
    type: TYPE.AUDIT,
  };
  const { config, plugin = {}, depUserTree, roleList } = props;
  const { updateNode } = plugin;

  const [nodeConfig, setNodeConfig] = useState<IConfig>({
    ...defaultConfig,
    ...config,
  });
  const onNodeConfigChange = (key: string, value: number | string | object) => {
    if (key) {
      setNodeConfig({
        ...nodeConfig,
        [key]: value,
      });
      updateNode({
        [key]: value,
      });
    } else if (value instanceof Object) {
      setNodeConfig({
        ...nodeConfig,
        ...value,
      });
      updateNode({
        ...value,
      });
    }
  };

  const handleTreeChange = (values: (string | number)[]) => {
    const newValues = values.map(cur => {
      if (typeof cur == 'string' && cur.includes('||')) {
        return { type: 'user', value: Number(cur.split('||')[0]), origin: cur };
      } else {
        return { type: 'dep', value: cur, origin: cur };
      }
    });
    onNodeConfigChange('audits', newValues);
  };

  const onSave = () => {
    UnityAction.emit('NODE_SAVE', nodeConfig);
  };
  useEffect(() => {
    setNodeConfig({
      ...defaultConfig,
      ...config,
    });
  }, [config]);

  return (
    <div className={`${PREFIX}-panel-body`}>
      <div className={`${PREFIX}-panel-group`}>
        <h5>内容</h5>
        <InputFiled
          label="标题"
          value={nodeConfig.label}
          onChange={value => {
            onNodeConfigChange('label', value);
          }}
        />
        <SelectField
          label="节点类型"
          value={nodeConfig.type}
          onChange={value => {
            onNodeConfigChange('type', value);
          }}
          options={typeOption}
        />
      </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);
          }}
        />
        <InputNumberFiled
          label="消息数量"
          value={nodeConfig.count}
          onChange={value => {
            onNodeConfigChange('count', value);
          }}
        />
        <div className={`${PREFIX}-node-text-style`}>
          <InputNumberFiled
            label="字号"
            value={nodeConfig.fontSize}
            width={68}
            onChange={value => {
              onNodeConfigChange('fontSize', value);
            }}
          />
          <ColorPicker
            value={nodeConfig.fontFill}
            onChange={(value: string) => {
              onNodeConfigChange('fontFill', value);
            }}
          />
        </div>
        <div className="group">
          <label>{typeOption.find(item => item.value == nodeConfig.type)?.label || '审批人'}</label>
          {nodeConfig.type != TYPE.AUDIT ? (
            <TreeSelect
              showSearch
              multiple
              allowClear
              defaultValue={nodeConfig.audits?.map(item => item.origin)}
              style={{ width: '80%' }}
              placeholder="请选择"
              treeData={depUserTree}
              onChange={values => {
                handleTreeChange(values);
              }}
            />
          ) : (
            <Select
              showSearch
              style={{ width: '100%' }}
              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
              onChange={value => {
                onNodeConfigChange('roleID', value);
              }}
            >
              {roleList &&
                roleList.map(item => (
                  <Option key={item.ID} value={item.ID + ''}>
                    {item.Name}
                  </Option>
                ))}
            </Select>
          )}
        </div>
      </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, flow }) => ({
  auditList: xflow.auditList,
  depUserTree: flow.depUserTree,
  roleList: flow.roleList,
}))(RecthServe);
