

 /* eslint no-underscore-dangle: ["error", { "allow": ["_status", "_updated_at"] }]*/

import React from 'react';
import Moment from 'moment';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ReportStatusTable.css';
import fulcrumSQLRecords from '../../utils/fulcrumSQLRecords';
import fulcrumFormHelpers from '../../utils/fulcrumFormHelpers';
import fulcrumTsHelpers from '../../utils/fulcrumTsHelpers';
import fulcrumVarHelpers from '../../utils/fulcrumVarHelpers';

class ReportStatusTable extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      completeObj: [],
      assignedObj: ['a', 'b', 'c'],
      incompleteObj: ['a', 'b', 'c'],
      fulcrumAppData: {},
      fulcrumTsList: [],
    };
  }

  componentDidMount() {
    // console.log('Surveys component mounted.');
    fulcrumSQLRecords.getComplete()
      .then((datas) => {
        this.setState({
          completeObj: datas,
        });
      });
    fulcrumSQLRecords.getIncomplete()
      .then((datas) => {
        this.setState({
          incompleteObj: datas,
        });
      });
    fulcrumSQLRecords.getAssigned()
      .then((datas) => {
        this.setState({
          assignedObj: datas,
        });
      });
    this.loadTimer = setTimeout(() => {
      this.setState({
        fulcrumAppData: fulcrumFormHelpers.getAppInfo(),
      });
    }, 3000);
    fulcrumTsHelpers.getInfoData()
      .then((datas) => {
        this.setState({
          fulcrumTsList: datas,
        });
      });
  }

  componentWillUnmount() {
    // console.log('Surveys component unmounted.');
    clearTimeout(this.loadTimer);
    if (this.loadTimer) {
      clearTimeout(this.loadTimer);
      this.loadTimer = null;
    }
  }

  render() {
    const { fulcrumAppData } = this.state;
    const allTsInfo = this.state.fulcrumTsList !== [] ?
      this.state.fulcrumTsList : [];
    // changedfulcrum console.log(this.state.fulcrumAppData)
    const allStaff = typeof (this.state.fulcrumAppData.form) !== 'undefined' ?
    fulcrumAppData.form.elements[fulcrumVarHelpers.fieldStaffSectionPosition].elements[fulcrumVarHelpers.fieldStaffListPosition].choices
    : [];
    const completeObjRecords = typeof (this.state.completeObj.data) !== 'undefined' ?
      this.state.completeObj.data : [];
    const assignedObjRecords = typeof (this.state.assignedObj.data) !== 'undefined' ?
      this.state.assignedObj.data : [];
    const incompleteObjRecords = typeof (this.state.incompleteObj.data) !== 'undefined' ?
      this.state.incompleteObj.data : [];

    // console.log(completeObjRecords)
    // console.log(assignedObjRecords)
    // console.log(incompleteObjRecords)
    // console.log(this.state.fulcrumTsList)

    const siftStats = function siftStatsFunc(staffId) {
      const staffCompleteRecList = completeObjRecords.rows;
      const staffIncompleteRecList = incompleteObjRecords.rows;
      const staffAssignedRecList = assignedObjRecords.rows;
      const staffCompleteRec = [];
      const staffIncompleteRec = [];
      const staffAssignedRec = [];
      const staff7AssignedRec = [];
      const milespc = [];
      const hourspc = [];

      staffCompleteRecList.forEach((staffRec) => {
        if (staffRec.fieldstaff === staffId) {
          staffCompleteRec.push(staffRec);
        }
      });

      staffIncompleteRecList.forEach((staffRec) => {
        if (staffRec.fieldstaff === staffId) {
          staffIncompleteRec.push(staffRec);
        }
      });

      staffAssignedRecList.forEach((staffRec) => {
        if (staffRec.fieldstaff === staffId) {
          staffAssignedRec.push(staffRec);
        }
      });

      staffAssignedRecList.forEach((staffRec) => {
        const staffRec7AssignDate = Moment(staffRec._updated_at, 'YYYY-MM-DDTHH:mm:ss.SSSSZ');
        const sevenDaysAgo = Moment().subtract(7, 'd');
        const sevendays = staffRec7AssignDate.isBetween(sevenDaysAgo, Moment());
        if (sevendays === true && staffRec.fieldstaff === staffId) {
          staff7AssignedRec.push(staffRec);
        }
      });

      allTsInfo.forEach((tsEntry) => {
        const entryStaff = tsEntry.form_values[fulcrumVarHelpers.timesheetnames].choice_values[0];
        if (entryStaff === staffId) {
          milespc.push(tsEntry);
          hourspc.push(tsEntry);
        }
      });

      const milespcmap = milespc.map((milespcitem) =>
      parseInt(milespcitem.form_values[fulcrumVarHelpers.milesquestionid], 10));

      const hourspcmap = hourspc.map((hourspcitem) => hourspcitem.form_values[fulcrumVarHelpers.hoursquestionid] !== undefined ? parseInt(hourspcitem.form_values[fulcrumVarHelpers.hoursquestionid].choice_values[0], 10) : 0);

      const totalmiles = milespcmap.reduce((a, b) => a + b, 0);
      const totalhours = hourspcmap.reduce((a, b) => a + b, 0);
      const milespercaseV = totalmiles / (staffCompleteRec.length + staffIncompleteRec.length);
      const hourspercaseV = totalhours / (staffCompleteRec.length + staffIncompleteRec.length);
      const milespercaseVa = milespercaseV > 0 && isFinite(milespercaseV) ?
        milespercaseV : 0;
      const hourspercaseVa = hourspercaseV > 0 && isFinite(hourspercaseV) ?
        hourspercaseV : 0;
      return [
        <td key={staffId + 1} className={s.statTabletd}>
          {staffCompleteRec.length + staffIncompleteRec.length} </td>,
        <td key={staffId + 2} className={s.statTabletd}> {staffAssignedRec.length} </td>,
        <td key={staffId + 3} className={s.statTabletd}> {staff7AssignedRec.length} </td>,
        <td key={staffId + 4} className={s.statTabletd}> {staffCompleteRec.length} </td>,
        <td key={staffId + 5} className={s.statTabletd}> {staffIncompleteRec.length} </td>,
        <td key={staffId + 6} className={s.statTabletd}> {milespercaseVa.toFixed(2)}</td>,
        <td key={staffId + 7} className={s.statTabletd}> {hourspercaseVa.toFixed(2)}</td>,
      ];
    };

    console.log('HERE');
    console.log(this.state.completeObj);
    console.log('HERE I');
    console.log(this.state.completeObj.length);
    console.log('HERE I AM');
    // console.log(this.state.completeObj.data.rows.length)

    const staffList = allStaff !== 'undefined' ?
      allStaff.map((staffOb, i) =>
        <tr key={staffOb.value + i} id={staffOb.value} className={staffOb.value}>
          <td
            key={staffOb.value + i + i}
            className={s.darkblueCell} id={staffOb.value}
          >{staffOb.label}</td>
          {typeof (this.state.completeObj.data) !== 'undefined' ?
            siftStats(staffOb.value) : [<td key={7} className={s.statTabletd}>0</td>,
              <td key={1} className={s.statTabletd}>0</td>,
              <td key={2} className={s.statTabletd}>0</td>,
              <td key={3} className={s.statTabletd}>0</td>,
              <td key={4} className={s.statTabletd}>0</td>,
              <td key={5} className={s.statTabletd}>0</td>,
              <td key={6} className={s.statTabletd}>0</td>]}
        </tr>,
      ) :
      (<tr>
        <td className={s.blueCell}>____</td>
        <td className={s.statTabletd}>0</td>
        <td className={s.statTabletd}>0</td>
        <td className={s.statTabletd}>0</td>
        <td className={s.statTabletd}>0</td>
        <td className={s.statTabletd}>0</td>
        <td className={s.statTabletd}>0</td>
        <td className={s.statTabletd}>0</td>
      </tr>)
      ;

    return (
      <div className={s.root}>
        <h4 className={s.tableTitle}>Field Staff Progress</h4>
        <table className={s.statTable}>
          <tbody>
            <tr>
              <td className={s.statTabletdOff} />
              <td className={s.darkblueCell}>Total Evaluated</td>
              <td className={s.blueCell}>Total Assigned</td>
              <td className={s.blueCell}>Assigned over the past 7 days</td>
              <td className={s.greenCell}>Completed</td>
              <td className={s.redCell}>Incomplete</td>
              <td className={s.darkgreenCell}>Miles per Evaluation</td>
              <td className={s.darkgreenCell}>Hours per Evaluation</td>
            </tr>
            {staffList}
          </tbody>
        </table>
      </div>
    );
  }
}

export default withStyles(s)(ReportStatusTable);
