<template>
  <div id="app">
    <v-app id="inspire">
      <v-container class="pa-2" grid-list-md fluid>
        <v-layout row wrap>
          <!--parameter-->

          <v-dialog v-model="dialogchooseprint" persistent max-width="50%">
            <v-card>
              <v-card-title class="headline white--text  pt-2 pb-2" :class="reportColor" primary-title style="color:white">
                <h4>{{reportTitle}}</h4>
              </v-card-title>
              <v-container>
                <v-layout row>
                  <v-flex xs12 pr-3>
                    <v-flex v-for="(detail, idx) in details" :key="idx">
                      <v-flex xs12 v-if="detail.R_InputTypeName=='date'" pa-2>
                        <v-menu v-model="detail.tmp_date" 
                           :close-on-content-click="false" :nudge-right="40" lazy transition="scale-transition" offset-y
                          full-width max-width="290px" min-width="290px">
                          <template v-slot:activator="{ on }">
                            <v-text-field class="mr-2" 
                            prepend-icon="event" v-model="detail.fmt_date" :label="detail.R_ReportDetailLabel" hide-details readonly
                              v-on="on"></v-text-field>
                          </template>
                          <v-date-picker v-model="detail.model" no-title @input="detail.tmp_date = false" @change="formatDate(idx,detail.model)"></v-date-picker>
                        </v-menu>
                      </v-flex>

                      <v-flex xs12 v-if="detail.R_InputTypeName=='text'" pa-2>
                        <v-text-field class="mr-2" v-model="detail.model"
                           @change="changeDetail(idx,detail.R_InputTypeName)" :label="detail.R_ReportDetailLabel"
                          hide-details></v-text-field>
                      </v-flex>

                      <v-flex xs12 v-if="detail.R_InputTypeName=='dropdown'" pa-2>
                        <v-select v-model="detail.model" return-object
                           item-text="name" :items="detail.items" :label="detail.R_ReportDetailLabel"
                          @change="changeDetail(idx,detail.R_InputTypeName)"></v-select>
                      </v-flex>

                      <v-flex xs12 v-if="detail.R_InputTypeName=='autocompletion'" pa-2>
                        <v-autocomplete :label="detail.R_ReportDetailLabel"
                           v-model="detail.model" @change="changeDetail(idx,detail.R_InputTypeName)"
                          :items="detail.items"  auto-select-first no-filter
                          :search-input.sync="search_autocomplete[idx]"
                          item-text="name" return-object no-data-text="Cari....." small>
                          <template slot="item" slot-scope="{ item }">
                            <v-list-tile-content>
                              <v-list-tile-title v-text="item.name"></v-list-tile-title>
                            </v-list-tile-content>
                          </template>
                        </v-autocomplete>
                      </v-flex>

                    </v-flex>
                    <v-flex md3>
                     <v-radio-group v-model="formatreport" row>
                        <v-radio color="grey" label="PDF" value="pdf"></v-radio>
                        <v-radio v-if="withoutxls === 'N'" color="grey" label="EXCEL" value="xlsx"></v-radio>
                     </v-radio-group>
                      </v-flex>
                  </v-flex>
                </v-layout>
              </v-container>
              <v-alert :value="alertMessage!=''" type="warning">
              {{alertMessage}}
              </v-alert>
              <v-divider></v-divider>
              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="black" flat @click="closeForm()"> Tutup </v-btn>
                <v-btn color="grey" flat @click="doPrint()"> Cetak </v-btn>
              </v-card-actions>
            </v-card>
          </v-dialog>

          <!--endparameter-->
          <v-toolbar class="pa-1 mb-2" color="blue lighten-3" dark height="60px">
            <v-toolbar-title>DAFTAR LAPORAN</v-toolbar-title>
            <v-spacer></v-spacer>
            <v-flex xs3>
            <v-text-field @keydown.enter="search_report" v-model="search" label="Filter Report "></v-text-field>
            </v-flex>
          </v-toolbar>


          <v-flex xs4 v-for="(group, idx) in reports" :key="idx">
            <v-card class="ml-3 pa-2" outlined tile>
              <v-toolbar class="pa-1 mb-1" :color="group.color" dark height="30px">
                {{group.name}}
              </v-toolbar>
              <v-card-actions v-for="(report, idy) in group.reports" :key="report.R_ReportID">
                <v-btn @click="do_report(report)" style="width:100%;" class="rpt">
                  <span style="color:brown">{{report.R_ReportCode}} </span> &nbsp; |&nbsp; {{report.R_ReportName}}
                </v-btn>
              </v-card-actions>


            </v-card>
         </v-flex>

          <one-dialog-print :title="printtitle"
            :width="printwidth" :height="500" :status="openprint"
            :urlprint="urlprint"
            @close-dialog-print="closePrint">
         </one-dialog-print>

        </v-layout>
      </v-container>
    </v-app>
  </div>

</template>

<style scoped>
  .rpt .v-btn__content {
    justify-content: left;
  }

  .searchbox .v-input.v-text-field .v-input__slot {
    min-height: 60px;
  }

  .searchbox .v-btn {
    min-height: 60px;
  }

  table.v-table tbody td,
  table.v-table tbody th {
    height: 40px;
  }

  table.v-table thead tr {
    height: 40px;
  }

  .textinput {
    -webkit-transition: width 0.4s ease-in-out;
    transition: width 0.4s ease-in-out;
    background-color: white;
    background-position: 10px 10px;
    background-repeat: no-repeat;
    padding-left: 40px;
    width: 100%;
    padding: 8px 10px;
    margin-bottom: 5px;
    box-sizing: border-box;
    border: 1px solid #607d8b;

  }

  .textinput:focus {
    width: 100%;
  }

  .textinput:focus::-webkit-input-placeholder {
    color: transparent;
  }

  .textinput:focus::-moz-placeholder {
    color: transparent;
  }

  .textinput:-moz-placeholder {
    color: transparent;
  }

  .boxoutline {
    color: red;
    border: 1px solid red;
    justify-content: center;
    height: 45px;
    line-height: 45px;
    padding-left: 10px;
    background: #ffffff;
    font-size: 14px;
    font-weight: 500;
    border-radius: 1px
  }

  .boxoutline:hover {
    background: rgba(0, 0, 0, 0.07) !important;
    font-size: 15px;
    font-weight: 700;
  }

  .boxsolid {
    color: #ffffff;
    border: 1px solid #ffffff;
    justify-content: center;
    height: 45px;
    line-height: 45px;
    padding-left: 10px;
    background: #f44336;
    font-size: 14px;
    font-weight: 500;
    border-radius: 1px
  }

  .boxsolid:hover {
    background: #f44336de;
    font-size: 15px;
    font-weight: 700;
  }

  .scroll-container {
    scroll-padding: 50px 0 0 50px;
  }

  ::-webkit-scrollbar {
    width: 7px;
  }

  /* this targets the default scrollbar (compulsory) */

  ::-webkit-scrollbar-track {
    background-color: #73baf3;
  }

  /* the new scrollbar will have a flat appearance with the set background color */

  ::-webkit-scrollbar-thumb {
    background-color: #2196f3;
  }

  /* this will style the thumb, ignoring the track */

  ::-webkit-scrollbar-button {
    background-color: #0079da;
  }

  /* optionally, you can style the top and the bottom buttons (left and right for horizontal bars) */

  ::-webkit-scrollbar-corner {
    background-color: black;
  }

  /* if both the vertical and the horizontal bars appear, then perhaps the right bottom corner also needs to be styled */
</style>

<script>
  module.exports = {
    data() {
      return {
        search: '',
        search_autocomplete: [],
        prev_search:[],
        dialogchooseprint: false,
        init_date: moment().format("Y-M-D"),
        openprint: false,
        sp_rpt: '',
        urlprint: '',
        printtitle: '',
        printwidth: 600,
        formatreport: 'pdf',
        xsearch: '',
        alertMessage:'',
        withoutxls: 'N',
        headers: [{
            text: "",
            align: "left",
            sortable: false,
            value: "mr",
            width: "20%"
          },
          {
            text: "",
            align: "left",
            sortable: false,
            value: "mr",
            width: "20%"
          },
          {
            text: "",
            align: "left",
            sortable: false,
            value: "mr",
            width: "10%"
          }
        ],
        pagination: {
          descending: true,
          page: 1,
          rowsPerPage: 100,
          sortBy: 'id DESC',
          totalItems: this.$store.state.report.total_filter_params
        }
      }
    },
    components: {
      'one-date-picker': httpVueLoader('./oneDatePicker2.vue'),
      'one-dialog-print': httpVueLoader('../../common/oneDialogPrintX.vue')
    },
    mounted() {
      this.$store.dispatch("report/list","")
    },
    methods: {
      search_report() {
         this.$store.dispatch("report/list",this.search)
      },
      async do_report(r) {
        await this.$store.commit("report/update_report", r)
        this.search_autocomplete = []
        await this.$store.dispatch("report/detail", r.R_ReportID)
        let details = this.$store.state.report.details
        this.prev_search = []
        for(idx=0;idx < details.leth ; idx++) {
           this.search_autocomplete[idx] = ''
           this.prev_search.push('')
        }
        this.withoutxls = r.R_ReportWithoutXls
        this.formatreport = 'pdf'
        this.dialogchooseprint = true
      },
      closeForm() {
        this.dialogchooseprint = false
        this.$store.commit("report/update_details", [])
      },
      changeDetail(idx, tipe) {
        var arrOrders = this.$store.state.report.details
        arrOrders[idx].model = arrOrders[idx].model
        this.$store.commit("report/update_details", arrOrders)
      },
      formatDate(idx,date) {
       var arrOrders = this.$store.state.report.details
        if (!date) return null
        const [year, month, day] = date.split('-')
        var f_date = `${day}-${month}-${year}`
       arrOrders[idx].fmt_date = f_date
       arrOrders[idx].model = date
       this.$store.commit("report/update_details", arrOrders)

        
      },
      formatDatex(idx,date) {
        if (!date) return null

        const [year, month, day] = date.split('-')
        return `${day}-${month}-${year}`
      },
      deFormatedDate(date) {
        if (!date) return null

        const [day, month, year] = date.split('-')
        return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
      },
      doPrint() {
        this.printwidth = 1028
        this.printtitle = ""
        let user = one_user()
        var d = new Date();
        var n = d.getTime()
        var rptname = this.reportUrl
        var formatrpt = this.formatreport
        var arrOrders = this.$store.state.report.details
        let param = '';
        this.alertMessage = ''
        arrOrders.forEach((value, index) => {
           let modelx = '';

           switch(value.R_InputTypeName) {
              case 'date' :
                  if (value.model == '') this.alertMessage += value.R_ReportDetailLabel + ' invalid, '
                  modelx = value.model;
                 break;
              case 'dropdown':
              case 'autocompletion':
                  modelx = value.model.id;
                  if (! (parseInt(value.model.id) >= 0) ) this.alertMessage += value.R_ReportDetailLabel + ' invalid, '
                 break;
              default : //
                 modelx = value.model ;
                  if (value.model == '') this.alertMessage += value.R_ReportDetailLabel + ' invalid, '
                 break;
          }
          param += "&" + value.R_ReportDetailParam.trim() + "=" + modelx.replace(' ', '+')
        });
        if ( this.alertMessage != '' ) return
        this.dialogchooseprint = false
        var param_all = param
        this.urlprint = rptname + "&__format=" +
          formatrpt + param_all + "&username=" + user.M_UserUsername.trim().replace(' ','+') + "&tm=" + n

        console.log(this.urlprint)

        this.openprint = true
      },
      closePrint() {
        this.openprint = false
      }
    },
    computed: {
      reportTitle() {
        return this.$store.state.report.report.R_ReportCode + ' | ' + this.$store.state.report.report.R_ReportName
      },
      reportUrl() {
        return this.$store.state.report.report.R_ReportUrl
      },
      reportColor() {
        return this.$store.state.report.report.R_ReportGroupColor
      },
      reports() {
        return this.$store.state.report.reports
      },
      details() {
        return this.$store.state.report.details
      },
      vparams() {
        return this.$store.state.report.params
      },
      isLoading() {
        return this.$store.state.report.search_status == 1
      },
    },
    watch: {
       search_autocomplete : {
          deep: true,
          handler: function (new_val, old) {
           let details = this.$store.state.report.details
           if (new_val == null ) return
           for(let idx=0; idx < new_val.length; idx++) {
              if (! new_val[idx] ) continue
              if ( new_val[idx] != '' ) {
                 if (new_val[idx] == this.prev_search[idx] ) continue
                 this.prev_search[idx] = new_val[idx]
                 let sp = details[idx].R_ReportDetailSourceSp
                 let dep = details[idx].R_ReportDetailDepParam
                 let value = ''
                 if (dep && dep != '') {
                    for(let idx_dep =0; idx_dep < details.length ; idx_dep++ ) {
                       if (dep == details[idx_dep].R_ReportDetailParam ) {
                           value = details[idx_dep].model.id
                       } 
                    }
                 }
                 this.$store.dispatch("report/listautocomplete", {
                   search: new_val[idx],
                   sp: sp,
                   index: idx,
                   dep: dep,
                   value
                 })
              }
           }
         }
       }
    }
  }
</script>
