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, Radio, RadioChangeEvent, Select, TreeSelect } from 'antd';

const { Option } = Select;

export const enum TYPE {
  INITIATOR = 1,
  AUDIT,
  JUDGE,
  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;
  initiator: { type: string; value: number; origin?: string | number; name?: string }[];
  //审批人目前只支持单选角色或者单选人
  audits: { type: string; value: number; origin?: string | number; name?: string }[];
}

export const enum IDTYPE {
  DEP = 'dep',
  USER = 'user',
  ROLE = 'role',
}

const Component = (props: any) => {
  const defaultConfig = {
    type: TYPE.AUDIT,
  };
  const { config, plugin = {}, depUserTree, roleList, userList } = props;
  const { updateNode } = plugin;
  const [isRole, setIsRole] = useState(1); ///按角色还是个人

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

  useEffect(() => {
    const bool = nodeConfig.audits?.some(item => item.type == IDTYPE.USER) ? 0 : 1;
    console.log(bool);
    setIsRole(bool);
  }, []);
  console.log('===================', nodeConfig);

  const handleTreeChange = (values: (string | number)[]) => {
    const newValues = values.map(cur => {
      if (typeof cur == 'string' && cur.includes('||')) {
        return { type: IDTYPE.USER, value: Number(cur.split('||')[0]), origin: cur };
      } else {
        return { type: IDTYPE.DEP, value: cur, origin: cur };
      }
    });
    onNodeConfigChange('initiator', 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>
        <InputField
          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);
          }}
        />
        <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>
        {nodeConfig.type != TYPE.AUDIT && (
          <div className="group">
            <label>{typeOption.find(item => item.value == nodeConfig.type)?.label || '-'}</label>
            <TreeSelect
              showSearch
              multiple
              allowClear
              value={nodeConfig.initiator?.map(item => item.origin)}
              style={{ width: '80%' }}
              placeholder="请选择"
              treeData={depUserTree}
              onChange={values => {
                handleTreeChange(values);
              }}
            />
          </div>
        )}

        {nodeConfig.type == TYPE.AUDIT && (
          <div className={`${PREFIX}-panel-group`}>
            <h5>审批人</h5>
            <Radio.Group
              onChange={(e: RadioChangeEvent) => {
                console.log(e.target.value);
                setIsRole(e.target.value);
                onNodeConfigChange('audits', []);
              }}
              value={isRole}
            >
              <Radio value={1}>发起人自选</Radio>
              <Radio value={0}>指定人</Radio>
            </Radio.Group>
            <div className="group">
              {isRole ? (
                <>
                  <label>审批角色</label>
                  <Select
                    showSearch
                    style={{ width: '100%' }}
                    value={nodeConfig.audits?.map(item => item.value)}
                    filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                    onChange={value => {
                      onNodeConfigChange('audits', [{ type: IDTYPE.ROLE, value: Number(value) }]);
                    }}
                  >
                    {roleList &&
                      roleList.map(item => (
                        <Option key={item.ID} value={item.ID}>
                          {item.Name}
                        </Option>
                      ))}
                  </Select>
                </>
              ) : (
                <>
                  <label>审批人</label>
                  <Select
                    showSearch
                    style={{ width: '100%' }}
                    value={nodeConfig.audits?.map(item => item.value)}
                    onChange={value => {
                      onNodeConfigChange('audits', [{ type: IDTYPE.USER, value: Number(value) }]);
                    }}
                    filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                  >
                    {(userList || []).map(item => (
                      <Option key={item.ID} value={item.ID}>
                        {item.CName}
                      </Option>
                    ))}
                  </Select>
                </>
              )}
            </div>
          </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, user }) => ({
  auditList: xflow.auditList,
  depUserTree: user.depUserTree,
  roleList: user.roleList,
  userList: user.list,
}))(RecthServe);
