import React, { useEffect, useMemo, useState } from 'react';
import { queryUserListByRoleID, queryLeader } from '@/services/boom';
import { connect } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import { Popover, Radio, RadioChangeEvent, Spin, Steps } from 'antd';
import { useModel, useRequest } from '@umijs/max';

const { Step } = Steps;

enum TYPE {
  ROLE = 'role',
  USER = 'user',
  LEADER = 'leader',
}

const ApprovalProcess = (props: any) => {
  const {
    approvalProcess,
    leaderData,
    dispatch,
    onChange,
    roleList = [],
  } = props;
  const [selectUserList, setSelectUserList] = useState([]);
  const [curNodeIdx, setCurNodeIdx] = useState(-1);
  const [loading, setLoading] = useState(false);
  const { userList, run } = useModel('userList');

  const list = useMemo(() => {
    approvalProcess
      ?.filter((item: any) => item)
      .forEach((item: any) => {
        if (item.length > 1 && item[0].type == TYPE.USER) {
          item.forEach((curUser: any) => {
            curUser.name =
              userList?.find((user: any) => user.ID == curUser.value)?.CName ||
              '-';
          });
        } else if (item.length == 1 && item[0].type == TYPE.USER) {
          item[0].name =
            userList?.find((user: any) => user.ID == item[0].value)?.CName ||
            '-';
        } else if (item.length == 1 && item[0].nowType == TYPE.USER) {
          item[0].name =
            userList?.find((user: any) => user.ID == item[0].nowValue)?.CName ||
            '-';
        } else {
          item[0].name = null;
        }
      });
    return approvalProcess?.filter((item: any) => item);
  }, [approvalProcess]);

  const onStepsChange = async (current: any, list: any) => {
    setLoading(true);
    const itemNode = list[current][0];
    if (itemNode.type !== 'role') return;
    const data = await queryUserListByRoleID({ role_id: itemNode.value });
    setCurNodeIdx(current);
    setSelectUserList(data);
    setLoading(false);
  };

  const selectedUserId = ({ target: { value } }: RadioChangeEvent) => {
    //userId
    const name = userList?.find((user: any) => user.ID == value)?.CName || '-';
    const data = { nowType: TYPE.USER, nowValue: Number(value), name }; //type: TYPE.USER, value: Number(value)
    list[curNodeIdx][0] = { ...list[curNodeIdx][0], ...data };
    console.log([...list]);
    onChange?.([...list]);
  };

  const content = (
    <Spin spinning={loading}>
      <Radio.Group onChange={selectedUserId}>
        {selectUserList.map((item: any) => (
          // <Button onClick={() => selectedUserId(item.user_id)}>{item.c_name}</Button>
          <Radio.Button value={item.user_id}>{item.c_name}</Radio.Button>
        ))}
      </Radio.Group>
    </Spin>
  );

  const getLeaderContent = (length: any) => (
    <Steps
      progressDot
      current={-1}
      direction="vertical"
      items={leaderData
        ?.slice(0, length || 0)
        .map((leader: any) => ({ title: leader.CName }))}
    ></Steps>
  );

  useEffect(() => {
    dispatch({
      type: 'user/getRoleList',
    });
    run();
  }, []);

  return (
    <>
      <Steps
        current={-1}
        direction="vertical"
        onChange={(value) => onStepsChange(value, list)}
      >
        {list?.map((item: any, index: Number) =>
          item[0]?.type == TYPE.LEADER ? (
            <Step
              key={String(index)}
              icon={
                <Popover
                  placement="bottomLeft"
                  title="查看审批人"
                  content={getLeaderContent(item[0]?.value)}
                  overlayStyle={{ width: '300px' }}
                >
                  <PlusOutlined />
                </Popover>
              }
              title={`${Math.min(
                item[0]?.value,
                leaderData?.length,
              )}级主管审批`}
            />
          ) : (
            <Step
              key={String(index)}
              icon={
                <Popover
                  placement="bottomLeft"
                  title={'选择审批人'}
                  content={content}
                  trigger="click"
                  overlayStyle={{ width: '300px' }}
                >
                  <PlusOutlined />
                </Popover>
              }
              title={
                item[0]?.name ||
                `从${
                  roleList?.find((cur: any) => cur.ID == item[0]?.value)
                    ?.Name || '-'
                }选择`
              }
            />
          ),
        )}
      </Steps>
    </>
  );
};
export default connect(({ user }: any) => ({
  roleList: user.roleList,
}))(ApprovalProcess);
