import React, { useEffect, useState } from 'react';
import { makeStyles, Theme } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import { PageHeader, Button, message, Steps, Space, Card, Dropdown, Menu } from 'antd';
import { Link, history } from 'umi';
import './index.less';
import { getReadInfo, menuList, updateReadStatus } from './service/service';
import { getProName, getSessionRoleData, getProTypeCode, getDefId, getPurchaseCanOperate, getReturnURL, getProId, getProMethod } from '@/utils/session';
import { Step, StepButton, StepLabel, Stepper, Toolbar, Popover, Typography } from '@material-ui/core';
import { isEmpty } from '@/utils/CommonUtils';
import { CustomerServiceTwoTone } from '@ant-design/icons';

const useStyles = makeStyles((theme: Theme) => ({
  root: {
    flexGrow: 1,
    width: '100%',
    backgroundColor: theme.palette.background.paper,
  },
  popover: {
    pointerEvents: 'none',
  },
  paper: {
    padding: theme.spacing(1),
  },
}));

function getUrlRelativePath() {
  let url = document.location.toString();
  let arrUrl = url.split("//");
  let start = arrUrl[1].indexOf("/");
  let relUrl = arrUrl[1].substring(start);
  return relUrl;
}


const Promenu: React.FC<{}> = () => {
  //获取采购方式
  const MethodDict = getProMethod();
  const classes = useStyles();
  //流程数据
  const [data, setData] = React.useState<any>([]);
  //角色
  const randerRole = getSessionRoleData().roleCode;
  //总步骤条数
  const [progress, setProgress] = useState<any>();
  //当前步骤条数
  const [current, setCurrent] = useState<any>();
  const [buttonValue, setButtonValue] = useState<any>();
  const url = getUrlRelativePath();
  const projectId = getProId();
  const defId = getDefId();
  //项目名称
  const [proName, setProName] = useState<string>("");
  //收藏状态 0-已收藏 d-未收藏
  const [subStatus, setSubStatus] = useState<string | null>(null);
  //收藏数据
  const [subData, setSubData] = useState<any>();
  //收藏loading
  const [subLoading, setSubLoading] = useState<boolean>(false);

  const [anchorEl, setAnchorEl] = React.useState<HTMLElement | null>(null);

  const [anchorName, setAnchorName] = useState<string>("");
  const scrollButtonsDesktop = document.getElementsByClassName("MuiTabs-scrollButtonsDesktop").length;
  const open = Boolean(anchorEl);

  useEffect(() => {
    menuList({ defId: defId, projectId: projectId }).then(res => {
      if (res.code === 200) {
        let data = res.data;
        setData(data);
        setProgress(data.length);
        setCurrent(getCurrentLinks(data) + 1);
        setButtonValue(stepButtonClick(findURL(data)));
      }
    })
    getReadInfo({ projectId: projectId }).then(res => {
      if (res?.code == 200) {
        const data = res?.data;
        if (data) {
          setSubStatus(data.status);
          setSubData(data);
        } else {
          setSubStatus("");
        }
      }
    })
    setProName(getProName());
  }, []);
  /**
   * 获取当前环节
   */
  const getCurrentLinks = (data: any) => {
    let num = -1;
    for (let i = 0; i < data.length; i++) {
      //1、已进行；2、当前环节；3、未开启
      if (data[i].taskStatus === 1) {
        num = i;
      }
    }
    return num;
  }

  /**
   * 变更收藏状态
   * @param status 
   * @returns 
   */
  const changeSubStatus = (data: any, status: string) => {
    const params = {
      id: data ? data?.id : null,
      projectId: projectId,
      status
    }
    setSubLoading(true);
    updateReadStatus(params).then(res => {
      if (res?.code == 200) {
        setSubStatus(status);
        message.success(status == '0' ? '添加收藏成功' : '移除收藏成功')
      }
    }).finally(() => {
      setSubLoading(false);
    })
  }

  const stepButtonClick = (data: any) => {
    if (isEmpty(data) || isEmpty(data.funcList)) {
      return null;
    }
    const funcList = data.funcList;
    return loadFuncList(funcList);
  }
  /**
   * 生成button数据
   * @param funcList 
   * @returns 
   */
  const loadFuncList = (funcList: any[]) => {
    let arr: JSX.Element[] = [];
    if (isEmpty(funcList)) {
      return arr;
    }
    const url = getUrlRelativePath();
    arr = funcList.map((item: any, index: number) =>
      <Button key={index} size="small" onClick={() => clickEnter(funcList, item.funcUrl)} type={url === item.funcUrl ? "primary" : "default"}>
        {item.funcName}
      </Button>
    );
    return arr;
  }
  /**
   * 进入页面
   * @param funcList 
   * @param funcUrl 
   */
  const clickEnter = (funcList: any[], funcUrl: string) => {
    history.push(funcUrl);
    setButtonValue(loadFuncList(funcList));
  }

  /**
   * 查找跟当前页面匹配的值（url）
   * @param data 
   * @returns 
   */
  const findURL = (data: any[]) => {
    if (isEmpty(data)) {
      return null;
    }
    for (const item of data) {
      for (const i of item.funcList) {
        if (i.funcUrl === url) {
          return item;
        }
      }
    }
    return null;
  }

  const getFuncName = (data: any) => {
    const funcList = data.funcList;
    if (isEmpty(funcList)) {
      return "";
    }
    const names = funcList.map((item: any) => item.funcName);
    return names.join(" | ");
  }

  const handlePopoverOpen = (event: React.MouseEvent<HTMLElement, MouseEvent>, data: any) => {
    setAnchorName(getFuncName(data));
    setAnchorEl(event.currentTarget);
  };

  const handlePopoverClose = () => {
    setAnchorEl(null);
  };
  const initChatUI = () => { //智慧客服
    if(MethodDict!='procurement_mode_6' && MethodDict!='procurement_mode_7' && window.location.pathname.indexOf('BidEvaluation')!=-1){
      message.warn('非谈判类项目【评标】阶段禁止沟通')
    }else{
      var tempForm = document.getElementById('tempForm_CustomerService') as HTMLFormElement
      if(tempForm){
        var hideInput = document.getElementById('tempInput_CustomerService') as HTMLInputElement
        if(hideInput){
          hideInput.value= window.location.pathname
        }else{
          hideInput = document.createElement("input")
          hideInput.id = 'tempInput_CustomerService'
          hideInput.type="hidden"
          hideInput.name= 'sceneUrl'
          hideInput.value= window.location.pathname
          tempForm.appendChild(hideInput)
        }
        tempForm.submit();
      }
    }
  }
  return (
    <div key='promenuDiv1' style={{ borderRadius: "6px", overflow: "hidden" }}>
      <div key='promenuDiv2' className="site-page-header-ghost-wrapper" style={{ background: '#ffffff' }}>
        <PageHeader
          title="项目名称"
          subTitle={proName}
          extra={[
            (randerRole == 'ebtp-supervision' && subStatus == "0")
              ? <Button key="qxdy" disabled={subLoading} onClick={() => changeSubStatus(subData, "d")}>移除收藏</Button> : null,
            (randerRole == 'ebtp-supervision' && (subStatus == "d" || subStatus == ""))
              ? <Button key="daiyue" disabled={subLoading} onClick={() => changeSubStatus(subData, "0")}>添加收藏</Button> : null,
            (randerRole == 'ebtp-agency-project-manager' || randerRole == 'ebtp-purchase' || randerRole == 'ebtp-supervision')
              ? <Button key="jiandang" onClick={() => history.push("/Project/ProjectManage/ProjectManager/ProjectInformationManagement")}>项目建档</Button> : null,
            (randerRole == 'ebtp-agency-project-manager' || randerRole == 'ebtp-purchase' || randerRole == 'ebtp-supervision') && defId != 'inquiry'
              ? <Button key="guidang" onClick={() => {
                history.push("/ProjectLayout/Archive/projectArchive")
                setButtonValue(stepButtonClick(data?.[data?.length - 1]))
              }}>项目归档</Button> : null,
            <Button key="customerservice" onClick={() =>{
              initChatUI() //智慧客服
            }} icon={<CustomerServiceTwoTone />}>我要咨询</Button>,
            ((randerRole == 'ebtp-agency-project-manager' || randerRole == 'ebtp-purchase' || randerRole == 'ebtp-supervision') && MethodDict != "procurement_mode_7")
              ? <Button key="manageyiyi" onClick={() => history.push("/Project/ProjectManage/ProjectManager/ObjectionComplaint")}>异议投诉</Button> : null,
            (randerRole == 'ebtp-supplier' && MethodDict != "procurement_mode_7")
              ? <Button key="supplieryiyi" onClick={() => history.push("/Project/ProjectManage/Supplier/ObjectionComplaint")}>异议投诉</Button> : null,
            <Button key="fanhui1" type="primary" onClick={() => history.push(getReturnURL())}>返回</Button>
            // randerRole == 'ebtp-agency-project-manager' ? <Button key="fanhui1" type="primary"><Link to={`/BidManage/ProjectList?proTypeCode=${getProTypeCode()}`}>返回</Link></Button> : null,
            // randerRole == 'ebtp-purchase' ? (getPurchaseCanOperate() != null && getPurchaseCanOperate() != undefined ? <Button key="fanhui1" type="primary"><Link to={`/Project/EntrustAssign/ProjectManager/PurchasingManagerEnquiries`}>返回</Link></Button>
            //   : <Button key="fanhui1" type="primary"><Link to={`/BidManage/ProjectList?proTypeCode=${getProTypeCode()}`}>返回</Link></Button>) : null,
            // randerRole == 'ebtp-supplier' ? <Button key="fanhui2" type="primary"><Link to={`/BidManage/ProjectsInvolvedList?proTypeCode=${getProTypeCode()}`}>返回</Link></Button> : null,
            // randerRole == 'ebtp-auction-manager' ? <Button key="fanhui3" type="primary"><Link to={`/Auction/AuctionManagerProject`}>返回</Link></Button> : null
          ]}
        >
        </PageHeader>
      </div>
      <div key='promenuDiv3' className={classes.root}>
        <AppBar position="static" color="default" style={{ background: '#ffffff', boxShadow: 'none' }}>
          <Tabs
            variant="scrollable"
            scrollButtons="auto"
            indicatorColor="primary"
            // textColor="primary"
            value={false}
            key='promenuTab'
          >
            <Stepper
              className="horizontal-stepper"
              activeStep={current}
              style={{
                width: progress > 10 ? "" : '100%',
                marginLeft: scrollButtonsDesktop === 0 ? '24px' : void 0,
                // paddingTop: '34px'
              }}
            >

              {data.map((item: any, index: number) =>
                <Step
                  key={index + 'Step'}
                  onMouseEnter={(e) => handlePopoverOpen(e, item)}
                  onMouseLeave={handlePopoverClose}
                >
                  <StepButton
                    disabled={false}
                    key={index + 'StepButton'}
                    onClick={() => setButtonValue(stepButtonClick(item))}
                  >
                    {item.taskName}
                  </StepButton>
                </Step>
              )}

            </Stepper>
          </Tabs>
          <Space
            style={{
              paddingLeft: scrollButtonsDesktop === 0 ? '24px' : '50px',
              paddingBottom: '8px'
            }}
          >
            {buttonValue}
          </Space>
        </AppBar>

        <Popover
          id="mouse-over-popover"
          className={classes.popover}
          classes={{
            paper: classes.paper,
          }}
          open={open}
          anchorEl={anchorEl}
          anchorOrigin={{
            vertical: 'top',
            horizontal: 'center',
          }}
          transformOrigin={{
            vertical: 'bottom',
            horizontal: 'center',
          }}
          onClose={handlePopoverClose}
        >
          {anchorName}
        </Popover>
      </div>
    </div>
  );
}

export default Promenu;