import React,{Component} from "react";
import { Link } from "react-router-dom";
import { Tabs,Tab } from 'react-bootstrap';
import {
  Breadcrumb,Button,
  BreadcrumbItem,Row,Col,
  Card,
  CardBody,
  CardHeader,
  CardTitle,
  Container,
  CardImg,
  CardLink,
  CardText,Input,
  InputGroup,
  InputGroupAddon,
  InputGroupText,
  CustomInput,Form,FormGroup, Modal,
  ModalBody,
  ModalFooter,
  ModalHeader
  } from "reactstrap";

import Header from "../../components/Header";
import Chart from "react-apexcharts";
import HeaderTitle from "../../components/HeaderTitle";
import * as myConstclassName from '../../constant.js';
import $ from 'jquery'; 
import { toastr } from "react-redux-toastr";
import avatar2 from "../../assets/img/photos/FoodPlaceHolder.png";
import * as myConstClass from '../../constant.js';
import swal from 'sweetalert';
import * as Icon from "react-feather";
import BootstrapTable from "react-bootstrap-table-next";
import ToolkitProvider, { Search } from "react-bootstrap-table2-toolkit";
import paginationFactory from "react-bootstrap-table2-paginator";
import filterFactory, { textFilter } from 'react-bootstrap-table2-filter';
import "./table.css";
// import { CircularProgressbar } from 'react-circular-progressbar';
import 'react-circular-progressbar/dist/styles.css';
const percentage = 166;
const { SearchBar } = Search;
const tableColumns = [
  // {
  //   dataField: "measures",
  //   text: "Measures",
  //   sort: true,
  //   headerStyle: { width:"25%" }
  // },
  {
    dataField: "title",
    text: "Name",
    sort: true,
    headerStyle: { width:"20%" }
  },
  {
    dataField: "energy",
    text: "Energy",
    sort: true,
    sortFunc: (a, b, order, dataField, rowA, rowB) => {
      if (order === 'asc') {
        return b - a;
      }
      return a - b; // desc
    },
    headerStyle: { width:"10%" }
  },
  {
    dataField: "fat",
    text: "Fat",
    sort: true,
    sortFunc: (a, b, order, dataField, rowA, rowB) => {
      if (order === 'asc') {
        return b - a;
      }
      return a - b; // desc
    },
    headerStyle: { width:"10%" }
  },
  {
    dataField: "carbohydrate",
    text: "Carbohydrate",
    sort: true,
    sortFunc: (a, b, order, dataField, rowA, rowB) => {
      if (order === 'asc') {
        return b - a;
      }
      return a - b; // desc
    },
    headerStyle: { width:"15%" }
    
  },
  {
    dataField: "protein",
    text: "Protein",
    sort: true,
    sortFunc: (a, b, order, dataField, rowA, rowB) => {
      if (order === 'asc') {
        return b - a;
      }
      return a - b; // desc
    },
    headerStyle: { width:"10%" }
    
  },
  {
    dataField: "action",
    text: "Action",
    headerStyle: { width:"10%" },
    csvExport: false
  },
  
];
const MyExportCSV = props => {
  const handleClick = () => {
    props.onExport();
  };
  return (
    <div>
        <button className="btn btn-secondary mt-2" onClick={handleClick}>
        Export
      </button>
    </div>
    
  );
};
class Validation extends Component {
  constructor(props) {
    super(props);
    this.state = {
      source:'',
      nutrient:'',
      recipe_ingredients_quantity:'',
      recipe_ingredients_measure_id:'',
      tableData:'',
      customDiv: [],
      user_id:'0',
      units:'',
      recipe_ingredients:'',recipe_nutrients:'',
      recipe_ingredients_measures:'',
      recipe_cooking_method:'',
      groups:'',
      macro:'',
      micro:'',
      state:'',
      city:'',
      formData:{
        name: '',
        description: '',
        total_time: '',
        preparation_time: '',
        weight:'',
        portions:'',
        state:'',
        city:'',
      },
      submitted: false,
      submitted1: false,
      modal:false,
      modal1:false,
      modal4:false,
      cooking_description:'',
      total_time_hour: '',
      total_time_minute: '',
      total_ptime_hour: '',
      total_ptime_minute: '',
      total_energy:0,
      total_fat:0,
      total_carbohydrate:0,
      total_protein:0,
      total_fiber:0,
      chartoptions: {
        legend: {
          position: 'bottom',
          horizontalAlign: 'center',
        },
     
        
         labels: ['Fat', 'Carbohydrate', 'Protein'],
      //   responsive: [{
      //     breakpoint: 480,
      //     options: {
      //       chart: {
      //         width: 200
      //       },
      //       legend: {
      //         position: 'bottom',
      //         show:'false',
              
      //       }
      //     }
      //   }],
       
      //   dataLabels: {
      //     textAnchor: 'middle',
      //     offset: 0,
      //     minAngleToShowLabel: 10,
      //     style: {
      //       fontSize: '10px',
      //       fontFamily: 'Helvetica, Arial, sans-serif',            
      //    },
      //    dropShadow: {
      //     enabled: false,
      //     top: 1,
      //     left: 1,
      //     blur: 1,
      //     opacity: 0.45
      // }
       // }
      },
      series: '',
    }
    
    this.sid=0;
    this.nid=0;
    this.recipe_ingredient_id=0;
    this.recipe_cooking_id=0;
    this.ingredient_id=0;
    this.options = {
      timeOut: parseInt(5000),
      showCloseButton: true,
      progressBar: true,
      position: "top-right"
    };
  this.handleChange = this.handleChange.bind(this);
  this.handleMeasure = this.handleMeasure.bind(this);
  this.handleDeleteMeasure = this.handleDeleteMeasure.bind(this);
//  this.changeMeasures = this.changeMeasures.bind(this);
  }

  add(id){
    //alert('in..');
   // alert(this.state.user_id + ' '+id);
   fetch(myConstclassName.BASE_URL+`/recipe/addRecipeIngredientMethod/`+this.state.user_id+'/'+id, {
    method: 'POST',
    body: JSON.stringify($('#pmform').serializeArray()),
  }).then(response =>  response.json()).then((response) => {
    if(response){
      
    fetch(myConstclassName.BASE_URL+`/recipe/getRecipeIngredientInfo/`+this.state.user_id, {
      method: 'POST',
      body: {'id':id},
    }).then(response =>  response.json()).then((response) => {
     
      this.setState({recipe_ingredients: response})
      this.state.total_fiber=0;
    this.state.total_energy = 0;this.state.total_fat = 0;this.state.total_carbohydrate = 0;this.state.total_protein = 0;
    this.state.recipe_ingredients.map((ele,index) => {
      this.state.total_energy += parseFloat(ele.energy);
      this.state.total_fat += parseFloat(ele.fat);
      this.state.total_carbohydrate += parseFloat(ele.carbohydrate);
      this.state.total_protein += parseFloat(ele.protein);
      this.state.total_fiber += parseFloat(ele.fiber);
    });
    let fat_calories = parseFloat(this.state.total_fat) * 9;
    let carbohdrate_calories = parseFloat(this.state.total_carbohydrate) * 4;
    let protein_calories = parseFloat(this.state.total_protein) * 4;
    let total_calories = parseFloat(fat_calories) + parseFloat(carbohdrate_calories) + parseFloat(protein_calories);
    //alert(this.state.total_energy);
    let chart_protein = (protein_calories/total_calories)*100;
    let carbohdrate_protein = (carbohdrate_calories/total_calories)*100;
    let fat_protein = (fat_calories/total_calories)*100;
    if(fat_protein || carbohdrate_protein ||chart_protein){//alert();
      this.setState({series: [fat_protein,carbohdrate_protein,chart_protein]});
    }
   
      if(response){
       //alert('Success : '+response.title);
       //let mdata = "<select id='measures_"+response.id+"' style='width:16%' onChange=changeMeasures()>";
    /// let mdata='<select id='measures_"+response.id+"' style={{'width':'16%'}} onChange={this.changeMeasures}>';
      //  if(response.measures){      
      //     response.measures.map((ele,index) => {
      //        // alert(ele.singular_name);
      //         // if(index == 0){
      //         //   data = <select>;
      //         // }
          
      //         mdata += '<option value='+ele.id+'>'+ele.singular_name+'('+ele.grams+' grams)</option>';
              
              
      //     });
      //     if(response.unit == '1'){
      //       mdata += '<option value=1>grams</option>';
      //     }          
      //  }
       let mdata = '';
       response.map((ele,index) => {
       if(ele.measure_id =='0'){
          mdata += '<div class="iclass">'+ele.title+'<hr/>100 Grams<span class="mclass">'+ele.title+'<span class="mclass">'+ele.energy+' Kcal</span><span class="mclass">'+ele.fat+' g</span><span class="mclass">'+ele.carbohydrate+' g</span><span class="mclass">'+ele.protein+' g</span><span class="mclass">'+<Icon.Edit size="10"/>+'</span></div>';
       }else{
          mdata += '<div class="iclass">'+ele.title+'<hr/>100 '+ele.measure_id+'<span class="mclass">'+ele.title+'<span class="mclass">'+ele.energy+' Kcal</span><span class="mclass">'+ele.fat+' g</span><span class="mclass">'+ele.carbohydrate+' g</span><span class="mclass">'+ele.protein+' g</span></div>';
       }
      });
    //  alert(mdata);
      // $('#ibody').html(mdata);
       //this.setState({ modal: false });
      }else{
       
      }
    })
    .catch(); 
    toastr.success(
      'Success',
      "Recipe Ingredient Added Successfully..!",
      this.options
    ) 
  }
})
  }

