import styles from './index.less';
import React, { useEffect, useState } from 'react';
import { OrgChartComponent } from '@/components/orgChart';
import * as d3 from 'd3';
import { TopBar } from '../components/topBar';
import ToolBar from '../components/toolBar';
import moment from 'moment';
import qs from 'qs';
import { message } from 'antd';

export default function userPage() {
  const [data, setData] = useState(null);
  const [progressTop, setProgressTop] = useState(50);
  let addNodeChildFunc = null;
  let orgChart = null;
  let progressBtnRef = null;
  let topBarSearchRequest = null;
  const [hasRight, setHasRight] = useState('');

  // 点击节点
  function onNodeClick(nodeId) {
    // alert('clicked ' + nodeId);
  }

  function onButtonClick(event, d) {
    if (d.children) {
      let idsList = [];
      d.children.forEach((item) => {
        if (item.data.hasChildren && !item._children) {
          idsList.push(item.data.id);
        }
      });

      if (idsList.length == 0) {
        return;
      }

      let idsStr = idsList.join(',');

      console.log('idsStr', idsStr);

      let api = '';
      if (topBarSearchRequest) {
        let request = { ...topBarSearchRequest, ids: idsStr };
        api =
          '/api/bs/hrmorganization/orgchart/asyncUserData' +
          qs.stringify(request, { addQueryPrefix: true });
      } else {
        api =
          '/api/bs/hrmorganization/orgchart/asyncUserData?fclass=0&root=0&date=' +
          moment(new Date()).format('YYYY-MM-DD') +
          '&ids=' +
          idsStr;
      }

      fetch(api)
        .then((res) => res.json())
        .then((data) => {
          if (data.data) {
            data.data.forEach((item) => {
              window.chart.addNode(item);
            });
          }
        });
    }
  }

  // 获取部门图片
  function getDepartmentImage() {
    let index = Math.floor(Math.random() * 8) + 1;
    return `./img/department/${index}.png`;
  }

  // 获取部门图片
  function getSubcompanyImage() {
    let index = Math.floor(Math.random() * 3) + 1;
    return `./img/subcompany/${index}.png`;
  }

  // 获取数据
  useEffect(() => {
    d3.json(
      // "/user/data"
      '/api/bs/hrmorganization/orgchart/userData?fclass=0&root=0&date=' +
        moment(new Date()).format('YYYY-MM-DD'),
    ).then((data) => {
      setData(data.data);
      setHasRight(data.hasRight);
    });
  }, [true]);

  // ButtonContent渲染
  const buttonContentRender = ({ node, state }) => {
    return `
        <div style="margin-left: 16px; margin-top: 10px;">
          <img src="./img/button_content.png" />
        </div>
      `;
  };

  // 节点宽度渲染
  const nodeWidthRender = (d) => {
    return 280;
  };

  const nodeHeightRender = (d) => {
    return 160;
  };

  // tool bar start
  const handleTopLayoutClick = (progressBtn) => {
    progressBtn.current.style.top = 50 + 'px';
    orgChart && orgChart.layout('top').render();
  };

  const handleLeftLayoutClick = (progressBtn) => {
    progressBtn.current.style.top = 50 + 'px';
    orgChart && orgChart.layout('left').render();
  };

  const handleZoomIn = (progressBtn) => {
    if (progressBtn) {
      let top = parseInt(progressBtn.current.style.top) - 10;
      if (top <= 0) {
        top = 30;
      }
      progressBtn.current.style.top = top + 'px';
    }
    orgChart && orgChart.zoomIn();
  };

  const handleZoomOut = (progressBtn) => {
    if (progressBtn) {
      let top = parseInt(progressBtn.current.style.top) + 10;
      if (top >= 100) {
        top = 70;
      }
      progressBtn.current.style.top = top + 'px';
    }
    orgChart && orgChart.zoomOut();
  };

  // tool bar end

  // top bar start

  function downloadPdf(chart) {
    chart.exportImg({
      save: false,
      onLoad: (base64) => {
        var pdf = new jsPDF();
        var img = new Image();
        img.src = base64;
        img.onload = function () {
          pdf.addImage(
            img,
            'JPEG',
            5,
            5,
            595 / 3,
            ((img.height / img.width) * 595) / 3,
          );
          pdf.save('chart.pdf');
        };
      },
    });
  }

  const handleExport = (type) => {
    if (type == 'png') {
      orgChart && orgChart.exportImg({ full: true });
    } else {
      orgChart && downloadPdf(orgChart);
    }
  };

  const handleSearch = (requestData) => {
    topBarSearchRequest = requestData;
    let api =
      '/api/bs/hrmorganization/orgchart/userData' +
      qs.stringify(requestData, { addQueryPrefix: true });
    fetch(api)
      .then((res) => res.json())
      .then((data) => {
        if (data.data && data.data.length > 0) {
          setData(data.data);
        } else {
          message.warning('暂无数据');
        }
      });
  };

  // top bar end

  const nodeContentRender = (d, i, arr, state) => {
    // 集团地址
    let companyUrl =
      '/spa/organization/static/index.html#/main/organization/group';
    // 分部地址
    let subcompanyUrl =
      '/spa/organization/static/index.html#/main/organization/companyExtend/';
    // 部门地址
    let departmentUrl =
      '/spa/organization/static/index.html#/main/organization/departmentExtend/';
    // 岗位地址
    let jobtitleUrl =
      '/spa/organization/static/index.html#/main/organization/jobExtend/';

    // 人员地址
    let userUrl = '/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/';

    // 通讯录
    let addressBookUrl = '/spa/hrm/index_mobx.html#/main/hrm/addressBook';

    if (d.data.ftype == 0 || d.data.ftype == 1 || d.data.ftype == 2) {
      return `<div>
          <div style="position: relative;">
            <img src="./img/user-card/card-label-start.png" />
            <span style="display: inline-block;
              position: absolute;
              left: 5px;
              top: -8px;
              background: #F7F9FD;
              z-index: 100;
              padding: 0px 10px; 
              font-size: 16px;
              font-family: Microsoft YaHei-Bold, Microsoft YaHei;
              font-weight: bold;
              color: #000000;
            " onclick="window.open('${
              d.data.ftype == 0
                ? companyUrl
                : d.data.ftype == 1
                ? subcompanyUrl + d.data.fnumber
                : d.data.ftype == 2
                ? departmentUrl + d.data.fnumber
                : ''
            }', '_blank')">${d.data.fname}</span>
            <span style="margin-left: 70px;">
              <img src="./img/user-card/line1.png" />
              <img src="./img/user-card/line2.png" />
            </span>
            <div style="background: url('./img/user-card/user-card.png'); height: 152px;background-size: 100% 100%;box-sizing: border-box;padding-top: 30px;" onclick="window.open('${
              userUrl + d.data.fleader
            }', '_blank')">
              <div onclick="window.open('${
                userUrl + d.data.fleader
              }', '_blank')" style="display: inline-block; background: url('./img/user-card/avatar-outer.png'); background-size: 100% 100%; width: 90px; height: 90px; text-align:center; vertical-align: top; margin-left: 11px;box-sizing: border;">
                <img src="${
                  d.data.fleaderimg
                    ? d.data.fleaderimg
                    : './img/default_avator.png'
                }" style="width: 58px; height: 58px; border-radius: 50%; margin-top: 16px;"/>
              </div>
              <div style="display: inline-block; margin-left: 6px;">
                <div style="
                font-size: 13px;
                font-family: Microsoft YaHei-Bold, Microsoft YaHei;
                font-weight: bold;
                color: #333333;
                margin-bottom: 9px;
                ">${d.data.fleadername}</div>
                <div style="
                  font-size: 13px;
                  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
                  font-weight: 400;
                  color: #333333;
                  margin-bottom: 19px;
                ">${d.data.fname} / ${d.data.fleaderjob}</div>
                <div style="display: flex;" onclick="window.open('${addressBookUrl}', '_blank')">
                  <div style="height: 28px;border: 1px solid #00C2FF; border-radius: 10px; line-height: 24px; padding: 0px 5px; min-width: 69px;">编制: ${
                    d.data.fplan
                  }</div>
                  <div style="height: 28px;border: 1px solid #00C2FF; border-radius: 10px; line-height: 24px; padding: 0px 5px; min-width: 69px; margin-left: 10px;">在岗: ${
                    d.data.fonjob
                  }</div>
                </div>
              </div>
            </div>
          </div>
        </div>`;
    } else if (d.data.ftype == 3) {
      return `<div>
          <div style="position: relative;">
            <img src="./img/user-card/card-label-start.png" />
            <span style="display: inline-block;
              position: absolute;
              left: 5px;
              top: -8px;
              background: #F7F9FD;
              z-index: 100;
              padding: 0px 10px; 
              font-size: 16px;
              font-family: Microsoft YaHei-Bold, Microsoft YaHei;
              font-weight: bold;
              color: #000000;
            " onclick="window.open('${
              jobtitleUrl + d.data.fnumber
            }', '_blank')">${d.data.fname}</span>
            <span style="margin-left: 70px;">
              <img src="./img/user-card/line1.png" />
              <img src="./img/user-card/line2.png" />
            </span>
            <div style="background: url('./img/user-card/user-card.png'); height: 152px;background-size: 100% 100%;box-sizing: border-box;padding-top: 40px;">
              <img src="./img/user-card/jobicon.png" style="margin-left: 20px; vertical-align: top;"/>
              <div style="display: inline-block; margin-left: 15px;">
                <div style="
                font-size: 13px;
                font-family: Microsoft YaHei-Bold, Microsoft YaHei;
                font-weight: bold;
                color: #333333;
                margin-bottom: 23px;
                " onclick="window.open('${
                  jobtitleUrl + d.data.fnumber
                }', '_blank')">${d.data.fname}</div>
                <div style="
                font-size: 13px;
                font-family: Microsoft YaHei-Regular, Microsoft YaHei;
                font-weight: 400;
                color: #333333;
                "  onclick="window.open('${addressBookUrl}', '_blank')">
                  <span>编制：${d.data.fplan}</span>
                  <span style="margin-left: 10px;">在岗：${d.data.fonjob}</span>
                </div>
              </div>
            </div>
          </div>
        </div>`;
    } else if (d.data.ftype == 4) {
      return `<div>
          <div style="position: relative;" onclick="window.open('${
            userUrl + d.data.fnumber
          }', '_blank')">
            <img src="./img/user-card/card-label-start.png" />
            <span >
              <img src="./img/user-card/line1.png" />
              <img src="./img/user-card/line2.png" />
            </span>
            <div style="background: url('./img/user-card/user-card.png'); height: 152px;background-size: 100% 100%;box-sizing: border-box;padding-top: 30px;">
              <div style="display: inline-block; background: url('./img/user-card/avatar-outer.png'); background-size: 100% 100%; width: 90px; height: 90px; text-align:center; vertical-align: top; margin-left: 11px;box-sizing: border;">
                <img src="${
                  d.data.fleaderimg
                    ? d.data.fleaderimg
                    : './img/default_avator.png'
                }" style="width: 58px; height: 58px; border-radius: 50%; margin-top: 16px;"/>
              </div>
              <div style="display: inline-block; margin-left: 6px;">
                <div style="
                font-size: 13px;
                font-family: Microsoft YaHei-Bold, Microsoft YaHei;
                color: #333333;
                margin-bottom: 9px;
                ">${d.data.fname}</div>
                <div style="
                  font-size: 13px;
                  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
                  font-weight: 400;
                  color: #333333;
                ">${d.data.department ? d.data.department + ' / ' : ''}${
        d.data.fleaderjob
      }</div>
                <div style="
                  font-size: 10px;
                  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
                  font-weight: 400;
                  color: #333333;
                  margin-bottom: 10px;
                ">${d.data.mobile ? d.data.mobile : ''}</div>
                <div style="
                  font-size: 10px;
                  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
                  font-weight: 400;
                  color: #333333;
                ">${d.data.address ? '地址：' + d.data.address : ''}</div>
              </div>
            </div>
          </div>
        </div>`;
    }
  };

  if (hasRight === false) {
    return (
      <div style={{ width: '100%', top: '40%', position: 'absolute' }}>
        <img
          style={{ display: 'block', margin: '0 auto' }}
          src="./img/permission.png"
        />
        <p style={{ textAlign: 'center' }}>对不起，您暂时没有权限!</p>
      </div>
    );
  }

  return (
    hasRight && (
      <div className={styles.contentWrapper}>
        <TopBar
          onExport={(type) => {
            handleExport(type);
          }}
          onSearch={(requestData) => {
            handleSearch(requestData);
          }}
          url="/api/bs/hrmorganization/orgchart/getCondition?type=user"
        />
        <ToolBar
          onTopLayoutClick={(progressBtn) => handleTopLayoutClick(progressBtn)}
          onLeftLayoutClick={(progressBtn) =>
            handleLeftLayoutClick(progressBtn)
          }
          onZoomOut={(progressBtn) => handleZoomOut(progressBtn)}
          onZoomIn={(progressBtn) => handleZoomIn(progressBtn)}
        />
        <OrgChartComponent
          setChart={(chart) => (orgChart = chart)}
          setClick={(click) => (addNodeChildFunc = click)}
          onNodeClick={onNodeClick}
          onButtonClick={onButtonClick}
          data={data}
          buttonContent={buttonContentRender}
          nodeWidth={nodeWidthRender}
          nodeHeight={nodeHeightRender}
          nodeContent={nodeContentRender}
        />
      </div>
    )
  );
}
