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,
  InputNumber,
} 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: {
    label: string; //描述
    type: string;
    value: number;
    origin?: string | number;
    name?: string;
  }[];
  //审批人目前只支持单选角色或者单选人
  audits: {
    label: string; //描述
    type: string;
    value: number;
    origin?: string | number;
    name?: string;
    is_cc: number;
  }[];
}

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

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(() => {
    let bool = 1;
    if (nodeConfig.audits?.length > 0)
      switch (nodeConfig.audits[0].type) {
        case IDTYPE.USER:
          bool = 0;
          break;
        case IDTYPE.ROLE:
          bool = 1;
          break;
        case IDTYPE.LEADER:
          bool = 2;
          break;
      }
    console.log(bool);
    setIsRole(bool);
  }, []);

  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, is_cc: 1 };
      }
    });
    onNodeConfigChange('initiator', newValues);
  };

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

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

  const renderAuditSelect = (key: Number) => {
    switch (key) {
      case 0:
        return (
          <>
            <label>审批人</label>
            <Select
              showSearch
              mode="multiple"
              style={{ width: '100%' }}
              value={nodeConfig.audits?.map((item) => item.value)}
              onChange={(value) => {
                const list = value.map((id) => {
                  return {
                    type: IDTYPE.USER,
                    label:
                      nodeConfig.label == '动作节点'
                        ? '抄送人'
                        : nodeConfig.label,
                    value: Number(id),
                  };
                });
                onNodeConfigChange('audits', list);
              }}
              filterOption={(input, option) =>
                option.props.children.indexOf(input) >= 0
              }
            >
              {(userList || []).map((item) => (
                <Option key={item.ID} value={item.ID}>
                  {item.CName}
                </Option>
              ))}
            </Select>
          </>
        );
      case 1:
        return (
          <>
            <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,
                    label:
                      nodeConfig.label == '动作节点'
                        ? '审批人'
                        : nodeConfig.label,
                    value: Number(value),
                  },
                ]);
              }}
            >
              {roleList &&
                roleList.map((item) => (
                  <Option key={item.ID} value={item.ID}>
                    {item.Name}
                  </Option>
                ))}
            </Select>
          </>
        );
      case 2:
        return (
          <>
            <label>多级审批</label>
            <InputNumber
              style={{ width: '100%' }}
              value={
                nodeConfig.audits?.length > 0 ? nodeConfig.audits[0].value : 0
              }
              onChange={(value) => {
                onNodeConfigChange('audits', [
                  {
                    type: IDTYPE.LEADER,
                    label:
                      nodeConfig.label == '动作节点'
                        ? '审批人'
                        : nodeConfig.label,
                    value: Number(value),
                  },
                ]);
              }}
            />
          </>
        );
    }
  };

  return (
    <div className={`${PREFIX}-panel-body`}>
      <div className={`${PREFIX}-panel-group`}>
        <h5>内容</h5>
        <InputField
          label="标题"
          value={nodeConfig.label}
          onChange={(value) => {
            onNodeConfigChange('', {
              label: value,
              audits:
                nodeConfig?.audits?.length > 0
                  ? [{ ...(nodeConfig?.audits[0] || []), 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.INITIATOR && (
          <div className="group">
            <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 value={2}>部门主管</Radio>
            </Radio.Group>
            <div className="group">{renderAuditSelect(isRole)}</div>
          </div>
        )}
      </div>
      {nodeConfig.type == TYPE.COPYMAN && (
        <div className="group">
          <label>抄送人:</label>
          <Select
            showSearch
            mode="multiple"
            style={{ width: '80%' }}
            value={nodeConfig.audits?.map((item) => item.value)}
            onChange={(value) => {
              const list = value.map((id) => {
                return {
                  type: IDTYPE.USER,
                  label:
                    nodeConfig.label == '动作节点'
                      ? '抄送人'
                      : nodeConfig.label,
                  value: Number(id),
                  is_cc: 1,
                };
              });
              onNodeConfigChange('audits', list);
            }}
            filterOption={(input, option) =>
              option?.props?.children.indexOf(input) >= 0
            }
          >
            {(userList || []).map((item) => (
              <Option key={item.ID} value={item.ID}>
                {item.CName}
              </Option>
            ))}
          </Select>
        </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);
