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,
} 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';
moment.locale('zh-cn');

export class TopBar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fclasslist: [],
      rootTreeData: [], //根节点异步树
      treeExpandedKeys: [],
      requestData: {
        fclass: '0',
        root: undefined,
        level: '3',
        fisvitual: '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;
    if (description.length == 0) {
      return message.error('请填写描述信息');
    }
    this.setState({ confirmLoading: true });
    setTimeout(() => {
      this.setState({ open: false, confirmLoading: false, description: '' });
      message.success('版本记录成功,请重新刷新页面');
    }, 2000);
    // let api = '/api/bs/hrmorganization/orgchart/synchronousData?flcass='+requestData.fclass+ '&description=' +description;
    // fetch(api)
    //   .then((res) => res.json())
    //   .then((data) => {
    //     if (data.code == 200) {
    //       this.setState({ open: false, confirmLoading: false,description:'' });
    //       message.success('版本记录成功,请重新刷新页面');
    //     } else {
    //       message.error('版本记录失败,请联系相关人员处理数据');
    //     }
    //   });
  };

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

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

  /**
   * 根节点树数据
   * @param {} parentId
   * @returns
   */
  getNodeTreeNode = (parentId) => {
    const { fclass } = this.state.requestData;
    let api =
      '/api/bs/hrmorganization/orgchart/getSubCompanyTree?subcompany=' +
      parentId +
      '&fclass=' +
      fclass;
    fetch(api)
      .then((res) => res.json())
      .then((data) => {
        if (data.api_status) {
          let arr = [...this.state.rootTreeData, ...data.companyTree];
          this.setState({
            rootTreeData: arr,
          });
        }
      });
  };

  /**
   * 根节点树异步加载
   * @param {} parentId
   * @returns
   */
  onRootLoadData = (treeNode) =>
    new Promise((resolve) => {
      const { id } = treeNode.props;
      setTimeout(() => {
        this.getNodeTreeNode(id);
        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) => {
        this.setState({
          fclasslist: data.fclasslist,
          rootTreeData: data.companyTree,
        });
      });
  };

  menu = (
    <Menu
      onClick={this.handleExportMenuClick.bind(this)}
      items={[
        {
          label: '导出图片',
          key: '1',
        },
        {
          label: '导出PDF',
          key: '2',
        },
      ]}
    />
  );

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

    return (
      <div className={style.topbarWrapper}>
        <Row>
          <Col span={6}>
            维度：
            <Select
              defaultValue="0"
              style={{ width: 140 }}
              value={this.state.requestData.fclass}
              onChange={(value) => {
                const requestData = {
                  fclass: value,
                  root: undefined,
                  level: '3',
                  fisvitual: '0',
                };
                this.handleFormChange(requestData);
                this.getSeatchCondition(
                  `/api/bs/hrmorganization/orgchart/getCondition?fclass=${value}&type=${this.props.type}`,
                );
                this.props.onSearch(requestData);
              }}
            >
              {this.state.fclasslist.map((item) => (
                <Option key={item.key} value={item.id}>
                  {item.companyname}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={6}>
            根节点：
            <TreeSelect
              treeDataSimpleMode
              allowClear
              style={{ width: '80%' }}
              value={this.state.requestData.root}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="请选择根节点"
              onChange={this.onRootChange}
              loadData={this.onRootLoadData}
              treeData={rootTreeData}
            />
          </Col>
          <Col span={6}>
            <Checkbox
              style={{ marginTop: '5px', marginLeft: 100 }}
              checked={this.state.requestData.fisvitual == '1'}
              onChange={(e) =>
                this.handleFormChange({
                  fisvitual: e.target.checked ? '1' : '0',
                })
              }
            >
              显示虚拟组织
            </Checkbox>
            <Tooltip
              title="提示:若启用虚拟组织，需要在分部自定义表增加字段(名称 fblx) 字段类型 下拉框(0实体 1虚拟) 部门自定义表同上(字段名称 bmlx)。"
              color="#FF7F00"
              placement="rightTop"
            >
              <QuestionCircleOutlined
                style={{ color: '#FF7F00', cursor: 'pointer', fontSize: 16 }}
              />
            </Tooltip>
          </Col>
          <Col span={6}>
            显示层级：
            <Select
              defaultValue="3"
              style={{ width: 140 }}
              value={this.state.requestData.level}
              onChange={(value) => this.handleFormChange({ level: value })}
            >
              <Option value="1">一级</Option>
              <Option value="2">二级</Option>
              <Option value="3">三级</Option>
            </Select>
          </Col>
        </Row>
        <Row style={{ marginTop: '15px' }}>
          <Col span={8}>
            {type == 'user' && (
              <Button
                type="primary"
                style={{ marginRight: '10px' }}
                disabled={disabled}
                onClick={() => {
                  this.setState({ open: true });
                }}
              >
                版本记录
              </Button>
            )}
            <Button
              type="primary"
              style={{ marginRight: '10px' }}
              onClick={() => {
                this.props.onSearch(this.state.requestData);
              }}
            >
              查询
            </Button>
            <Dropdown overlay={this.menu}>
              <Button type="primary">导出</Button>
            </Dropdown>
          </Col>
        </Row>
        <Modal
          title="版本记录"
          cancelText="取消"
          okText="确定"
          open={open}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={() => this.setState({ open: false })}
        >
          <p style={{ color: 'red' }}>
            提示:版本操作耗时较长，请谨慎操作（版本仅记录当前维度的数据）
          </p>
          <p>描述:</p>
          <TextArea
            showCount
            maxLength={10}
            style={{ height: 120, resize: 'none' }}
            onChange={this.onChange}
            placeholder="please enter"
          />
        </Modal>
      </div>
    );
  }
}