  addMethod(){
   
      fetch(myConstclassName.BASE_URL+`/recipe/addRecipeCookingMethod/`+this.state.user_id+'/'+this.recipe_cooking_id, {
        method: 'POST',
        body: JSON.stringify($('#pmmform').serializeArray()),
      }).then(response =>  response.json()).then((response) => {
        if(response){

          fetch(myConstclassName.BASE_URL+'/recipe/getRecipesMethod/'+this.state.user_id)
          .then(response => response.json())
          .then(response =>{
          this.setState({recipe_cooking_method: response})
          // let dhtml = '';
          // response.map((data,index) => {
          //  dhtml += '<div class="iclass">'+data.description+'</div>';
          // });
         
          // $('#mbody').html(dhtml);
        }).catch(err => console.log(err))
        this.recipe_cooking_id = 0;  
        this.setState({ cooking_description: '' });  
          toastr.success(
            'Success',
            "Cooking Method Added Successfully..!",
            this.options
          )

        }else{
          
        }
      })
      .catch();

     
    
     this.setState({ modal1: false });
  }

  componentDidMount(){
    const answer_array = this.props.location.pathname.split('/');
  
    if(answer_array['3']!=='0'){
      
        this.state.user_id = answer_array['3'];
        fetch(myConstclassName.BASE_URL+'/recipe/getRecipeInfo/'+answer_array['3'])
        .then(response => response.json())
        .then(response =>{
        this.setState({formData: response})
        let cDivs = [];//alert(response.total_time.split(':'));
        let timearr = response.total_time.split(':');
        if(timearr['0']){
        this.setState({total_time_hour: timearr['0'] });
        this.setState({total_time_minute: timearr['1'] });
        }

        let ptimearr = response.preparation_time.split(':');
        if(ptimearr['0']){
        this.setState({total_ptime_hour: ptimearr['0'] });
        this.setState({total_ptime_minute: ptimearr['1'] });
        }
        response.sinarr.map(() => {
          //let cDivs = this.state.customDiv;
          cDivs.push('newDiv')
          this.setState({customDiv: cDivs })
        });
       
        if(this.state.formData.source=='2'){
          $('#source_div').show();
          fetch(myConstclassName.BASE_URL+'/measures/getCity/'+this.state.formData.state)
          .then(response => response.json())
          .then(response =>{
          this.setState({city: response})
          }).catch(err => console.log(err))
        }
      }).catch(err => console.log(err))     
    }

    fetch(myConstClass.BASE_URL+'/ingredient/getRIngredients/')
  .then(response => response.json())
  .then(response =>{
    let i=1;  
  response.forEach(element => {
    let id=element.uid;let data ='';
    
    let measures = element.measures;
    measures.map((ele,index) => {
    //  alert(ele.singular_name);
      // if(index == 0){
      //   data = <select>;
      // }
      data = <select><option>{ele.singular_name}</option></select>
    });
   // data += </select>;
    element.measures = data;
  element.action = <div><Icon.PlusCircle style={{margin:'0px 15px 0px 0px',cursor:'Pointer',width: '20px'}} onClick={() =>this.add(id)} /></div>;
   // console.log(element);
   element.uid = i;
   i++;
  });

  this.setState({tableData: response})
  document.querySelector('.react-bootstrap-table').style.minHeight  = "243px";
}).catch(err => console.log(err))

fetch(myConstClass.BASE_URL+'/measures/getSource/')
  .then(response => response.json())
  .then(response =>{
  this.setState({source: response})
}).catch(err => console.log(err))

fetch(myConstClass.BASE_URL+'/measures/getNutrients/')
  .then(response => response.json())
  .then(response =>{
  this.setState({nutrient: response})
}).catch(err => console.log(err))


fetch(myConstclassName.BASE_URL+'/recipe/getRecipesMethod/'+this.state.user_id)
.then(response => response.json())
.then(response =>{
this.setState({recipe_cooking_method: response})

}).catch(err => console.log(err))


  fetch(myConstclassName.BASE_URL+`/recipe/getRecipeIngredientInfo/`+this.state.user_id, {
    method: 'POST',
   
  }).then(response =>  response.json()).then((response) => {
    if(response){
    this.setState({recipe_ingredients: response})
   // alert(response['0'].micronutrients_array);
    this.state.total_energy = 0;this.state.total_fat = 0;this.state.total_carbohydrate = 0;this.state.total_protein = 0;
    this.state.recipe_ingredients.map((ele,index) => {
      this.state.total_energy += parseFloat(ele.energy);
      this.state.total_fat += parseFloat(ele.fat);
      this.state.total_carbohydrate += parseFloat(ele.carbohydrate);
      this.state.total_protein += parseFloat(ele.protein);
      this.state.total_fiber += parseFloat(ele.fiber);
      if(response['0'].micronutrients_array){
        fetch(myConstclassName.BASE_URL+`/recipe/getRecipeNutrients/`+this.state.user_id+'/0/'+ele.quantity+'/'+ele.measure_id+'/'+ele.ingredient_id, {   
          method: 'POST',
          body: JSON.stringify(response['0'].micronutrients_array),
        }).then(response =>  response.json()).then((response) => {
          if(response)
          this.setState({recipe_nutrients: response})
        });
      }
    });

    let fat_calories = parseFloat(this.state.total_fat).toFixed('2') * 9;
    let carbohdrate_calories = parseFloat(this.state.total_carbohydrate).toFixed('2') * 4;
    let protein_calories = parseFloat(this.state.total_protein).toFixed('2') * 4;
    let total_calories = parseFloat(fat_calories) + parseFloat(carbohdrate_calories) + parseFloat(protein_calories);
    //alert(this.state.total_energy);
    let chart_protein = (protein_calories/total_calories)*100;
    let carbohdrate_protein = (carbohdrate_calories/total_calories)*100;
    let fat_protein = (fat_calories/total_calories)*100;
    if(fat_protein || carbohdrate_protein ||chart_protein){//alert();
    this.setState({series: [fat_protein,carbohdrate_protein,chart_protein]});
    }
    
  }
  });

  }

  handleStateChange = (event) => {

    //alert(event.target.value);
    if(event.target.value){

      const { formData } = this.state;
      formData['state'] = event.target.value;
      this.setState({ formData }); 
      //this.setState({state: event.target.value})
      fetch(myConstclassName.BASE_URL+'/measures/getCity/'+event.target.value)
.then(response => response.json())
.then(response =>{
this.setState({city: response})
}).catch(err => console.log(err))

fetch(myConstClass.BASE_URL+'/ingredient/getIngredients/'+this.sid+'/'+this.nid+'/'+event.target.value+'/'+$('#source_city').val())
.then(response => response.json())
.then(response =>{
  let i=1;  
response.forEach(element => {
  let id=element.uid;
element.action = <div><Icon.PlusCircle style={{margin:'0px 15px 0px 0px',cursor:'Pointer',width: '20px'}} onClick={() =>this.add(id)} /></div>;
 // console.log(element);
 element.uid = i;
 i++;
});
this.setState({tableData: response})

}).catch(err => console.log(err))
    }
      
    
  }

  handleCityChange = (event) => {

    //alert(event.target.value);
    if(event.target.value){

      const { formData } = this.state;
      formData['city'] = event.target.value;
      this.setState({ formData }); 
     

fetch(myConstClass.BASE_URL+'/ingredient/getIngredients/'+this.sid+'/'+this.nid+'/'+$('#source_state').val()+'/'+$('#source_city').val())
.then(response => response.json())
.then(response =>{
  let i=1;  
response.forEach(element => {
  let id=element.uid;
element.action = <div><Icon.PlusCircle style={{margin:'0px 15px 0px 0px',cursor:'Pointer',width: '20px'}} onClick={() =>this.add(id)} /></div>;
 // console.log(element);
 element.uid = i;
 i++;
});
this.setState({tableData: response})

}).catch(err => console.log(err))
    }
      
    
  }


