/**
 * @file 加签功能
 */
import React, { Component } from 'react';
import { Modal, Input, Table, Row, Col, Tooltip, Spin, Tag } from 'antd';
import styles from './style.less';
import { openToast } from '../Notification';
import { connect } from 'dva';
import { getUaaServicesNomal } from '../../../Services/services';
import { addSignsApi } from '../../../Services/apiConfig';

const { Search } = Input;

@connect()
export default class Countersign extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [], // 表格参数
      textAreaValue: '', // 用户转发理由
      current: 1, // 当前页数
      pageSize: 10, // 每页条数
      total: 0, // 数据总数
      realname: '', // 姓名输入框输入值
      username: '', // 账号输入框输入值
      isLoading: false, // 请求状态
      visible: false,
      selectUserData: [],
      btnLoading: false, // 提交状态
    };
    this.columns = [
      {
        title: '用户名',
        fixed: 'left',
        dataIndex: 'realname',
        width: 170,
      },
      {
        title: '工号',
        dataIndex: 'stuNo',
        width: 170,
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        width: 200,
        render: text => {
          return (
            <Tooltip title={text}>
              <div className={styles.table_post_name}>{text}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '职位',
        dataIndex: 'mainPostName',
        render: text => {
          return (
            <Tooltip title={text}>
              <div className={styles.table_post_name}>{text}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '操作',
        key: '操作',
        fixed: 'right',
        render: record => {
          return (
            <a
              onClick={() => {
                this.addUserSelect(record);
              }}
            >
              选择
            </a>
          );
        },
      },
    ];
  }

  componentDidMount() {
    this.props.updateCountersignModal(this.showModal);
    this.setState(
      {
        isLoading: true,
      },
      () => {
        this.getInit();
      },
    );
  }

  /**
   * @function 进行用户添加
   * @event click
   */
  addUserSelect = val => {
    const { selectUserData } = this.state;
    let array = selectUserData.filter(item => item.id === val.id);
    if (array.length > 0) {
      openToast('warning', '请勿重复添加用户');
      return;
    }
    let ary = [
      ...selectUserData,
      {
        id: val.id,
        name: val.realname,
      },
    ];
    this.setState({
      selectUserData: ary,
    });
  };
  /**
   * @function 进行用户删除
   * @param { string } id 需要删除的ID
   */
  removeUserSelect = id => {
    const { selectUserData } = this.state;
    let ary = selectUserData.filter(item => item.id !== id);
    this.setState({
      selectUserData: ary,
    });
  };
  getInit = async () => {
    // 用户名列表
    this.getData();
    await this.setState({
      isLoading: false,
    });
  };

  getData = async (params = {
    pageNo: 1,
    pageSize: 5,
  }) => {
    const {
      dispatch,
      data,
    } = this.props;

    await dispatch({
      type: 'uaa_User_OneStop/fetch',
      payload: {
        ...params,
      },
      callback: val => {
        this.setState({
          data: val.rows,
          current: val.pageNo,
          total: val.totalPage,
          pageSize: val.pageSize,
        });
      },
    });
  };

  userPaginationChange = value => {
    const {
      realname,
      username,
    } = this.state;
    this.getData({
      pageNo: value,
      pageSize: 5,
      realname,
      username,
    });
  };
  /**
   * 根据名字查询
   * @param { string } value 用户输入值
   */
  searchNameChange = value => {
    this.getData({
      realname: value,
      pageNo: 1,
      pageSize: 5,
    });

  };
  /**
   * 名字输入事件
   * @param { stirng } e 用户输入事件
   */
  onNameChange = e => {
    this.setState({
      realname: e.target.value,
      username: '',
    });
  };
  /**
   * 根据账号查询
   * @param { stirng } value 用户输入值
   */
  serachStuNoChange = value => {
    this.setState({
      username: value,
    });
    this.getData({
      username: value,
      pageNo: 1,
      pageSize: 5,
    });
  };
  /**
   * 账号输入数据
   * @param { stirng } e 用户输入事件
   */
  onStuNoChange = e => {
    this.setState({
      username: e.target.value,
      realname: '',
    });
  };
  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  handleOk = e => {
    const { selectUserData } = this.state;
    let ary = [];
    selectUserData.map(item => {
      ary.push(item.id);
    });
    if (ary.length === 0) {
      openToast('info', '并未选择加签用户,请选择');
      return;
    }
    this.setState(
      {
        btnLoading: true,
      },
      () => {
        getUaaServicesNomal(addSignsApi, {
          taskId: this.props.taskId,
          userIds: ary,
        }).then(() => {
          openToast('success', '加签成功');
            this.props.getInit();
            this.setState({
              visible: false,
              btnLoading: false,
            });
        });
        // dispatch({
        //   type: 'countersign/countersignHandle',
        //   payload: {
        //     taskId: this.props.taskId,
        //     userIds: ary,
        //   },
        //   callback: () => {
        //     openToast('success', '加签成功');
        //     this.props.getInit();
        //     this.setState({
        //       visible: false,
        //       btnLoading: false,
        //     });
        //   },
        // });
      },
    );
  };

  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  render() {
    const {
      data,
      current,
      total,
      pageSize,
      realname,
      username,
      isLoading,
      selectUserData,
      btnLoading,
    } = this.state;
    let allWidth = 0;
    // 计算滑动总长度
    if (Array.isArray(this.columns)) {
      this.columns.map((item, index) => {
        if (this.columns.length - 1 === index) {
          // 为最后一个元素时跳过
          allWidth += 270; // 自适应200宽度
          return item;
        }
        if (item.width) {
          // 存在默认宽度
          allWidth += item.width;
        } else {
          // 不存在
          allWidth += 170;
        }
        return item;
      });
    }
    return (
      <Modal
        title='加签'
        visible={this.state.visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        width={800}
        confirmLoading={btnLoading}
        destroyOnClose
      >
        {!isLoading ? (
          <>
            <Row>
              <Col span={12}>
                <Row>
                  <Col
                    span={4}
                    style={{
                      minHeight: 32,
                      textAlign: 'right',
                      lineHeight: '32px',
                    }}
                  >
                    姓名 &nbsp;
                  </Col>
                  <Col span={20}>
                    <Search
                      placeholder='姓名'
                      value={realname}
                      onSearch={this.searchNameChange}
                      onChange={this.onNameChange}
                      enterButton
                    />
                  </Col>
                </Row>
              </Col>
              <Col span={12}>
                <Col
                  span={4}
                  style={{
                    minHeight: 32,
                    textAlign: 'right',
                    lineHeight: '32px',
                  }}
                >
                  账号 &nbsp;
                </Col>
                <Col span={20}>
                  <Search
                    placeholder='账号'
                    value={username}
                    onSearch={this.serachStuNoChange}
                    onChange={this.onStuNoChange}
                    enterButton
                  />
                </Col>
              </Col>
            </Row>
            <div id='trun_to_table' className={styles.trun_to_table_div}>
              <Table
                columns={this.columns}
                dataSource={data}
                scroll={{ x: allWidth }}
                pagination={{
                  hideOnSinglePage: true,
                  pageSize,
                  total,
                  current,
                  onChange: this.userPaginationChange,
                }}
              />
            </div>
            <div className={styles.title_name_div}>已选择加签人</div>
            <div className={styles.tag_div}>
              {selectUserData &&
              Array.isArray(selectUserData) &&
              selectUserData.length > 0 &&
              selectUserData.map(item => {
                return (
                  <Tag
                    color='#108ee9'
                    onClose={() => {
                      this.removeUserSelect(item.id);
                    }}
                    closable
                    key={item.id}
                  >
                    {item.name}
                  </Tag>
                );
              })}
            </div>
          </>
        ) : (
          <div className={styles.spin_div}>
            <Spin />
          </div>
        )}
      </Modal>
    );
  }
}
