import React from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import style from './index.less';
import {
  DatePicker,
  Select,
  Button,
  Checkbox,
  Row,
  Col,
  Dropdown,
  Menu,
  TreeSelect,
  Tooltip,
  Modal,
  Input,
  message,
  notification,
} from 'antd';
const { Option } = Select;
const { TextArea } = Input;
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import { HomeOutlined } from '@ant-design/icons';
moment.locale('zh-cn');
import { getLabel } from '../../util/i18n.js';
import { SmileOutlined } from '@ant-design/icons';

export class TopBar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fclasslist: [],
      rootTreeData: [], //根节点异步树
      treeLoadedKeys: [],
      treeExpandedKeys: [],
      requestData: {
        fclass: '0',
        root: undefined,
        level: '2',
        fisvitual: '0',
        hidedept: '0',
      },
      open: false,
      confirmLoading: false,
      description: '',
    };
  }

  /**
   * 表单值改变
   * @param {*} payload
   */
  handleFormChange(payload) {
    let requestData = { ...this.state.requestData, ...payload };
    this.setState({ requestData });
  }

  onChange = (e) => {
    this.setState({ description: e.target.value });
  };

  /**
   * 弹窗确认
   */
  handleOk = () => {
    const { description, requestData } = this.state;
    const { labelData } = this.props;
    if (description.length == 0) {
      return message.error(`${getLabel(547512, labelData)}`);
    }
    this.setState({ confirmLoading: true });
    let api =
      '/api/bs/hrmorganization/orgchart/versionRecord?fclass=' +
      requestData.fclass +
      '&description=' +
      description;
    fetch(api)
      .then((res) => res.json())
      .then((data) => {
        if (data.api_status) {
          this.setState({
            open: false,
            confirmLoading: false,
          });
          message.success(`${getLabel(547513, labelData)}`, 2, 3);
        } else {
          message.error(`${getLabel(547514, labelData)}`, 2, 3);
        }
      });
  };

  handleExportMenuClick(e) {
    this.props.onExport(e.key == '1' ? 'png' : 'pdf');
  }

  handleExportButtonClick() {
    this.props.onExport('png');
  }

  /**
   * 根节点树数据
   * @param {} parentId
   * @returns
   */
  getNodeTreeNode = (url, merge = true) => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        if (data.api_status) {
          let arr = [];
          if (merge) {
            arr = [...this.state.rootTreeData, ...data.companyTree];
          } else {
            arr = [...data.companyTree];
          }
          arr.map((item, index) => {
            item.icon = <HomeOutlined />;
          });
          this.setState({
            rootTreeData: arr,
          });
        }
      });
  };

  /**
   * 根节点树异步加载
   * @param {} parentId
   * @returns
   */
  onRootLoadData = (treeNode) =>
    new Promise((resolve) => {
      const { id } = treeNode;
      setTimeout(() => {
        const { fclass } = this.state.requestData;
        let api =
          '/api/bs/hrmorganization/orgchart/getSubCompanyTree?subcompany=' +
          id +
          '&fclass=' +
          fclass;
        this.getNodeTreeNode(api);
        resolve(undefined);
      }, 500);
    });

  onRootChange = (value) => {
    let requestData = { ...this.state.requestData, root: value };
    this.setState({ requestData });
  };

  onTreeExpand = (expandedKeys) => {
    this.setState({
      treeExpandedKeys: expandedKeys,
    });
  };

  componentDidMount() {
    this.getSeatchCondition(this.props.url);
  }

  getSeatchCondition = (url) => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        data.companyTree.map((item, index) => {
          item.icon = <HomeOutlined />;
        });
        this.setState({
          fclasslist: data.fclasslist,
          rootTreeData: data.companyTree,
        });
      });
  };

  menu = (
    <Menu
      onClick={this.handleExportMenuClick.bind(this)}
      items={[
        {
          label: `${getLabel(547315, this.props.labelData)}`,
          key: '1',
        },
        // {
        //   label: '导出PDF',
        //   key: '2',
        // },
      ]}
    />
  );

  render() {
    const { disabled, type, labelData } = this.props;
    const { rootTreeData, open, confirmLoading, treeExpandedKeys } = this.state;

    return (
      <div className={style.topbarWrapper}>
        <Row>
          <Col span={6}>
            {getLabel(547293, labelData)}：
            <Select
              defaultValue="0"
              style={{ width: 140 }}
              value={this.state.requestData.fclass}
              onChange={(value) => {
                const requestData = {
                  fclass: value,
                  root: undefined,
                  level: '2',
                  fisvitual: '0',
                  hidedept: '0',
                };
                this.handleFormChange(requestData);
                this.setState({
                  rootTreeData: [],
                });
                this.getNodeTreeNode(
                  `/api/bs/hrmorganization/orgchart/getSubCompanyTree?fclass=${value}`,
                  false,
                );
                this.props.changeFclass(requestData);
              }}
            >
              {this.state.fclasslist.map((item) => (
                <Option key={item.key} value={item.id}>
                  {item.companyname}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={6}>
            {getLabel(547294, labelData)}：
            <TreeSelect
              treeDataSimpleMode
              allowClear
              style={{ width: '65%' }}
              value={this.state.requestData.root}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder={getLabel(547298, labelData)}
              onChange={this.onRootChange}
              loadData={this.onRootLoadData}
              treeData={rootTreeData}
              treeIcon
            />
          </Col>
          <Col span={6}>
            <Checkbox
              style={{ marginTop: '5px', marginLeft: 100 }}
              checked={this.state.requestData.hidedept == '1'}
              onChange={(e) =>
                this.handleFormChange({
                  hidedept: e.target.checked ? '1' : '0',
                })
              }
            >
              {getLabel(547296, labelData)}
            </Checkbox>
            <Tooltip
              title={getLabel(547303, labelData)}
              color="#0082fb"
              placement="rightTop"
            >
              <QuestionCircleOutlined
                style={{ color: '#0082fb', cursor: 'pointer', fontSize: 16 }}
              />
            </Tooltip>
          </Col>
          <Col span={6}>
            {getLabel(547299, labelData)}：
            <Select
              defaultValue="3"
              style={{ width: 140 }}
              value={this.state.requestData.level}
              onChange={(value) => this.handleFormChange({ level: value })}
            >
              <Option value="1">{getLabel(547301, labelData)}</Option>
              <Option value="2">{getLabel(547463, labelData)}</Option>
              <Option value="3">{getLabel(547464, labelData)}</Option>
              <Option value="4">{getLabel(547465, labelData)}</Option>
            </Select>
          </Col>
        </Row>
        <Row style={{ marginTop: '15px' }}>
          <Col span={6}>
            <Checkbox
              style={{ marginTop: '5px' }}
              checked={this.state.requestData.fisvitual == '1'}
              onChange={(e) =>
                this.handleFormChange({
                  fisvitual: e.target.checked ? '1' : '0',
                })
              }
            >
              {getLabel(547302, labelData)}
            </Checkbox>
            <Tooltip
              title={getLabel(547304, labelData)}
              color="#0082fb"
              placement="rightTop"
            >
              <QuestionCircleOutlined
                style={{ color: '#0082fb', cursor: 'pointer', fontSize: 16 }}
              />
            </Tooltip>
          </Col>
          <Col span={16}>
            <Button
              type="primary"
              style={{ marginRight: '10px' }}
              disabled={disabled}
              onClick={() => {
                this.setState({ open: true });
              }}
            >
              {getLabel(547305, labelData)}
            </Button>

            <Button
              type="primary"
              style={{ marginRight: '10px' }}
              onClick={() => {
                this.props.onSearch(this.state.requestData);
              }}
            >
              {getLabel(547307, labelData)}
            </Button>
            <Button
              type="primary"
              style={{ marginRight: '10px' }}
              onClick={() => {
                window.open('#/dragtree', 'blank');
              }}
            >
              {getLabel(547310, labelData)}
            </Button>
            <Button
              type="primary"
              style={{ marginRight: '10px' }}
              onClick={() => {
                window.open('#/statistics', 'blank');
              }}
            >
              {getLabel(547313, labelData)}
            </Button>
            <Dropdown overlay={this.menu}>
              <Button type="primary">{getLabel(547314, labelData)}</Button>
            </Dropdown>
          </Col>
        </Row>
        <Modal
          title={getLabel(547305, labelData)}
          cancelText={getLabel(547318, labelData)}
          okText={getLabel(547319, labelData)}
          open={open}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={() => this.setState({ open: false })}
        >
          <p style={{ color: 'red' }}>{getLabel(547316, labelData)}</p>
          <p>{getLabel(547317, labelData)}:</p>
          <TextArea
            showCount
            maxLength={20}
            style={{ height: 120, resize: 'none' }}
            onChange={this.onChange}
            placeholder="please enter"
          />
        </Modal>
      </div>
    );
  }
}
