text: import React, {Component} from 'react'
  import ReactDOM from 'react-dom'
  import url from '../../url'
  import Swal from 'sweetalert2'
  import Axios from "axios"
  import Roles from "../data/Roles"
  import Select from 'react-select'
  import moment from 'moment'
  import DatePicker, {registerLocale} from "react-datepicker"
  import setHours from "date-fns/setHours"
  import setMinutes from "date-fns/setMinutes"
  import "react-datepicker/dist/react-datepicker.css"
  import es from 'date-fns/locale/es'
  
  registerLocale('es', es)
  
  
  export default class FormTreatment extends Component {
      constructor(props) {
          super(props)
  
          this.state = {
              specialties: Roles.roles_init,
              doctors: Roles.roles_init,
              patients: Roles.roles_init,
              selectedOption: {
                  label: '',
                  value: ''
              },
              selectedDoctor: {
                  label: '',
                  value: ''
              },
              selectedSpecialty: {
                  label: '',
                  value: ''
              },
              selectedProcedure: {
                  label: '',
                  value: ''
              },
              form: {
                  id: 0,
                  id_patient: '',
                  id_doctor: '',
                  id_specialty: '',
                  reason: '',
                  description: '',
                  total_price: 0,
                  detail: []
              },
              table: {
                  procedure_id: 0,
                  description: '',
                  quantity: 1,
                  price: 0,
                  price_unit: 0
              },
              detail: [],
  
              medicalprocedures: []
  
          }
          this.searchDoctor = this.searchDoctor.bind(this)
          this.handleChange = this.handleChange.bind(this)
          this.handleChangeTable = this.handleChangeTable.bind(this)
          this.handleChangeSpecialty = this.handleChangeSpecialty.bind(this)
          this.handleChangePatients = this.handleChangePatients.bind(this)
          this.handleChangeProcedures = this.handleChangeProcedures.bind(this)
          this.handleChangeDoctors = this.handleChangeDoctors.bind(this)
          this.addItem = this.addItem.bind(this)
          this.handleSubmit = this.handleSubmit.bind(this)
          this.deleteItem = this.deleteItem.bind(this)
          this.clearForm = this.clearForm.bind(this)
  
      }
  
  
      async componentDidMount() {
          try {
             this.getTreatment(this.state.form.id)
  
          } catch (e) {
  
          }
      }
  
     
  
      async componentDidUpdate(prevProps, prevState) {
          if (prevProps.id_treatment !== this.props.id_treatment) {
              this.setState({
                  form:{
                      ...this.state.form,
                      id:this.props.id_treatment
                  }
              }, () => {
                 
                    this.getTreatment(this.state.form.id)
                 /*
                  if (this.props.message_form == "success" || this.props.message_form == "cancel") {
                      this.setState({
                          selectedOption: {
                              label: '',
                              value: ''
                          },
                          selectedDoctor: {
                              label: '',
                              value: ''
                          },
                          selectedSpecialty: {
                              label: '',
                              value: ''
                          },
  
                      })
                  }
                  */
              })
          }
  
      }
  
      getTreatment(id){
          const api_url = `${url}/api/api-create-treatement/${id}`
          Axios.get(api_url)
              .then((res) => {
                  if(res.data.treatment===null){
                      this.setState({
                          specialties: res.data.specialties,
                          doctors: res.data.doctors,
                          patients: res.data.patients,
                           selectedOption: {
                              label: '',
                              value: ''
                          },
                          selectedDoctor: {
                              label: '',
                              value: ''
                          },
                          selectedSpecialty: {
                              label: '',
                              value: ''
                          },
                         
                          
                      }, () => {
                          this.clearForm()
                          const url_medicalprocedures = `${url}/api/api-get-select-procedures`
                          Axios.get(url_medicalprocedures).then((res) => {
                              this.setState({
                                  medicalprocedures: res.data.medicalprocedures
                              })
                          })
                      })
                  }else{
                      let reason = res.data.treatment.reason
                      let description = res.data.treatment.description
                      if(reason===null){
                          reason = ''
                      }
                      if(description===null){
                          description = ''
                      }
                      this.setState({
                          specialties: res.data.specialties,
                          doctors: res.data.doctors,
                          patients: res.data.patients,
                          form: {
                              ...this.state.form,
                              id_patient: res.data.treatment.patient_id,
                              id_doctor: res.data.treatment.doctor_id,
                              id_specialty: res.data.treatment.specailty_id,
                              reason: reason,
                              description: description,
                              total_price: res.data.treatment.price_total,
                              detail: res.data.detail
                          },
                          detail: res.data.detail,
                          selectedOption: {
                              label: res.data.treatment.name_p+' '+res.data.treatment.last_name_p,
                              value:  res.data.treatment.patient_id
                          },
                          selectedDoctor: {
                              label: res.data.treatment.name_d+' '+res.data.treatment.last_name_d,
                              value: res.data.treatment.doctor_id
                          },
                          selectedSpecialty: {
                              label: res.data.treatment.name_s,
                              value:  res.data.treatment.specailty_id
                          },
                      }, () => {
                          const url_medicalprocedures = `${url}/api/api-get-select-procedures`
                          Axios.get(url_medicalprocedures).then((res) => {
                              this.setState({
                                  medicalprocedures: res.data.medicalprocedures
                              })
                          })
                      })
  
                  }
                  
              })
      }
  
      clearForm() {
          this.setState({
              form: {
                  id: 0,
                  reason: '',
                  description: '',
                  total_price: 0,
                  detail: []
              },
              table: {
                  description: '',
                  quantity: 1,
                  price: 0,
                  price_unit: 0
              },
              detail: [],
          })
      }
  
      addItem(e) {
          e.preventDefault()
          if (this.state.table.procedure_id === 0) {
              Swal.fire({
                  icon: 'warning',
                  title: 'Selecciona un procedimiento',
                  text: 'Debes elejir un procedimiento y una cantidad para agregar'
              })
          } else {
              if (this.state.detail.length === 0) {
                  let total = parseFloat(this.state.table.price_unit) * parseInt(this.state.table.quantity)
                  this.setState({
                      table: {
                          ...this.state.table,
                          price: total,
                      }
                  }, () => {
                      let data = this.state.table
                      this.setState({
                          detail: this.state.detail.concat(data)
                      }, () => {
                          let total = 0
                          for (let i = 0; i < this.state.detail.length; i++) {
                              total = total + this.state.detail[i].price
                          }
                          this.setState({
                              form: {
                                  ...this.state.form,
                                  detail: this.state.detail,
                                  total_price: total
                              }
                          })
                      })
                  })
              } else {
                  let total = parseFloat(this.state.table.price_unit) * parseInt(this.state.table.quantity)
                  this.setState({
                      table: {
                          ...this.state.table,
                          price: total,
                      }
                  }, () => {
                      let details_cp = []
                      details_cp = this.state.detail
                      let data = this.state.table
                      for (let i = 0; i < details_cp.length; i++) {
                          if (data.description === details_cp[i].description) {
                              details_cp.splice(i, 1)
                          }
                      }
                      details_cp.push(data)
                      let total = 0
                      for (let i = 0; i < details_cp.length; i++) {
                          total = total + details_cp[i].price
                      }
                      this.setState({
                          detail: details_cp,
                          form: {
                              ...this.state.form,
                              detail: details_cp,
                              total_price: total
                          }
                      })
                  })
  
              }
  
          }
  
  
      }
  
      deleteItem(table) {
          let details = this.state.detail
          for (let i = 0; i < details.length; i++) {
              if (table.description === details[i].description) {
                  details.splice(i, 1)
              }
          }
          let total = 0
          for (let i = 0; i < details.length; i++) {
              total = total + details[i].price
          }
          this.setState({
              details: details,
              form: {
                  ...this.state.form,
                  details: details,
                  total_price: total
              }
          })
      }
  
      ///metodo para el submit
      async handleSubmit(e) {
          //evento para que no recargue la pagina
          e.preventDefault()
          try {
              if (this.state.form.detail.length === 0) {
                  Swal.fire({
                      icon: 'warning',
                      title: 'Advertencia',
                      text: 'El tratamiento debe contener uno o mas procedimientos!'
                  })
              } else {
                  if(this.state.form.id==0){
  
                      let config = {
                          method: 'POST',
                          headers: {
                              'Accept': 'application/json',
                              'Content-Type': 'application/json'
                          },
                          body: JSON.stringify(this.state.form)
                      }
                      let res = await fetch(`${url}/api/api-store-treatement`, config)
                      let data = await res.json()
                      if (res.status == 200 && res.ok == true) {
                          Swal.fire(
                              'Creado!',
                              'El tratamientos ha sido creado con éxito.',
                              'success'
                          )
                          
                          this.clearForm()
                           this.props.refresh(data.treatment.updated_at)
                          console.log(data.treatment.updated_at)
                      } else {
                          //this.changeErrors(data)
                          Swal.fire({
                              icon: 'error',
                              title: 'Error...',
                              text: 'Algo ha salido mal, revise los datos!'
                          })
                      }
                  }else{
                      let config = {
                          method: 'PUT',
                          headers: {
                              'Accept': 'application/json',
                              'Content-Type': 'application/json'
                          },
                          body: JSON.stringify(this.state.form)
                      }
                      let res = await fetch(`${url}/api/api-update-treatement`, config)
                      let data = await res.json()
                      if (res.status == 200 && res.ok == true) {
                          Swal.fire(
                              'Actualizado!',
                              'El tratamientos ha sido actualizado con éxito.',
                              'success'
                          )
                          
                          this.clearForm()
                           this.props.refresh(data.treatment.updated_at)
                          console.log(data.treatment.updated_at)
                      } else {
                          //this.changeErrors(data)
                          Swal.fire({
                              icon: 'error',
                              title: 'Error...',
                              text: 'Algo ha salido mal, revise los datos!'
                          })
                      }
  
                  }
  
                  
  
              }
  
  
          } catch (e) {
              Swal.fire({
                  icon: 'error',
                  title: 'Error...',
                  text: 'Algo ha salido mal!'
              })
          }
  
      }
  
      searchDoctor(id) {
          try {
              const api_url = `${url}/api-filter-doctors-specailty/${id}`
              Axios.get(api_url)
                  .then((res) => {
                      this.setState({
                          doctors: res.data.doctors
                      })
                      console.log(res.data.doctors)
                  })
          } catch (e) {
          }
      }
  
      ///METODO PARA ESCUCHAR LOS CAMBIOS EN EL SELECTED SPECIALTY
      handleChangeSpecialty(id) {
  
          let color_select = '#ffffff'
          this.state.specialties.forEach(specialty => {
              if (specialty.id == id) {
                  color_select = specialty.color
              }
  
          });
  
          this.setState({
              form: {
                  ...this.state.form,
                  color: color_select,
  
              }
          })
  
      }
  
      //METODO PARA ESCUCHAR LOS CAMBIOS DEL SELECT PROCEDIMIENTOS
      handleChangeProcedures(selectedProcedure) {
  
          let item = [];
          let id_p = selectedProcedure.value
  
          this.state.medicalprocedures.map((procedure) => {
              if (id_p === procedure.id) {
                  item = procedure;
              }
          })
  
          this.setState({selectedProcedure}, () => {
              this.setState({
                  table: {
                      ...this.state.table,
                      procedure_id: item.id,
                      description: item.name,
                      price_unit: item.price
  
                  }
              })
  
          });
  
  
      }
  
      renderListProdecuders() {
          return (this.state.medicalprocedures.map(data => ({label: data.name, value: data.id})))
      }
  
      //METODO PARA ESCUCHAR LOS CAMBIOS DEL SELECT PACIENTES
      handleChangePatients(selectedOption) {
          this.setState({selectedOption}, () => {
              this.setState({
                  form: {
                      ...this.state.form,
                      id_patient: selectedOption.value
                  }
              })
  
          });
      }
  
      renderList() {
          return (this.state.patients.map(data => ({label: data.name + ' ' + data.last_name, value: data.id})))
      }
  
      //METODO PARA ESCUCHAR LOS CAMBIOS DEL SELECT DOCTORES
      handleChangeDoctors(selectedDoctor) {
          this.setState({selectedDoctor}, () => {
              this.setState({
                  form: {
                      ...this.state.form,
                      id_doctor: selectedDoctor.value
                  }
              })
  
          });
      }
  
      renderListDoctor() {
  
          return (this.state.doctors.map(data => ({label: data.name + ' ' + data.last_name, value: data.id})))
      }
  
      //METODO PARA ESCUCHAR LOS CAMBIOS DEL SELECT especialidad
      handleChangeSpecialty(selectedSpecialty) {
          this.setState({selectedSpecialty}, () => {
              let color_select = '#ffffff'
              this.state.specialties.forEach(specialty => {
                  if (specialty.id == selectedSpecialty.value) {
                      color_select = specialty.color
                  }
  
              });
              this.setState({
                  form: {
                      ...this.state.form,
                      id_specialty: selectedSpecialty.value,
                      color: color_select
                  },
  
              })
  
          });
      }
  
      renderListSpecialty() {
  
          return (this.state.specialties.map(data => ({label: data.name, value: data.id})))
      }
  
  
      ///METODO PARA ESCUCHAR LOS CAMBIOS EN EL FORMULARIO
      handleChange(e) {
          //actualiza el estado del form
          this.setState({
              form: {
                  ...this.state.form,
                  [e.target.name]: e.target.value
              }
          })
  
      }
  
      ///METODO PARA ESCUCHAR LOS CAMBIOS EN EL FORMULARIO
      handleChangeTable(e) {
          //actualiza el estado del form
          this.setState({
              table: {
                  ...this.state.table,
                  [e.target.name]: e.target.value
              }
          })
  
      }
  
      showForm() {
          return (
              <React.Fragment>
                  <form onSubmit={(e) => this.handleSubmit(e)}>
                      <div className="row p-3">
                          <div className="col-sm-6">
                              <div className="form-group">
                                  <small className="text-primary" htmlFor="Name">Especialidad</small>
                                  <Select
                                      value={this.state.selectedSpecialty}
                                      onChange={this.handleChangeSpecialty}
                                      options={this.renderListSpecialty()}
                                      name="id_specialty"
                                  />
                                  <div
                                      hidden={this.props.errors.id_specialty === '' || this.props.errors.id_specialty === undefined ? true : false}
                                      className="alert alert-danger" rol="alert">
                                      <small>{this.props.errors.id_specialty}</small>
                                  </div>
                              </div>
                          </div>
  
  
                          <div className="col-sm-6">
                              <div className="form-group">
                                  <small className="text-primary" htmlFor="Name">Doctor</small>
                                  <Select
                                      value={this.state.selectedDoctor}
                                      onChange={this.handleChangeDoctors}
                                      options={this.renderListDoctor()}
                                      name="id_doctor"
                                  />
                                  <div
                                      hidden={this.props.errors.id_doctor === '' || this.props.errors.id_doctor === undefined ? true : false}
                                      className="alert alert-danger" rol="alert">
                                      <small> {this.props.errors.id_doctor}</small>
                                  </div>
                              </div>
                          </div>
  
                          <div className="col-sm-6">
                              <div className="form-group">
                                  <small className="text-primary" htmlFor="Name">Pacientes</small>
                                  <Select
                                      value={this.state.selectedOption}
                                      onChange={this.handleChangePatients}
                                      options={this.renderList()}
                                      name="id_patient"
                                  />
                                  <div
                                      hidden={this.props.errors.id_patient === '' || this.props.errors.id_patient === undefined ? true : false}
                                      className="alert alert-danger" rol="alert">
                                      <small>{this.props.errors.id_patient}</small>
                                  </div>
                              </div>
                          </div>
                          <div className="col-sm-6">
                              <div className="form-group">
                                  <small className="pull-left text-primary">Motivo del tratamiento</small>
                                  <input id="reason" name="reason" value={this.state.form.reason}
                                         onChange={this.handleChange}
                                         className="form-control" type="text"/>
                                  <div
                                      hidden={this.props.errors.reason === '' || this.props.errors.reason === undefined ? true : false}
                                      className="alert alert-danger" rol="alert">
                                      <small>{this.props.errors.reason}</small>
                                  </div>
                              </div>
                          </div>
                          <div className="col-sm-12 border border-secundary ">
                              <p className="text-primary" htmlFor="Name">Agrege un procedimiento</p>
  
                              <div className="row">
                                  <div className="col-sm-8">
                                      <div className="form-group">
                                          <small className="text-primary" htmlFor="Name">Procedimientos</small>
                                          <Select
                                              value={this.state.selectedProcedure}
                                              onChange={this.handleChangeProcedures}
                                              options={this.renderListProdecuders()}
                                              name="procedure_id"
                                          />
                                          <div
                                              hidden={this.props.errors.procedure_id === '' || this.props.errors.procedure_id === undefined ? true : false}
                                              className="alert alert-danger" rol="alert">
                                              <small>{this.props.errors.procedure_id}</small>
                                          </div>
                                      </div>
                                  </div>
                                  <div className="col-sm-4">
                                      <div className="form-group">
                                          <small className="pull-left text-primary">Cantidad</small>
                                          <input min={1} id="quantity" name="quantity" value={this.state.table.quantity}
                                                 onChange={this.handleChangeTable}
                                                 className="form-control" type="number"/>
  
                                      </div>
                                  </div>
                                  <div className="col-sm-12">
  
                                      <button onClick={this.addItem} type="button"
                                              className="btn btn-primary mb-3">Agregar
                                      </button>
  
  
                                  </div>
                              </div>
  
                          </div>
                          <div className="col-sm-12 border border-secundary mt-3">
                              <p className="text-primary" htmlFor="Name">Detalle</p>
                              <div className="row">
                                  <div className="col-sm-12">
                                      <div className="table-responsive">
                                          {this.showProcedures()}
                                      </div>
                                  </div>
                                  <div className="col-sm-12">
                                      <h4 hidden={this.state.form.total_price > 0 ? false : true}
                                          className="float-right mt-3"> Total $ {this.state.form.total_price}</h4>
                                  </div>
                              </div>
  
                          </div>
  
  
                          <div className="col-sm-12">
                              <div className="form-group">
                                  <small className="pull-left text-primary">Indicaciones</small>
                                  <textarea id="description" name="description" value={this.state.form.description}
                                            onChange={this.handleChange}
                                            className="form-control" type="text"/>
                                  <div
                                      hidden={this.props.errors.description === '' || this.props.errors.description === undefined ? true : false}
                                      className="alert alert-danger" rol="alert">
                                      <small>{this.props.errors.description}</small>
                                  </div>
                              </div>
                          </div>
                          <div className="col-sm-12">
  
                              <button type="button" data-dismiss="modal" onClick={this.clearForm} className="btn btn-danger">Cancelar
                              </button>
                              <button type="submit" className="btn btn-primary">Guardar</button>
                          </div>
                      </div>
                  </form>
              </React.Fragment>
          )
      }
  
      showProcedures() {
          const detail_treatment = this.state.detail;
          if (detail_treatment.length === 0) {
              return (
                  <React.Fragment>
                      <div className="text-center col-lg-12">
                          <img width={320} height={250} src="img/doctorweb.png"/>
                          <h5>No se enontrarón resultados</h5>
                      </div>
                  </React.Fragment>
              )
          }
          return (
              <React.Fragment>
                  <table className="table  nowrap mb-2 dataTable">
                      <thead>
                      <tr>
                          <th>Procedimiento</th>
                          <th>Valor</th>
                          <th>cantidad</th>
                          <th>total</th>
                          <th>Acción</th>
                      </tr>
                      </thead>
                      <tbody>
  
                      {detail_treatment.map((detail) => (
                          <tr key={detail.procedure_id}>
                              <td>{detail.description}</td>
                              <td>$ {detail.price_unit}</td>
                              <td> {detail.quantity}</td>
                              <td>$ {detail.price}</td>
                              <td>
                                  <button onClick={(e) => this.deleteItem(detail)} type="button"
                                          className="btn btn-danger btn-sm">Quitar
                                  </button>
                              </td>
                          </tr>
                      ))}
  
                      </tbody>
  
                  </table>
  
  
              </React.Fragment>
          )
  
      }
  
      render() {
          return (
              <React.Fragment>
                  {this.showForm()}
  
              </React.Fragment>
          )
      }
  }
  if (document.getElementById('formtreatment')) {
      ReactDOM.render(<FormTreatment/>, document.getElementById('formtreatment'));
  
  }
  