  handleChange = (event) => {

  
    // if($('#rqty').val() !='1' || $('#rqty').val() !='100'){
    //   this.setState({ recipe_ingredients_quantity: event.target.value });
    // }
    if(event.target.name=='source' && event.target.value=='2'){

        fetch(myConstclassName.BASE_URL+'/measures/getState/101')
          .then(response => response.json())
          .then(response =>{
          this.setState({state: response})
        }).catch(err => console.log(err))

      $('#source_div').show();
    }
    if(event.target.name=='source' && event.target.value!='2'){
      $('#source_div').hide();
    }
    const { formData } = this.state;
    formData[event.target.name] = event.target.value;
    this.setState({ formData });   

    if(event.target.name=='cooking_method'){
      this.setState({ cooking_description: event.target.value });
    }   

    if(event.target.name=='measures'){
      let old_grams = this.state.recipe_ingredients_quantity;
      this.setState({ recipe_ingredients_measure_id: event.target.value });
     
      if(event.target.value > 0)
      this.setState({ recipe_ingredients_quantity: 1 });
      else
      this.setState({ recipe_ingredients_quantity: old_grams });
    }
    if(event.target.name=='quantity'){
      this.setState({ recipe_ingredients_quantity: event.target.value });
    }
    if(event.target.name=='total_time_hour'){
      this.setState({ total_time_hour: event.target.value });
    }

    if(event.target.name=='total_ptime_hour'){
      this.setState({ total_ptime_hour: event.target.value });
    }
    
  }

  handleMeasure = () => {
    //alert('in');
    let cDivs = this.state.customDiv;
    cDivs.push('newDiv')
    this.setState({customDiv: cDivs })
  }

 

  

  remove(e) { 
    swal({
      title: "Are you sure?",
      text: "Are you sure that you want to delete this record?",
      icon: "warning",
      buttons: true,
      dangerMode: true,
    }).then((result) => {
      
      if (result){
    const options = {
      timeOut: parseInt(this.state.timeOut),
      showCloseButton: this.state.showCloseButton,
      progressBar: this.state.progressBar,
      position: this.state.position
    };
    this.flag = 1;
    fetch(myConstClass.BASE_URL+`/recipe/deleteRecipe`, {
    method: 'POST',
    body: e,
  }).then(toastr.success(
    'Success',
    "Recipe Deleted Successfully..!",
    options
  )
  )
  .catch();
  this.props.history.push('/recipe');
}
    });

  
  }

  toggle(){
    this.setState({ modal: true });
    
  };

  toggle1(id){
   
    this.setState({ modal1: true });
    if(id){
      this.recipe_cooking_id = id;
      fetch(myConstclassName.BASE_URL+`/recipe/getRecipeCookingInfo/`+id, {
        method: 'POST',
      
      }).then(response =>  response.json()).then((response) => {
        if(response){
        this.setState({ cooking_description: response.description }); 
       
        }
      });
    }
  };

  
  toggle4(ingredient_id,id){
    //alert(ingredient_id);
    //alert(id);
    this.recipe_ingredient_id = id;
    this.ingredient_id = ingredient_id;
    fetch(myConstclassName.BASE_URL+`/ingredient/getIngredientMeasures/`+ingredient_id, {
      method: 'POST',
     
    }).then(response =>  response.json()).then((response) => {
      this.setState({recipe_ingredients_measures: response})
    });

    fetch(myConstclassName.BASE_URL+`/recipe/getRecipeIngredientsInfo/`+id, {
      method: 'POST',
     
    }).then(response =>  response.json()).then((response) => {
      this.setState({recipe_ingredients_quantity: response.quantity})
      this.setState({recipe_ingredients_measure_id: response.measure_id})
    });
    this.setState({ modal4: true });
    this.setState({ modal1: false });
    this.setState({ modal: false });
  };

  deleteCooking(id){
    //alert(ingredient_id);
   // this.recipe_ingredient_id = id;
   // this.ingredient_id = ingredient_id;
    const options = {
      timeOut: parseInt(this.state.timeOut),
      showCloseButton: this.state.showCloseButton,
      progressBar: this.state.progressBar,
      position: this.state.position
    };
    fetch(myConstclassName.BASE_URL+`/recipe/deleteCooking/`+id, {
      method: 'POST',
    }).then(response => response.json())
      .then(response =>{
        if(response){

          fetch(myConstclassName.BASE_URL+'/recipe/getRecipesMethod/'+this.state.user_id)
          .then(response => response.json())
          .then(response =>{
          this.setState({recipe_cooking_method: response})
          // let dhtml = '';
          // response.map((data,index) => {
          //  dhtml += '<div class="iclass">'+data.description+'</div>';
          // });
         
          // $('#mbody').html(dhtml);
        }).catch(err => console.log(err))

          toastr.success(
            'Success',
            "Cooking Method Deleted Successfully..!",
            this.options
          )

        }else{
          
        }
   
      })
    .catch();

    
  };

  deleteIngredients(ingredient_id,id){
    //alert(ingredient_id);
    this.recipe_ingredient_id = id;
    this.ingredient_id = ingredient_id;
    const options = {
      timeOut: parseInt(this.state.timeOut),
      showCloseButton: this.state.showCloseButton,
      progressBar: this.state.progressBar,
      position: this.state.position
    };
    fetch(myConstclassName.BASE_URL+`/recipe/deleteIngredients/`+id, {
      method: 'POST',
    }).then(response => response.json())
      .then(response =>{
        if(response){

          fetch(myConstclassName.BASE_URL+`/recipe/getRecipeIngredientInfo/`+this.state.user_id, {
            method: 'POST',
           
          }).then(response =>  response.json()).then((response) => {
            this.setState({recipe_ingredients: response})
    let total_energy = 0;let total_fat = 0;let total_carbohydrate = 0;let total_protein = 0;
    let total_fiber = 0;
    response.map((ele,index) => {
       total_energy += parseFloat(ele.energy)
      total_fat += parseFloat(ele.fat);
     total_carbohydrate += parseFloat(ele.carbohydrate);
      total_protein += parseFloat(ele.protein);
      total_fiber += parseFloat(ele.fiber);
    });
    this.setState({total_energy: total_energy})
    this.setState({total_fat: total_fat})
    this.setState({total_carbohydrate: total_carbohydrate})
    this.setState({total_protein: total_protein})
    this.setState({total_fiber: total_fiber})
    let fat_calories = parseFloat(this.state.total_fat) * 9;
    let carbohdrate_calories = parseFloat(this.state.total_carbohydrate) * 4;
    let protein_calories = parseFloat(this.state.total_protein) * 4;
    let total_calories = parseFloat(fat_calories) + parseFloat(carbohdrate_calories) + parseFloat(protein_calories);
    //alert(this.state.total_energy);
    let chart_protein = (protein_calories/total_calories)*100;
    let carbohdrate_protein = (carbohdrate_calories/total_calories)*100;
    let fat_protein = (fat_calories/total_calories)*100;
    if(fat_protein || carbohdrate_protein ||chart_protein){//alert();
    this.setState({series: [fat_protein,carbohdrate_protein,chart_protein]});
    }
    fetch(myConstclassName.BASE_URL+`/recipe/getRecipeNutrients/`+this.state.user_id, {
      method: 'POST',
      body: JSON.stringify(response['0'].micronutrients_array),
    }).then(response =>  response.json()).then((response) => {
      if(response)
      this.setState({recipe_nutrients: response})
    });

  
    //alert(this.state.total_energy);
    toastr.success(
      'Success',
      "Ingredients Deleted Successfully..!",
      this.options
    )

          });

         
        }else{
          
        }
   
      })
    .catch();

    
  };


  removetoggle(){
    this.setState({ modal: false });
    
  };

  removetoggle4(){
    this.setState({ modal4: false });
    
  };

  removetoggle1(){
    this.setState({ modal1: false });
    
  };

  changeSource= (event) =>{
    // alert(event);
     //console.log('Event : ',e);
     this.sid=event;
     fetch(myConstClass.BASE_URL+'/ingredient/getIngredients/'+this.sid+'/'+this.nid)
   .then(response => response.json())
   .then(response =>{
     let i=1;  
   response.forEach(element => {
     let id=element.uid;
   element.action = <div><Icon.PlusCircle style={{margin:'0px 15px 0px 0px',cursor:'Pointer',width: '20px'}} onClick={() =>this.add(id)} /></div>;
    // console.log(element);
    element.uid = i;
    i++;
   });
   this.setState({tableData: response})
   
 }).catch(err => console.log(err))

    if(event =='2'){
      fetch(myConstclassName.BASE_URL+'/measures/getState/101')
  .then(response => response.json())
  .then(response =>{
  this.setState({state: response})
}).catch(err => console.log(err))

fetch(myConstClass.BASE_URL+'/ingredient/getIngredients/'+this.sid+'/'+this.nid+'/'+this.state.formData.state+'/'+$('#source_city').val())
   .then(response => response.json())
   .then(response =>{
     let i=1;  
   response.forEach(element => {
     let id=element.uid;
   element.action = <div><Icon.PlusCircle style={{margin:'0px 15px 0px 0px',cursor:'Pointer',width: '20px'}} onClick={() =>this.add(id)} /></div>;
    // console.log(element);
    element.uid = i;
    i++;
   });
   this.setState({tableData: response})
   
 }).catch(err => console.log(err))
    }else{
      this.setState({state: ''});
      this.setState({city: ''});
    }

   }
 
   changenutrient= (event) =>{
     this.nid=event;
     // alert(event);
      //console.log('Event : ',e);
      fetch(myConstClass.BASE_URL+'/ingredient/getIngredients/'+this.sid+'/'+this.nid)
    .then(response => response.json())
    .then(response =>{
      let i=1;  
    response.forEach(element => {
      let id=element.uid;
    element.action = <div><Icon.PlusCircle style={{margin:'0px 15px 0px 0px',cursor:'Pointer',width: '20px'}} onClick={() =>this.add(id)} /></div>;
     // console.log(element);
     element.uid = i;
     i++;
    });
    this.setState({tableData: response})
    
  }).catch(err => console.log(err))
    }

  handleValidSubmit = (e) => {
    e.preventDefault();
    this.setState({ submitted: true }, () => {
      
        setTimeout(() => this.setState({ submitted: false }), 5000);
        fetch(myConstclassName.BASE_URL+`/recipe/add/`+this.state.user_id, {
                method: 'POST',
                body: JSON.stringify($('#pform').serializeArray()),
              }).then(response =>  response.json()).then((response) => {
                if(response){
                  (this.state.user_id =='0' ) ?
                  toastr.success(
                    'Success',
                    "Recipe Added Successfully..!",
                    this.options
                  ) : toastr.success(
                    'Success',
                    "Recipe Updated Successfully..!",
                    this.options
                  );
                  //alert('in');
                  //this.props.history.push('/recipe/listing');

                }else{
                  toastr.error(
                    'Error',
                    "Recipe not Added..!",
                    this.options
                  )
                }
              })
              .catch();
    });
  }

  handleValidMeasuresSubmit= (e) => {
    e.preventDefault();
    this.setState({ submitted1: true }, () => {
      
        setTimeout(() => this.setState({ submitted1: false }), 5000);
        fetch(myConstclassName.BASE_URL+`/recipe/addMeasures/`+this.state.user_id, {
                method: 'POST',
                body: JSON.stringify($('#pmform').serializeArray()),
              }).then(response =>  response.json()).then((response) => {
                if(response){
                  (this.state.user_id =='0' ) ?
                  toastr.success(
                    'Success',
                    "Recipe Measures Added Successfully..!",
                    this.options
                  ) : toastr.success(
                    'Success',
                    "Recipe Measures Updated Successfully..!",
                    this.options
                  );
                  //alert('in');
                  //this.props.history.push('/recipe/listing');

                }else{
                  toastr.error(
                    'Error',
                    "Recipe Measures not Added..!",
                    this.options
                  )
                }
              })
              .catch();
    });
  }

  showtick(id){
    if(id)
    $('#tickinput').show();
    else
    $('#tickinput').hide();
  }

  handleSinChange=(event)=>{
    var arr=[];
  $("input:text[name^='sinname_']").each(function(v){ 
    //alert($( this ).val() );
    arr.push($( this ).val());
  });
    const { formData } = this.state;
    formData['sinarr'] = arr;
    this.setState({ formData });
  }

  handleMquantityChange=(event)=>{
    var arr=[];
  $("input:text[name^='mquantity_']").each(function(v){ 
    //alert($( this ).val() );
    arr.push($( this ).val());
  });
    const { formData } = this.state;
    formData['quantityarr'] = arr;
    this.setState({ formData });
  }

  handleGramsChange=(event)=>{
    var arr=[];
  $("input:text[name^='grams_']").each(function(v){ 
    //alert($( this ).val() );
    arr.push($( this ).val());
  });
    const { formData } = this.state;
    formData['gramsarr'] = arr;
    this.setState({ formData });
  }

  handlePortionChange=(event)=>{
    var arr=[];
  $("input:text[name^='portion_']").each(function(v){ 
    //alert($( this ).val() );
    arr.push($( this ).val());
  });
    const { formData } = this.state;
    formData['portionarr'] = arr;
    this.setState({ formData });
  }

  handlePluChange=(event)=>{
    var arr=[];
  $("input:text[name^='pluname_']").each(function(v){ 
    //alert($( this ).val() );
    arr.push($( this ).val());
  });
    const { formData } = this.state;
    formData['pluarr'] = arr;
    this.setState({ formData });
  }

  changeInput=(event)=>{
    
    $('#total_time_input').hide();
    $('#total_time_hour').show();
    $('#total_time_minute').show();
  }
  changePInput=(event)=>{
    
    $('#preparation_time').hide();
    $('#total_ptime_hour').show();
    $('#total_ptime_minute').show();
  }

  calculate(){//alert();
  //   alert(this.ingredient_id);
  //   alert(this.recipe_ingredient_id);
  //  alert($('#rmeasures').val());
  //   alert($('#rqty').val());
        if($('#rqty').val() > 0){
  fetch(myConstclassName.BASE_URL+`/recipe/calculate/`+this.state.user_id+'/'+this.recipe_ingredient_id+'/'+$('#rqty').val()+'/'+$('#rmeasures').val()+'/'+this.ingredient_id, {
    method: 'POST',
   
  }).then(response =>  response.json()).then((response) => {
    //this.setState({recipe_ingredients: response})

    fetch(myConstclassName.BASE_URL+`/recipe/getRecipeIngredientInfo/`+this.state.user_id, {
      method: 'POST',
     
    }).then(response =>  response.json()).then((response) => {
      this.setState({recipe_ingredients: response})
      this.state.total_fiber = 0;
    this.state.total_energy = 0;this.state.total_fat = 0;this.state.total_carbohydrate = 0;this.state.total_protein = 0;
    response.map((ele,index) => {
      this.state.total_energy += parseFloat(ele.energy);
      this.state.total_fat += parseFloat(ele.fat);
      this.state.total_carbohydrate += parseFloat(ele.carbohydrate);
      this.state.total_protein += parseFloat(ele.protein);
      this.state.total_fiber += parseFloat(ele.fiber);
    });
    let fat_calories = parseFloat(this.state.total_fat) * 9;
    let carbohdrate_calories = parseFloat(this.state.total_carbohydrate) * 4;
    let protein_calories = parseFloat(this.state.total_protein) * 4;
    let total_calories = parseFloat(fat_calories) + parseFloat(carbohdrate_calories) + parseFloat(protein_calories);
    //alert(this.state.total_energy);
    let chart_protein = (protein_calories/total_calories)*100;
    let carbohdrate_protein = (carbohdrate_calories/total_calories)*100;
    let fat_protein = (fat_calories/total_calories)*100;
    if(fat_protein || carbohdrate_protein ||chart_protein){//alert();
    this.setState({series: [fat_protein,carbohdrate_protein,chart_protein]});
    }
    toastr.success(
      'Success',
      "Recipe Ingredient Updated Successfully..!",
      this.options
    )
 
//alert($('#rqty').val());
    fetch(myConstclassName.BASE_URL+`/recipe/getRecipeNutrients/`+this.state.user_id+'/'+this.recipe_ingredient_id+'/'+$('#rqty').val()+'/'+$('#rmeasures').val()+'/'+this.ingredient_id, {
      method: 'POST',
      body: JSON.stringify(response['0'].micronutrients_array),
    }).then(response =>  response.json()).then((response) => {
      this.setState({recipe_nutrients: response})
    });
    this.setState({ modal4: false });
    });
   
 
      
  });
}else{
  swal({
   // title: "Are you sure?",
    text: "Quantity should be greater than 0.",
    buttons: true,
    dangerMode: true,
  })
  //alert('');
}
  }

  changeTotalTimeMinute(event){
   // alert($('#total_time_hour').val()+':'+event.target.value);
   
    if(event.target.name=='total_time_minute'){
      this.setState({ total_time_minute: event.target.value });
    }
  //  $('#total_time_input').val();
    const { formData } = this.state;
    formData['total_time'] = $('#total_time_hour').val()+':'+event.target.value;
    this.setState({ formData });
    $('#total_time_input').show();
    $('#total_time_hour').hide();
    $('#total_time_minute').hide();
  }

  changeTotalPTimeMinute(event){
    // alert($('#total_time_hour').val()+':'+event.target.value);
    
     if(event.target.name=='total_ptime_minute'){
       this.setState({ total_ptime_minute: event.target.value });
     }
   //  $('#total_time_input').val();
     const { formData } = this.state;
     formData['preparation_time'] = $('#total_ptime_hour').val()+':'+event.target.value;
     this.setState({ formData });
     $('#preparation_time').show();
     $('#total_ptime_hour').hide();
     $('#total_ptime_minute').hide();
   }

render () {  
  //alert(this.state.series);
 // alert(this.state.cooking_description);
 
  const { recipe_nutrients,submitted1,recipe_cooking_method,modal,submitted,source,nutrient,modal1,recipe_ingredients,modal4,recipe_ingredients_measures,formData} = this.state;
  const cnt_rn = recipe_nutrients.length;
  //alert(this.state.user_id);
  return(
  <Container fluid>
    <Header>
      <HeaderTitle>{(this.state.user_id =='0' ) ? 'Add' : 'Edit' }</HeaderTitle>

      <Breadcrumb>
        <BreadcrumbItem>
          <Link to="/dashboard">Dashboard</Link>
        </BreadcrumbItem>
        <BreadcrumbItem>
          <Link to="/recipe/listing">Recipe</Link>
        </BreadcrumbItem>
        <BreadcrumbItem active>{(this.state.user_id =='0' ) ? 'Add' : 'Edit' }</BreadcrumbItem>
      </Breadcrumb>
    </Header>
    <Row>
      <Col md="6" lg="4">
      <Card>
    <CardImg top width="100%" src={avatar2} alt="Card image cap" style={{height: '294px'}}/>
    <CardHeader>
      <CardTitle tag="h5" className="mb-0">
      
      </CardTitle>
    </CardHeader>
    <CardBody>
      <CardText>
      <button class="btn btn-outline-success form-control">Print Recipe</button><br/><br/>
      {(this.state.user_id =='0' ) ? '' : <button class="btn btn-outline-danger form-control" onClick={() =>this.remove(this.state.user_id)}>Delete Recipe</button>}
      
      </CardText>
     
    </CardBody>
  </Card>
      </Col>
      <Col md="6" lg="8">
      <Card>
    <CardHeader>
      <CardTitle tag="h2" className="mb-0">
        Basic Information
      </CardTitle>
    </CardHeader>
    <CardBody>
      <CardText>
      <Form id="pform" onSubmit={this.handleValidSubmit}>
         
      <Row>
            <Col lg={12}>
      <InputGroup className="mb-3">
            <InputGroupAddon addonType="prepend">Name</InputGroupAddon>
            <Input name="name" value={this.state.formData.name} onChange={this.handleChange} required/>
            </InputGroup>
            </Col>
            <Col lg={12}>
      <InputGroup className="mb-3">
            <InputGroupAddon addonType="prepend">Description</InputGroupAddon>
      <textarea name="description" class="form-control" value={this.state.formData.description} onChange={this.handleChange} required />   
            </InputGroup>
            </Col>
            <Col lg={12}>
      <InputGroup className="mb-3">
            <InputGroupAddon addonType="prepend">Total Time</InputGroupAddon>
            <CustomInput style={{display:'none'}}
                type="select"
                id="total_time_hour"
                name="total_time_hour"
                value={this.state.total_time_hour}
                onChange={this.handleChange}
                //onChange={event => this.changeSource(event.target.value)}
                
              ><option value="">hour</option><option value="0">00</option><option value="1">01</option><option value="2">02</option><option value="3">03</option><option value="4">04</option><option value="5">05</option><option value="6">06</option><option value="7">07</option><option value="8">08</option><option value="9">09</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option><option value="21">21</option><option value="22">22</option><option value="23">23</option></CustomInput>
            <CustomInput style={{display:'none'}}
                type="select"
                id="total_time_minute"
                name="total_time_minute"               
                onChange={event => this.changeTotalTimeMinute(event)}
                value={this.state.total_time_minute}
              ><option value="">minute</option><option value="0">00</option><option value="5">05</option><option value="10">10</option><option value="15">15</option><option value="20">20</option><option value="25">25</option><option value="30">30</option><option value="35">35</option><option value="40">40</option><option value="45">45</option><option value="50">50</option><option value="55">55</option></CustomInput>
             <Input id="total_time_input" name="total_time" value={this.state.formData.total_time} onChange={this.handleChange} onFocus={this.changeInput} required/>
            </InputGroup>
            </Col>
            <Col lg={12}>
      <InputGroup className="mb-3">
            <InputGroupAddon addonType="prepend">Preparation Time</InputGroupAddon>
            <CustomInput style={{display:'none'}}
                type="select"
                id="total_ptime_hour"
                name="total_ptime_hour"
                value={this.state.total_ptime_hour}
                onChange={this.handleChange}
                //onChange={event => this.changeSource(event.target.value)}
                
              ><option value="">hour</option><option value="0">00</option><option value="1">01</option><option value="2">02</option><option value="3">03</option><option value="4">04</option><option value="5">05</option><option value="6">06</option><option value="7">07</option><option value="8">08</option><option value="9">09</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option><option value="21">21</option><option value="22">22</option><option value="23">23</option></CustomInput>
            <CustomInput style={{display:'none'}}
                type="select"
                id="total_ptime_minute"
                name="total_ptime_minute"               
                onChange={event => this.changeTotalPTimeMinute(event)}
                value={this.state.total_ptime_minute}
              ><option value="">minute</option><option value="0">00</option><option value="5">05</option><option value="10">10</option><option value="15">15</option><option value="20">20</option><option value="25">25</option><option value="30">30</option><option value="35">35</option><option value="40">40</option><option value="45">45</option><option value="50">50</option><option value="55">55</option></CustomInput>
            
            <Input id="preparation_time" name="preparation_time" value={this.state.formData.preparation_time} onChange={this.handleChange} onFocus={this.changePInput} required/>
            </InputGroup>
            </Col>
            <Col lg={12}>
      <InputGroup className="mb-3">
            <InputGroupAddon addonType="prepend">Final Weight</InputGroupAddon>
            <Input name="weight" value={this.state.formData.weight} onChange={this.handleChange} required/>
            <InputGroupAddon addonType="append">grams</InputGroupAddon>
            </InputGroup>
            </Col>
            <Col lg={12}>
      <InputGroup className="mb-3">
            <InputGroupAddon addonType="prepend">Portions</InputGroupAddon>
            <Input name="portions" value={this.state.formData.portions} onChange={this.handleChange} required/>
            </InputGroup>
            </Col>
            </Row>           
            <Row>
          <Col lg={12}>
          <FormGroup>
          <Link to="/recipe" style={{margin:"0rem 1.5rem 1.5rem 0rem",border: "#6f42c1 1px solid",color: "#6f42c1",padding: "0.10rem 0.90rem 0.30rem 0.90rem",textDecoration: 'none',borderRadius:'0.2rem'}}>Cancel</Link>
          {(this.state.user_id !='0' ) ? <Button disabled={submitted}>{
                        (submitted && 'Your form is submitted!')
                        || (!submitted && 'Update')
                    }</Button> : <Button disabled={submitted}>{
                        (submitted && 'Your form is submitted!')
                        || (!submitted && 'Add')
                    }</Button> }         
          </FormGroup>
          </Col>
          </Row>
            </Form>
      </CardText>
     
    </CardBody>
  </Card>
      </Col>
      </Row>
      <Tabs defaultActiveKey="home" id="uncontrolled-tab-example">
            <Tab eventKey="home" title="Creation" ><br/>
    <Row>
    <Col md="8" lg="8">
      <Col md="12" lg="12">
      <Card>
    <CardHeader>
      <CardTitle tag="h1" className="mb-0">
       Ingredients
       <button class="mr-1 mb-1 btn btn-sm btn-outline-secondary"  onClick={() => this.toggle()} style={{float:'right',margin:'auto'}}><Icon.PlusCircle /></button>
      </CardTitle>
    </CardHeader>
    <CardBody>
    <div id="ibody">
   { recipe_ingredients ? recipe_ingredients.map((ele,index) => {
       if(ele.measure_id =='0'){
         //this.state.total_enery += ele.energy;
        return(<div>
          <div class="row">
            <div class="col-md-12">{ele.quantity} grams of {ele.title}</div>
            </div><br/>
          <div className="search-result-elements">
            <div className="search-result-element search-result-unit">{ele.quantity} Grams</div>
            <div className="search-result-element search-result-information">{ele.title}</div><div className="search-result-element search-result-summary">
          <div className="information energy_kcal">
          <div class="title"><div class="value">{ele.energy}<div class="unit">kcal</div></div></div>
          <div class="description">Energy</div></div>
          <div className="information fat">
          <div class="title"><div class="value">{ele.fat}<div class="unit">g</div></div></div>
          <div class="description">Fat</div></div>          
          <div className="information carbohydrate">
          <div class="title"><div class="value">{ele.carbohydrate}<div class="unit">g</div></div></div>
          <div class="description">Carbohydrate</div></div>
          <div className="information protein"><div class="title"><div class="value">{ele.protein}<div class="unit">g</div></div></div>
          <div class="description">Protein</div></div>
          <div className="information actions"><Icon.Edit2 size="18" style={{'cursor':'pointer'}} onClick={() => this.toggle4(ele.ingredient_id,ele.id)} />&nbsp;&nbsp;<Icon.Trash size="18" style={{'cursor':'pointer'}} onClick={() => this.deleteIngredients(ele.ingredient_id,ele.id)} /></div></div></div><hr/></div>);
   
         // return(<div><div class="row"><div class="col-md-12">{ele.quantity} {ele.plural_name} of {ele.title}({ele.grams} grams)</div></div><br/><div class="row"><div class="col-md-3">{ele.quantity} Grams</div><div class="col-md-3">{ele.title}</div><div class="col-md-1">{ele.energy} Kcal</div><div class="col-md-1">{ele.fat} g</div><div class="col-md-1">{ele.carbohydrate} g</div><div class="col-md-1">{ele.protein} g</div><div class="col-md-2"><Icon.Edit2 style={{'cursor':'pointer'}} onClick={() => this.toggle4(ele.ingredient_id,ele.id)} />&nbsp;&nbsp;<Icon.Trash style={{'cursor':'pointer'}} onClick={() => this.deleteIngredients(ele.ingredient_id,ele.id)} /></div></div><hr/></div>);
       }else if(ele.measure_id){
        if((ele.quantity*ele.mqty) > 1){
          ele.plural_name = ele.plural_name;
        }else{
          ele.plural_name = ele.singular_name;
        }
       // this.state.total_enery += ele.energy;
         // mdata += '<div class="iclass">'+ele.title+'<hr/>100 '+ele.measure_id+'<span class="mclass">'+ele.title+'<span class="mclass">'+ele.energy+' Kcal</span><span class="mclass">'+ele.fat+' g</span><span class="mclass">'+ele.carbohydrate+' g</span><span class="mclass">'+ele.protein+' g</span></div>';
      //   return(<div><div class="row"><div class="col-md-12">{ele.quantity} {ele.plural_name} of {ele.title}({ele.grams} grams)</div></div><br/><div class="row"><div class="col-md-3">{ele.quantity} {ele.plural_name}({ele.grams} grams)</div><div class="col-md-3">{ele.title}</div><div class="col-md-1">{ele.energy} Kcal</div><div class="col-md-1">{ele.fat} g</div><div class="col-md-1">{ele.carbohydrate} g</div><div class="col-md-1">{ele.protein} g</div><div class="col-md-2"><Icon.Edit2 style={{'cursor':'pointer'}} onClick={() => this.toggle4(ele.ingredient_id,ele.id)} />&nbsp;&nbsp;<Icon.Trash style={{'cursor':'pointer'}} onClick={() => this.deleteIngredients(ele.ingredient_id,ele.id)}/></div></div><hr/></div>);
        //  return(<div><div class="row"><div class="col-md-12">{ele.quantity} {ele.plural_name} of {ele.title}({ele.grams} grams)</div></div><br/><div className="search-result-elements"><div className="search-result-elements">{ele.quantity} {ele.plural_name}({ele.grams} grams)</div><div className="search-result-elements">{ele.title}</div><div className="search-result-element search-result-summary"><div className="information energy_kcal">{ele.energy} Kcal</div><div className="information fat">{ele.fat} g</div>
        //  <div className="information carbohydrate">{ele.carbohydrate} g</div><div className="information protein">{ele.protein} g</div><div className="information action"><Icon.Edit2 style={{'cursor':'pointer'}} onClick={() => this.toggle4(ele.ingredient_id,ele.id)} />&nbsp;&nbsp;<Icon.Trash style={{'cursor':'pointer'}} onClick={() => this.deleteIngredients(ele.ingredient_id,ele.id)}/></div></div></div><hr/></div>);
        return(<div>
          <div class="row">
            
            <div class="col-md-12">{ele.quantity*ele.mqty} {ele.plural_name} of {ele.title} ({ele.quantity * ele.grams} grams)</div>
            </div><br/>
          <div className="search-result-elements">
            <div className="search-result-element search-result-unit">{ele.mqty} {ele.plural_name} ({ele.grams} grams)</div>
            <div className="search-result-element search-result-information">{ele.title}</div><div className="search-result-element search-result-summary">
          <div className="information energy_kcal">
          <div class="title"><div class="value">{ele.energy}<div class="unit">kcal</div></div></div>
          <div class="description">Energy</div></div>
          <div className="information fat">
          <div class="title"><div class="value">{ele.fat}<div class="unit">g</div></div></div>
          <div class="description">Fat</div></div>          
          <div className="information carbohydrate">
          <div class="title"><div class="value">{ele.carbohydrate}<div class="unit">g</div></div></div>
          <div class="description">Carbohydrate</div></div>
          <div className="information protein"><div class="title"><div class="value">{ele.protein}<div class="unit">g</div></div></div>
          <div class="description">Protein</div></div>
          <div className="information actions"><Icon.Edit2 size="18" style={{'cursor':'pointer'}} onClick={() => this.toggle4(ele.ingredient_id,ele.id)} />&nbsp;&nbsp;<Icon.Trash size="18" style={{'cursor':'pointer'}} onClick={() => this.deleteIngredients(ele.ingredient_id,ele.id)} /></div></div></div><hr/></div>);
      
      }
      }) :''
    }
    </div>
      <CardText> 
      <React.Fragment>
      <Modal centered isOpen={modal} toggle={() => this.toggle()} size="lg">
          <ModalHeader toggle={() => this.removetoggle()}>
            Ingredients
            
          </ModalHeader>
          <ModalBody className="text-center m-3"  style={{ 'height': '380px',
   'overflow': 'auto'}}>
           
          <Row>
            <Col md={3}>
              <CustomInput style={{marginLeft:'10px'}}
                type="select"
                id="exampleCustomSelect"
                name="source"
                className="mb-3"
                onChange={event => this.changeSource(event.target.value)}
                
              >
                <option value="0">All</option>
              {source ?  source.map((cell, i) => {
                        return(<option value={cell.id}>{cell.title}</option>)
                    }) : ''}
              </CustomInput>
            </Col>
            {this.state.state ?
            <Col md={3}>
            <CustomInput type="select" id="source_state" name="state" value={this.state.formData.state} onChange={this.handleStateChange}>
              <option value="0">Select State</option>
              {this.state.state ?  this.state.state.map((cell1, i1) => {
                 return(<option value={cell1.id}>{cell1.name}</option>)
            }) : ''}
            </CustomInput>
            </Col> :''}
            
            {this.state.city ?
            <Col md={3}>
            <CustomInput type="select" id="source_city" name="city" value={this.state.formData.city} onChange={this.handleCityChange} >
              {/* <option value="">Select...</option> */}
              {this.state.city ?  this.state.city.map((cell2, i2) => {
                 return(<option value={cell2.id}>{cell2.name}</option>)
            }) : ''}
            </CustomInput></Col>:''}
            
            <Col md={3}>
              <CustomInput style={{marginLeft:'10px'}}
                type="select"
                id="exampleCustomSelect"
                name="nutrient"
                className="mb-3"
                onChange={event => this.changenutrient(event.target.value)}
                
              >
                <option value="0">All</option>
              {nutrient ?  nutrient.map((cell, i) => {
                        return(<option value={cell.id}>{cell.title}</option>)
                    }) : ''}
              </CustomInput>
            </Col>     
          </Row>
          {this.state.tableData ?
        <ToolkitProvider
        keyField="name"
        data={this.state.tableData}
        columns={tableColumns}
        search
        exportCSV
      >
        {props => (
          <div>
            <CardHeader>
            <div className="float-left pull-left">
              
            <SearchBar { ...props.searchProps } />
       
            </div>
              <div className="float-right pull-right">
              
                <MyExportCSV {...props.csvProps} />
              </div><br/>
              {/* <CardTitle tag="h5">Export CSV</CardTitle>
              <h6 className="card-subtitle text-muted">
                Exportable CSV by react-bootstrap-table2
              </h6> */}
            </CardHeader>
            <CardBody>
              <BootstrapTable
                {...props.baseProps}
                bootstrap4
                bordered={false}
                filter={filterFactory()}
                pagination={paginationFactory({
                  sizePerPage: 25,
                  sizePerPageList: [5, 10, 25, 50]
                })}
              />
            </CardBody>
          </div>
        )}
      </ToolkitProvider> :''}
          </ModalBody>
          <ModalFooter>
            <Button color="secondary" onClick={() => this.removetoggle()}>
              Close
            </Button>
          </ModalFooter>
      </Modal>

      <Modal centered isOpen={modal4} toggle={() => this.toggle4()} size="lg">
          <ModalHeader toggle={() => this.removetoggle4()}>
            Ingredients
          </ModalHeader>
          <ModalBody className="text-center m-3">
           
           
           {recipe_ingredients_measures ?<div><Row> <Col md={2}>
             <label>Quantity</label></Col>
             <Col md={4}>
             <Input type="number" name="quantity" id="rqty" value={this.state.recipe_ingredients_quantity}  onChange={this.handleChange} />
              
               </Col></Row><br/>
             <Row> <Col md={2}>
             <label>Measures</label></Col>
             <Col md={4}>
      <CustomInput 
        type="select"
        id="rmeasures"
        name="measures"
        className="mb-3"
        value={this.state.recipe_ingredients_measure_id}
        onChange={this.handleChange} 
      >
       
       {recipe_ingredients_measures ?  recipe_ingredients_measures.map((cell, i) => {
         if(cell.quantity >1){
          return(<option value={cell.id}>{cell.quantity} {cell.plural_name}({cell.grams} grams, {cell.portion}% ediable)</option>)
         }else{
          return(<option value={cell.id}>{cell.quantity} {cell.singular_name}({cell.grams} grams, {cell.portion}% ediable)</option>)
         }
                
            }) : ''}
             <option value="0">grams</option>
      </CustomInput>
      </Col></Row></div>:''}
   
     
      
          </ModalBody>
          <ModalFooter>
          <Button color="primary" onClick={() => this.calculate()}>
              Save
            </Button>
            <Button color="secondary" onClick={() => this.removetoggle4()}>
              Close
            </Button>
          </ModalFooter>
      </Modal>
                  
              </React.Fragment> 
      </CardText>
    </CardBody>  
    </Card>
    </Col>  
      <Col md="12" lg="12">
      <Card>
    <CardHeader>
      <CardTitle tag="h1" className="mb-0">
      Cooking Method
       <button class="mr-1 mb-1 btn btn-sm btn-outline-secondary"  onClick={() => this.toggle1()} style={{float:'right',margin:'auto'}}><Icon.PlusCircle /></button>
      </CardTitle>
    </CardHeader>
    <CardBody>
    <div id="mbody"></div>
      <CardText> 
        {  recipe_cooking_method ? recipe_cooking_method.map((data,index) => {
          return(<div><div class="row iclass"><div class="col-md-10">{data.description}</div><div class="col-md-2"><Icon.Edit2 size="18" style={{'cursor':'pointer'}} onClick={() => this.toggle1(data.id)} />&nbsp;&nbsp;<Icon.Trash size="18" onClick={() => this.deleteCooking(data.id)} style={{'cursor':'pointer'}}/></div></div><br/></div>);
           }) :''
           
        }
      <React.Fragment>
      <Modal centered isOpen={modal1} toggle={() => this.toggle1()} size="lg">
          <ModalHeader >
            Cooking Method
          </ModalHeader>
          <ModalBody className="text-center m-3">
          <Form id="pmmform">
          <Row>
           
          <Col md={12}>
           <InputGroup className="mb-3">
            <InputGroupAddon addonType="prepend">Add Method</InputGroupAddon>
              <textarea name="cooking_method" id="cooking_method" class="form-control" onChange={this.handleChange} value={this.state.cooking_description ? this.state.cooking_description :''} required onFocus={() => this.showtick(1)} />  
              <InputGroupAddon id="tickinput" style={{'display':'none','cursor':'pointer','alignItems': 'center','width': '5%',
            'padding': '10px 10px'}} onClick={() => this.addMethod()} addonType="append"><Icon.Check /></InputGroupAddon> 
            </InputGroup>
            </Col>       
          </Row>
        </Form> 
        </ModalBody>
          <ModalFooter>
            <Button color="secondary" onClick={() => this.removetoggle1()}>
              Close
            </Button>
          </ModalFooter>
         </Modal>
       </React.Fragment> 
     </CardText>
    </CardBody>  
   </Card>
  </Col>  
   <Col md="12" lg="12">
  <Card>
    <CardHeader>
      <CardTitle tag="h1" className="mb-0">
      Common Measures
      <button class="mr-1 mb-1 btn btn-sm btn-outline-secondary"  onClick={this.handleMeasure} style={{float:'right',margin:'auto'}}><Icon.PlusCircle /></button>
      </CardTitle>
    </CardHeader>
    <CardBody>
    <Form id="pmform" onSubmit={this.handleValidMeasuresSubmit}>
    {this.state.customDiv.map((cdiv, i) => {
              return(
                <Row>
           <Col lg={8} style={{marginTop:'10px',padding:'5px 5px'}}>
           <div className="col-md-6 manage-food-modal" key={cdiv} data-common-measure-id="temp-`${i}`">
             <div className="field common-measure" style={{display: '-webkit-box'}}>
               <div className="multiple-fields collapse-margin">
                 <div className="field field-titled" style={{display: '-webkit-box'}}>
                    <div className="field-title">
                     <label className="string optional" for="food_common_measures__name">Singular name</label>
                    </div>
                    <div className="field field-input">
                      <div className="field-content no-padding">
                        <div className="form-group string required food_common_measures_name">
                          <input className="form-control string required" value={formData.sinarr ? formData.sinarr[i] :''} onChange={this.handleSinChange} type="text" name={"sinname_"+i} id="food_common_measures__name"/>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="field field-titled" style={{display: '-webkit-box'}}>
                    <div className="field-title">
                      <label className="string optional" for="food_common_measures__plural_name">Plural name</label>
                    </div>
                    <div className="field field-input">
                      <div className="field-content no-padding">
                        <div className="form-group string required food_common_measures_plural_name">
                          <input className="form-control string required" required="required" aria-required="true" type="text" name={"pluname_"+i} id="food_common_measures__plural_name" value={formData.pluarr ? formData.pluarr[i] :''} onChange={this.handlePluChange}/>
                        </div>
                      </div>
                    </div>
                    </div>

                    <div className="field field-titled" style={{display: '-webkit-box'}}>
                      <div className="field-title">
                        <label className="float optional" for="food_common_measures__quantity">Quantity</label>
                      </div>                                  
                      <div className="field field-input">
                        <div className="field-content no-padding">
                          <div className="form-group float required food_common_measures_quantity">
                            <input className="form-control numeric float required" greater_than="0" type="number" step="any" name={"mquantity_"+i} id="food_common_measures__quantity" value={formData.quantityarr ? formData.quantityarr[i] :''} onChange={this.handleMquantityChange}/>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div className="field field-titled" style={{display: '-webkit-box'}}>
                      <div className="field-title">
                        <label className="float optional" for="food_common_measures__grams">Total grams</label>
                      </div>
                      <div className="field field-input">
                        <div className="field-content no-padding">
                          <div className="form-group float required food_common_measures_grams">
                            <input className="form-control numeric float required" greater_than="0" type="number" step="any" name={"grams_"+i} id="food_common_measures__grams" value={formData.gramsarr ? formData.gramsarr[i] :''} onChange={this.handleGramsChange}/>
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <div className="field field-titled" style={{display: '-webkit-box'}}>
                      <div className="field-title">
                        <label className="float optional" for="food_common_measures__edible_portion_percentage">Edible portion (%)</label>
                      </div>
                      <div className="field field-input">
                        <div className="field-content no-padding">
                          <div className="form-group float optional food_common_measures_edible_portion_percentage">
                            <input className="form-control numeric float optional" greater_than="0" max="100" type="number" step="any" name={"portion_"+i} id="food_common_measures__edible_portion_percentage" value={formData.portionarr ? formData.portionarr[i] :''} onChange={this.handlePortionChange}/>
                            </div>
                        </div>
                      </div>
                    </div>
                </div>
                <label className="field-action field-action-remove" onClick={() => this.handleDeleteMeasure(i)}  style={{marginBottom: 'auto'}}>
                <Icon.Trash size="18"/></label>
              </div>
            </div>
            </Col>
            <Col lg={4}>
            {/* <p style={{marginTop:'10px',padding:'5px 5px',border:'solid 1px',cursor:'pointer'}} onClick={this.handleMeasure}><Icon.PlusSquare />&nbsp;&nbsp;Add New Measure</p>
             */}
            </Col>
            </Row>
              )
            }
            )}
            <br/>
             {(this.state.user_id !='0' ) ? <Button disabled={submitted1}>{
                        (submitted1 && 'Your form is submitted!')
                        || (!submitted1 && 'Update')
                    }</Button> : <Button disabled={submitted1}>{
                        (submitted1 && 'Your form is submitted!')
                        || (!submitted1 && 'Add')
                    }</Button> }      
            </Form>
    </CardBody>  
    </Card>
    </Col>  
    </Col>
    <Col md="4" lg="4" style={{'padding':' 0px 0px 0px 0px'}}>
      <Col md="12" lg="12">
      <Card>
    <CardHeader>
      <CardTitle tag="h1" className="mb-0">
       Global Analysis
       <div style={{'fontSize':'14px','fontWeight': '400'}}>Energy, macronutrients and fiber distribution</div>
       </CardTitle>
    </CardHeader>
    <CardBody>
     <label>Energy</label><span style={{'float':'right'}}>{this.state.total_energy ? this.state.total_energy : 0} Kcal</span><hr style={{'margin':'0px 0px'}}/><br/>
     <CircularProgressbar strokeWidth="4" value={this.state.total_fat ?(this.state.total_fat).toFixed('2') :0} text={`${this.state.total_fat ? (this.state.total_fat).toFixed('2') : 0}g`} styles={{
    // Customize the root svg element
    root: {},
    // Customize the path, i.e. the "completed progress"
    path: {
      // Path color
      stroke: `#DB4A65`,
      // Whether to use rounded or flat corners on the ends - can use 'butt' or 'round'
      strokeLinecap: 'butt',
      // Customize transition animation
      transition: 'stroke-dashoffset 0.5s ease 0s',
    },
    // Customize the circle behind the path, i.e. the "total progress"
    trail: {
      // Trail color
      stroke: '#d6d6d6',
    },
    // Customize the text
    text: {
      // Text color
      fill: '#000',
      // Text size
      fontSize: '25px',
    },
    // Customize background - only used when the `background` prop is true
    background: {
      fill: '#3e98c7',
    },
  }}/>&nbsp;&nbsp;
     <CircularProgressbar strokeWidth="4" value={this.state.total_carbohydrate ? (this.state.total_carbohydrate).toFixed('2') :0} text={`${this.state.total_carbohydrate ? (this.state.total_carbohydrate).toFixed('2') :0}g`} styles={{
    // Customize the root svg element
    root: {},
    // Customize the path, i.e. the "completed progress"
    path: {
      // Path color
      stroke: `#EA9F77`,
      // Whether to use rounded or flat corners on the ends - can use 'butt' or 'round'
      strokeLinecap: 'butt',
      // Customize transition animation
      transition: 'stroke-dashoffset 0.5s ease 0s',
    },
    // Customize the circle behind the path, i.e. the "total progress"
    trail: {
      // Trail color
      stroke: '#d6d6d6',
    },
    // Customize the text
    text: {
      // Text color
      fill: '#000',
      // Text size
      fontSize: '25px',
    },
    // Customize background - only used when the `background` prop is true
    background: {
      fill: '#3e98c7',
    },
  }}/>&nbsp;&nbsp;
     <CircularProgressbar strokeWidth="4" value={this.state.total_protein ? (this.state.total_protein).toFixed('2') :0} text={`${this.state.total_protein ? (this.state.total_protein).toFixed('2') :0}g`} styles={{
    // Customize the root svg element
    root: {},
    // Customize the path, i.e. the "completed progress"
    path: {
      // Path color
      stroke: `#1AB394`,
      // Whether to use rounded or flat corners on the ends - can use 'butt' or 'round'
      strokeLinecap: 'butt',
      // Customize transition animation
      transition: 'stroke-dashoffset 0.5s ease 0s',
    },
    // Customize the circle behind the path, i.e. the "total progress"
    trail: {
      // Trail color
      stroke: '#d6d6d6',
    },
    // Customize the text
    text: {
      // Text color
      fill: '#000',
      // Text size
      fontSize: '25px',
    },
    // Customize background - only used when the `background` prop is true
    background: {
      fill: '#3e98c7',
    },
  }}/>&nbsp;&nbsp;
     <CircularProgressbar strokeWidth="4" value={this.state.total_fiber ? (this.state.total_fiber).toFixed('2') :0} text={`${this.state.total_fiber ? (this.state.total_fiber).toFixed('2') :0}g`} styles={{
    // Customize the root svg element
    root: {},
    // Customize the path, i.e. the "completed progress"
    path: {
      // Path color
      stroke: `#6A7D93`,
      // Whether to use rounded or flat corners on the ends - can use 'butt' or 'round'
      strokeLinecap: 'butt',
      // Customize transition animation
      transition: 'stroke-dashoffset 0.5s ease 0s',
    },
    // Customize the circle behind the path, i.e. the "total progress"
    trail: {
      // Trail color
      stroke: '#d6d6d6',
    },
    // Customize the text
    text: {
      // Text color
      fill: '#000',
      // Text size
      fontSize: '25px',
    },
    // Customize background - only used when the `background` prop is true
    background: {
      fill: '#3e98c7',
    },
  }}/><br/><br/>
   <span style={{marginRight:'24px',marginLeft:'24px'}}>FAT</span><span style={{marginRight:'13px'}}>Carbohydrate</span><span style={{marginRight:'24px'}}>Protein</span><span style={{marginRight:'24px'}}>Fiber</span>
      </CardBody>
      </Card>
      </Col>
      {/* </Row>
      <Row> */}
     <Col md="12" lg="12">
      <Card>
    <CardHeader>
      <CardTitle tag="h1" className="mb-0">
      Macronutrients
       <div style={{'fontSize':'14px','fontWeight': '400'}}>Macronutrients distribution of the recipe</div>
       </CardTitle>
    </CardHeader>
    <CardBody>
      {this.state.series ?
      <div id="chart">
            <Chart options={this.state.chartoptions} series={this.state.series} type="pie"/>
          </div> :''}
          </CardBody>
</Card>
      </Col>
      {/* </Row>
      <Row> */}
     <Col md="12" lg="12">
      <Card>
    <CardHeader>
      <CardTitle tag="h1" className="mb-0">
      Micronutrients
       <div style={{'fontSize':'14px','fontWeight': '400'}}>Micronutrients distribution of the recipe</div>
       </CardTitle>
    </CardHeader>
    <CardBody>
     
    { recipe_nutrients ? recipe_nutrients.map((ele,index) => {
        if(ele.type =='2'){
      return(<div className="micronutrient"><div className="name">{ele.title}</div><div className="value-wrapper"><div className="current-value">{ele.nutrient_id}</div><div className="unit">{ele.symbol}</div></div></div>)
        }
    }):'' }
      </CardBody>
      </Card>
      </Col>
    </Col>
    </Row>
      </Tab>
      <Tab eventKey="common" title="Analysis" >
<Row>
  <Col md={12} lg={12}>
  <Card>
    <CardHeader>
      <CardTitle tag="h1" className="mb-0">
      Nutritional label
       <div style={{'fontSize':'14px','fontWeight': '400'}}>Check recipe's nutritional label</div>
       </CardTitle>
    </CardHeader>
    <CardBody>
    <table class="table table-striped">
      <thead>
        <tr>
        <th>Nutrient</th>
        <th>Value per 100g</th>
        {/* <th>DRI percentage</th> */}
        </tr>
      </thead>
      <tbody>
      { recipe_nutrients ? recipe_nutrients.map((ele,index) => {
        if(index == '0' || index == '3' || index == '39' || index == '1' || index == '4' || index == '6' || index == '9' || index == '12' || index == '21' ){
      return(<tr>
        <td>{ele.title}</td>
        <td><span class="value"></span>{ele.value_per_100grams}<span class="unit">&nbsp;&nbsp;{ele.symbol}</span></td>
        
        </tr>)
        }
    }):'' }
       
      </tbody>
    </table>
    </CardBody>
  </Card>
  </Col>
  <Col md={12} lg={12}>
  <Card>
    <CardHeader>
      <CardTitle tag="h1" className="mb-0">
      Nutritional information
       <div style={{'fontSize':'14px','fontWeight': '400'}}>Check recipe's nutritional information</div>
       </CardTitle>
    </CardHeader>
    <CardBody>
      <Row>
    <Col md={6} lg={6}>
    <table class="table table-striped">
      <thead>
        <tr>
        <th>Nutrient</th>
        <th>Yeild Value</th>
        </tr>
      </thead>
      <tbody>
      { recipe_nutrients ? recipe_nutrients.map((ele,index) => {
        if(index < (cnt_rn)/2){
      return(<tr>
        <td>{ele.title}</td>
        <td><span class="value"></span>{(ele.nutrient_id).toFixed('2')}<span class="unit">&nbsp;&nbsp;{ele.symbol}</span></td>
        </tr>)
        }
    }):'' }
        
      </tbody>
    </table>
    </Col>
    <Col md={6} lg={6}>
    <table class="table table-striped">
      <thead>
        <tr>
        <th>Nutrient</th>
        <th>Yeild Value</th>
        </tr>
      </thead>
      <tbody>
      { recipe_nutrients ? recipe_nutrients.map((ele,index) => {
        if(index >= (cnt_rn)/2){
      return(<tr>
        <td>{ele.title}</td>
        <td><span class="value"></span>{(ele.nutrient_id).toFixed('2')}<span class="unit">&nbsp;&nbsp;{ele.symbol}</span></td>
        </tr>)
        }
    }):'' }
      </tbody>
    </table>
    </Col>
    </Row>
    </CardBody>
  </Card>
  </Col>
  </Row>
      </Tab>
      </Tabs>
   </Container>
)
}
}

export default Validation;




















class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {values: []};
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  
  createUI(){
     return this.state.values.map((el, i) => 
         <div key={i}>
    	    <input type="text" value={el||''} onChange={this.handleChange.bind(this, i)} />
    	    <input type='button' value='remove' onClick={this.removeClick.bind(this, i)}/>
         </div>          
     )
  }
  
  handleChange(i, event) {
     let values = [...this.state.values];
     values[i] = event.target.value;
     this.setState({ values });
  }
  
  addClick(){
    this.setState(prevState => ({ values: [...prevState.values, '']}))
  }
  
  removeClick(i){
     let values = [...this.state.values];
     values.splice(i,1);
     this.setState({ values });
  }
  
  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.values.join(', '));
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
          {this.createUI()}        
          <input type='button' value='add more' onClick={this.addClick.bind(this)}/>
          <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('container'));