import React from 'react';
import { Drawer, Space, Button, Dropdown, Menu, Table } from 'antd';
import { OrgChartComponent } from '@/components/orgChart';
import * as d3 from 'd3';
import qs from 'qs';
import { message } from 'antd';
import jsPDF from 'jspdf';
import styles from './index.less';

let addNodeChildFunc = null;
let orgChart = null;
let active = 'top';
export default class DrawerComponents extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false,
      data: [],
      detailType: 'chart',
      rootId: '',
    };
  }

  componentDidMount() {
    //this.getDeatilDatas();
  }

  // 点击节点
  onNodeClick(node) {}

  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(',');
      let api = '/api/bs/hrmorganization/orgchart/asyncUserData?ids=' + idsStr;
      fetch(api)
        .then((res) => res.json())
        .then((data) => {
          if (data.data) {
            data.data.forEach((item) => {
              window.chart.addNode(item);
            });
          }
        });
    }
  }

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

  //获取数据
  getDeatilDatas(rootId) {
    const { detailType } = this.state;
    d3.json(
      '/api/bs/hrmorganization/orgchart/userData?' +
        qs.stringify({ detauleType: detailType, rootId: rootId }),
    ).then((data) => {
      this.setState(data.data);
    });
  }

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

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

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

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

  handleLeftLayoutClick = (progressBtn) => {
    progressBtn.current.style.top = 50 + 'px';
    orgChart &&
      orgChart
        .layout('left')
        .setCentered(orgChart.getChartState().root.id)
        .render();
    active = 'left';
  };

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

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

  downloadPdf(chart) {
    chart.exportImg({
      save: false,
      full: true,
      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');
        };
      },
    });
  }

  handleExport = (e) => {
    let type = e.key == '1' ? 'png' : 'pdf';
    if (type == 'png') {
      orgChart && orgChart.exportImg({ full: true });
    } else {
      orgChart && downloadPdf(orgChart);
    }
  };

  /**
   * 节点渲染
   */
  nodeContentRender = (d, i, arr, state) => {
    if (d.data.ftype == 2) {
      return `<div style="position: relative;">
                <div style=" height: 152px;background-size: 100% 100%;box-sizing: border-box;padding-top: 30px;position:relative;z-index:2">
                    <div style='position:absolute;z-index:-1;top:0'>
                        <img src='./img/user-card/user-card.png'>
                    </div>
                    <div style="display: inline-block;  background-size: 100% 100%; width: 35%; height: 90px; text-align:center; vertical-align: top; margin-left: 11px;box-sizing: border;">
                        <img src='./img/user-card/avatar-outer.png' style='position:absolute;width:90px;height:90px;left:11px'/>
                        <img src="./img/department.png" style="width: 58px; height: 58px;position:absolute;left:29px; border-radius: 50%; margin-top: 16px;position:absolute;left:29px;z-index:999"/>
                    </div>
                    <div style="display: inline-block; margin-left: 6px;width: 55%">
                        <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;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                            ${d.data.fname}${
        d.data.fleaderjob ? `/${d.data.fleaderjob}` : ''
      }
                        </div>
                    </div>
                    <div style="display:flex" >
                        <div style="height: 28px;border: 1px solid #00C2FF; border-radius: 10px; line-height: 24px; padding: 0px 5px; min-width: 60px;">
                            在岗: ${d.data.fonjob}
                        </div>
                    </div>
                </div>
              </div>`;
    } else if (d.data.ftype == 3) {
      return `<div style="position: relative;">
                <div style=" height: 152px;background-size: 100% 100%;box-sizing: border-box;padding-top: 40px;">
                    <div style='position:absolute;z-index:-1;top:16px'>
                        <img src='./img/user-card/user-card.png'>
                    </div>
                    <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;">${d.data.fname}</div>
                        <div style="font-size: 13px;font-family: Microsoft YaHei-Regular, Microsoft YaHei;font-weight: 400;color: #333333;display: flex;">
                            <span style="margin-left: 10px;">在岗：${d.data.fonjob}</span>
                        </div>
                    </div>
                </div>
              </div>`;
    } else if (d.data.ftype == 4) {
      return `<div style="position: relative;" >
                <div style="height: 152px;background-size: 100% 100%;box-sizing: border-box;padding-top: 30px;">
                    <div style='position:absolute;z-index:-1;top:16px'>
                        <img src='./img/user-card/user-card.png'>
                    </div>
                    <div style="display: inline-block;  background-size: 100% 100%; width: 35%; height: 90px; text-align:center; vertical-align: top; margin-left: 11px;box-sizing: border;">
                        <img src='./img/user-card/avatar-outer.png' style='position:absolute;width:90px;height:90px;left:11px;z-index:-1'/>
                        <img src="${
                          d.data.fleaderimg
                            ? d.data.fleaderimg
                            : './img/default_avator.png'
                        }" style="width: 58px; height: 58px; border-radius: 50%; margin-top: 16px;z-index:999" />
                    </div>
                    <div style="display: inline-block; margin-left: 6px;width: 55%;height:100%">
                        <div style='display:flex;align-items:center;margin-bottom:19px;margin-top:15px'>
                            <div style="font-size: 13px;ont-family: Microsoft YaHei-Bold, Microsoft YaHei;color: #333333;">${
                              d.data.fname
                            }</div>
                        </div>
                    </div>
                </div>
             </div>`;
    }
  };

  showDrawer = (rootId) => {
    this.getDeatilDatas(rootId);
    this.setState({ open: true, rootId: rootId });
  };

  onClose = () => {
    this.setState({ open: false });
  };

  changeDetail = () => {
    const { detailType, rootId } = this.state;
    this.getDeatilDatas(rootId);
    this.setState({
      detailType: detailType == 'chart' ? 'table' : 'chart',
    });
  };

  render() {
    const { open, data, detailType } = this.state;

    const menu = (
      <Menu
        onClick={this.handleExport.bind(this)}
        items={[
          {
            label: '导出图片',
            key: '1',
          },
          {
            label: '导出PDF',
            key: '2',
          },
        ]}
      />
    );
    const dataSource = [
      {
        key: '1',
        name: '胡彦斌',
        age: 32,
        address: '西湖区湖底公园1号',
      },
      {
        key: '2',
        name: '胡彦祖',
        age: 42,
        address: '西湖区湖底公园1号',
      },
    ];

    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '年龄',
        dataIndex: 'age',
        key: 'age',
      },
      {
        title: '住址',
        dataIndex: 'address',
        key: 'address',
      },
    ];

    return (
      <Drawer
        title="详细信息"
        width={920}
        onClose={this.onClose}
        open={open}
        bodyStyle={{
          paddingBottom: 80,
        }}
        extra={
          <Space>
            <Dropdown overlay={menu}>
              <Button type="primary">导出</Button>
            </Dropdown>
            <img
              style={{ width: 36, height: 36, cursor: 'pointer' }}
              src="./img/change.png"
              onClick={this.changeDetail}
            />
          </Space>
        }
      >
        {detailType == 'chart' ? (
          <OrgChartComponent
            setChart={(chart) => (orgChart = chart)}
            setClick={(click) => (addNodeChildFunc = click)}
            onNodeClick={this.onNodeClick}
            onButtonClick={this.onButtonClick}
            data={data}
            buttonContent={this.buttonContentRender}
            nodeWidth={this.nodeWidthRender}
            nodeHeight={this.nodeHeightRender}
            nodeContent={this.nodeContentRender}
          />
        ) : (
          <Table dataSource={dataSource} columns={columns} />
        )}
      </Drawer>
    );
  }
}
