Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, {Component} from 'react';
  2. import styled from 'styled-components';
  3. import { withRouter } from "react-router-dom";
  4. import axios from 'axios';
  5. import moment from 'moment';
  6.  
  7. import RecordCard from '../../components/RecordCard'
  8.  
  9. import Header from '../../components/Header';
  10. import Menubar from '../../components/Menubar';
  11. import Divider from '../../components/Divider';
  12. import { filter } from '../../utils/Filter';
  13. import {languageText} from '../../languages/MultiLanguage.js';
  14. import Checkbox from '../../components/Checkbox';
  15. import customImg from '../../assets/custom-options.png'
  16.  
  17. const HistoryComponent = styled.section`
  18.   display: block;
  19.   padding: 7rem 0;
  20.   margin: 0;
  21.   h2 {
  22.     text-transform: uppercase;
  23.     font-weight: 300;
  24.     margin: 0 0 2rem 0;
  25.     text-align: center;
  26.   }
  27.   h3 {
  28.     margin-left: 1rem;
  29.   }
  30.  
  31. `
  32. const CustomIcon = styled.img`
  33.   width: 40px;
  34.   height: auto;
  35.   right: 1rem;
  36.   position: absolute;
  37.   margin-top: 2rem;
  38. `
  39.  
  40. const Records = styled.ul`
  41.     display:flex;
  42.     flex-direction: column;
  43.     align-items: center;
  44.     padding: 0;
  45.     list-style-type: none;
  46.  
  47.     li {
  48.       margin-bottom:1rem;
  49.       width: 100%;
  50.     }
  51. `
  52. const NoMoreStyle = styled.ul`
  53.     padding: 0;
  54.     margin-bottom: 5rem;
  55. `
  56.  
  57.  
  58. class History extends Component {
  59.   constructor(props) {
  60.     super(props);
  61.  
  62.     this.fieldsLocalization= ['Home', 'Outside','Transit', 'Work', 'Bed','School']
  63.     this.fieldsPain= ['No Pain','Mild','Moderate','Intense','Maximum']
  64.  
  65.     this.state = {
  66.       history: {},
  67.       order: [],
  68.       rawData: [],
  69.       localizations: {},
  70.       intensity: {},
  71.     }
  72.  
  73.     this.getIntensity = this.getIntensity.bind(this);
  74.     this.deleteReport = this.deleteReport.bind(this);
  75.     this.editReport = this.editReport.bind(this);
  76.     this.parseHistory = this.parseHistory.bind(this);
  77.     this.formatDuration = this.formatDuration.bind(this);
  78.     this.handleChangeFilter = this.handleChangeFilter.bind(this);
  79.     this.handleChangeFilter2 = this.handleChangeFilter2.bind(this);
  80.  
  81.   }
  82.  
  83.   componentDidMount() {
  84.     axios.get('/api/reports')
  85.       .then(({ data }) => {
  86.         this.parseHistory(data);
  87.       })
  88.       .catch((err) => console.log(err));
  89.  
  90.     axios.get('/api/users/answer')
  91.     .then((res) => {
  92.       if(res.status === 204){
  93.         console.log("No content");
  94.       } else {
  95.         const answerLocalization = res.data.localization
  96.         this.fieldsLocalization = [...this.fieldsLocalization, ...answerLocalization]
  97.      }
  98.     })
  99.     .catch((err) => {console.log(err);})
  100.   }
  101.  
  102.   getIntensity(key) {
  103.     const options = ['No Pain', 'Mild', 'Moderate', 'Intense', 'Maximum'];
  104.     return options.indexOf(key) + 1;
  105.   }
  106.  
  107.   editReport(evt) {
  108.     evt.stopPropagation()
  109.     const { history } = this.props
  110.     const { id } = evt.target
  111.     if (id) {
  112.     history.push(`edit/${id}/`)
  113.     }
  114.   }
  115.  
  116.   summaryReport(item) {
  117.     const { history } = this.props
  118.     history.push(`summary/`, {data: item, preview: true})
  119.   }
  120.  
  121.   deleteReport(evt){
  122.     evt.stopPropagation()
  123.     if(evt.target.id){
  124.       const id = evt.target.id;
  125.       const url = "/api/reports/" + id;
  126.       axios.delete(url)
  127.       .then((res) => {
  128.         this.componentDidMount();
  129.       })
  130.       .catch((err) => console.log(err));
  131.     }
  132.  
  133.   }
  134.  
  135.   parseHistory(data) {
  136.     let history = {};
  137.     let order = [];
  138.  
  139.     if (data.length) {
  140.       data.forEach((item) => {
  141.         const key = moment(item.start_date).format('YYYYMM');
  142.         const month = history[key] || [];
  143.         history = {
  144.           ...history,
  145.           [key]: [
  146.             ...month,
  147.             item,
  148.           ]
  149.         };
  150.       })
  151.  
  152.       order = Object.keys(history).sort((objA, objB) => {
  153.         return objB - objA;
  154.       });
  155.     }
  156.  
  157.     this.setState({ history, order, rawData: data },
  158.       () => {
  159.         const results = filter(this.state.rawData,
  160.           {start: new Date('2019-01-01'), end: new Date('2019-02-01')},
  161.           // {pain:"Mild"});
  162.           //{localization:["Outside","Work"],triggers:"Sport"});
  163.           {localization:["Outside","Work"]});
  164.           // {localization:"Outside",triggers:["Sport","Stress"]});
  165.         console.log(results);
  166.       });
  167.   }
  168.  
  169.  
  170.   handleChangeFilter(e) {
  171.   const item = e.target.name;
  172.   const isChecked = e.target.checked;
  173.  
  174.   this.setState(prevState => ({
  175.     localizations:{ ...prevState.localizations, [item]: isChecked }}))
  176. }
  177.  
  178.   handleChangeFilter2(e) {
  179.     const item = e.target.name;
  180.     const isChecked = e.target.checked;
  181.    
  182.     this.setState(prevState => ({
  183.       intensity:{ ...prevState.intensity, [item]: isChecked }}))
  184.   }
  185.  
  186.   formatDuration(duration) {
  187.     let text = "";
  188.     if(duration.days() > 0){
  189.       text+=duration.days() + "d ";
  190.     }
  191.     if(duration.hours() > 0){
  192.       text+=duration.hours() + "h ";
  193.     }
  194.     if(duration.minutes() > 0){
  195.       if(duration.days() === 0){
  196.         text+=duration.minutes() + "min";
  197.       }
  198.     }
  199.     return text;
  200.   }
  201.  
  202.   render() {
  203.     const { history, order } = this.state;
  204.  
  205.     return (
  206.       <HistoryComponent >
  207.         <Header />
  208.         <h2>{languageText.history.title}
  209.         {/* <CustomIcon src={customImg} onClick={() => this.setState({customPeriodVisible: true})}/> */}
  210.         </h2>
  211.         <div style={{ width: '100%' }}>
  212.         <h3>Localization</h3>
  213.          <div>
  214.           {
  215.             this.fieldsLocalization.map((field) => (
  216.               <Checkbox
  217.                 key={field}
  218.                 small
  219.                 text={field}
  220.                 name={field}
  221.                 onChange={this.handleChangeFilter}
  222.               />
  223.             ))
  224.           }
  225.           </div>
  226.           <h3>Pain intensity</h3>
  227.           <div>
  228.           {
  229.             this.fieldsPain.map((field) => (
  230.               <Checkbox
  231.               key={field}
  232.               small
  233.               text={field}
  234.               name={field}
  235.               onChange={this.handleChangeFilter2}
  236.               />
  237.             ))
  238.           }
  239.         </div>
  240.  
  241.           <Records>
  242.             {!!order.length && order.map((chunk) => {
  243.               const month = chunk.substring(4);
  244.               const monthName = languageText.dateTime.monthNames[moment(month, 'MM').format('M') -1]
  245.  
  246.               return (
  247.                 <li key={chunk}>
  248.                   <Records>
  249.                     <Divider text={monthName} />
  250.                     {history[chunk].map((item) => {
  251.                       const startDate = moment(item.start_date, 'YYYY-MM-DDTHH:mm:ss');
  252.                       const endDate =  item.end_date ? moment(item.end_date,'YYYY-MM-DDTHH:mm:ss') : moment(new Date(),'ddd MMM DD YYYY HH:mm:ss');
  253.                       const duration = moment.duration(endDate.diff(startDate));
  254.                       const formattedDuration = this.formatDuration(duration);
  255.                       return (
  256.                         <li key={item._id}>
  257.                           <RecordCard handleClick={() => this.summaryReport(item)} date={startDate.format('DD.MM.YYYY')}
  258.                             duration={formattedDuration}
  259.                             intensity={this.getIntensity(item.pain)}
  260.                             isRecent={false}
  261.                             id={item._id}
  262.                             handleDelete={this.deleteReport}
  263.                             handleEdit={this.editReport}
  264.                             hasEnd={!!item.end_date}
  265.                             />
  266.                         </li>
  267.                       )
  268.                     })}
  269.                   </Records>
  270.                 </li>
  271.               );
  272.             })}
  273.             <li key="9999">
  274.               <NoMoreStyle>
  275.                 <Divider text={languageText.history.noMore} />
  276.               </NoMoreStyle>
  277.             </li>
  278.           </Records>
  279.         </div>
  280.         <Menubar />
  281.       </HistoryComponent>
  282.     );
  283.   }
  284. }
  285.  
  286. export default withRouter(History);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement