<template>
  <v-layout column>
    <v-dialog v-model="dialog" width="500">
      <v-card>
        <v-card-title class="headline grey lighten-2 pt-2 pb-2" primary-title>
          Ticket Berhasil Dibuat
        </v-card-title>
        <v-card-text class="pt-2 pb-2">
          <h6 class="display-1 text-center">
            Number <span class="blue--text">{{ text_ticket_no }}</span>
          </h6>
        </v-card-text>
        <v-divider></v-divider>

        <v-card-actions>
          <v-btn color="primary" flat @click="finish"> Tutup </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Alert dialog -->
    <v-dialog v-model="dialogalert" max-width="30%">
      <v-card>
        <v-card-title class="headline grey lighten-2 pt-2 pb-2" primary-title>
          Peringatan !
        </v-card-title>
        <v-card-text class="pt-2 pb-2">
          <v-layout row>
            <v-flex xs12 d-flex>
              <v-layout row>
                <v-flex pb-1 xs12>
                  <v-layout row>
                    <v-flex pt-2 pr-2 xs12>
                      {{ msgalert }}
                    </v-flex>
                  </v-layout>
                </v-flex>
              </v-layout>
            </v-flex>
          </v-layout>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" flat @click="dialogalert = false">
            Tutup
          </v-btn>
          <v-btn color="primary" flat @click="saveForm()"> Yakin lah </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <!-- End alert dialog -->
    <!-- ERROR DIALOG -->
    <v-dialog v-model="dialog_error" max-width="500px">
      <v-card>
        <v-card-title>
          <span>ERROR !</span>
          <v-spacer></v-spacer>
        </v-card-title>
        <v-divider></v-divider>
        <div class="ma-3 red--text">{{ msgError }}</div>
        <v-divider></v-divider>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" flat @click="dialog_error = false"
            >Close</v-btn
          >
        </v-card-actions>
      </v-card>
    </v-dialog>
    <!-- END ERROR DIALOG -->
    <!-- Snackbar -->
    <v-snackbar
      v-model="snackbar"
      :timeout="5000"
      :multi-line="false"
      :vertical="false"
      :top="true"
      :color="clr"
      :value="snackbar"
    >
      {{ msgsnackbar }}
      <v-btn flat @click="snackbar = false"> Tutup </v-btn>
    </v-snackbar>
    <!-- End Snackbar -->

    <v-card>
      <v-flex xs12>
        <v-subheader red--text text--lighten-1> BUAT TIKET BARU </v-subheader>
        <v-divider></v-divider>
        <v-layout row wrap>
          <v-flex xs12 pa-2>
            <v-layout row>
              <v-flex xs12 pa-1>
                <v-autocomplete
                  auto-select-first
                  :items="xclients"
                  v-model="vclient"
                  :search-input.sync="search_clientx"
                  :loading="loading_client"
                  item-text="clientName"
                  item-value="clientId"
                  label="CLIENT*"
                  return-object
                  outline
                  clearable
                  no-data-text="Pilih Client"
                >
                  <template slot="item" slot-scope="{ item }">
                    <v-list-tile-content>
                      <v-list-tile-title
                        v-text="item.clientName"
                      ></v-list-tile-title>
                    </v-list-tile-content>
                  </template>
                </v-autocomplete>
                <p
                  v-if="checkError('requirevclient')"
                  class="error pl-2 pr-2"
                  style="color: #fff"
                >
                  Pilih client dulu
                </p>
              </v-flex>
            </v-layout>

            <v-layout row>
              <v-flex xs12 pa-1>
                <v-text-field label="TITLE*" outline v-model="xtitle">
                </v-text-field>
                <p
                  v-if="checkError('requirextitle')"
                  class="error pl-2 pr-2"
                  style="color: #fff"
                >
                  Title belum diisi
                </p>
              </v-flex>
            </v-layout>

            <v-layout row>
              <v-flex xs12 pa-1>
                <v-text-field label="SENDER*" outline v-model="xsender">
                </v-text-field>
                <p
                  v-if="checkError('requirexsender')"
                  class="error pl-2 pr-2"
                  style="color: #fff"
                >
                  Sender belum diisi
                </p>
              </v-flex>
            </v-layout>

            <v-layout row>
              <v-flex xs12 pa-1>
                <v-autocomplete
                  auto-select-first
                  :items="xbranchs"
                  v-model="vbranch"
                  :loading="loading_branch"
                  :search-input.sync="search_branchx"
                  item-text="M_BranchName"
                  item-value="M_BranchID"
                  label="BRANCH*"
                  return-object
                  outline
                  clearable
                  no-data-text="Pilih Branch"
                >
                  <template slot="item" slot-scope="{ item }">
                    <v-list-tile-content>
                      <v-list-tile-title
                        v-text="item.M_BranchName"
                      ></v-list-tile-title>
                    </v-list-tile-content>
                  </template>
                </v-autocomplete>
                <p
                  v-if="checkError('requirevbranch')"
                  class="error pl-2 pr-2"
                  style="color: #fff"
                >
                  Pilih branch dulu
                </p>
              </v-flex>
            </v-layout>

            <v-layout row>
              <v-flex xs12 pa-1>
                <v-checkbox
                  label="DIRECT MESSAGE"
                  v-model="xdirect"
                ></v-checkbox>
              </v-flex>
            </v-layout>

            <v-layout row>
              <v-flex xs12 pa-1>
                <v-textarea
                  filled
                  outline
                  label="DESCRIPTION*"
                  rows="3"
                  v-model="xdescription"
                ></v-textarea>
                <p
                  v-if="checkError('requirexdescription')"
                  class="error pl-2 pr-2"
                  style="color: #fff"
                >
                  Description belum diisi
                </p>
              </v-flex>
            </v-layout>

            <v-layout
              mr-2
              ml-2
              style="border: 1px solid black"
              align-center
              row
              pa-2
            >
              <v-flex xs12>
                <input
                  type="file"
                  id="files"
                  ref="files"
                  multiple
                  v-on:change="handleFileUploads()"
                />
              </v-flex>
              <!-- <v-flex xs3 class="text-xs-right">
                                    <v-btn :disabled="show_progrees_upload" small dark color="blue lighten-1" @click="submitFiles()">Upload</v-btn>
                                </v-flex> -->
            </v-layout>
            <!-- <p v-if="error_image" class="mt-1 error pl-2 pr-2" style="color:#fff">Anda belum mengisi</p> -->
            <v-layout v-if="show_progrees_upload" row align-center mr-2 ml-2>
              <v-flex xs12>
                <v-progress-linear :indeterminate="true"></v-progress-linear>
              </v-flex>
            </v-layout>
            <v-layout
              v-if="urls.length > 0 && !show_progrees_upload"
              align-center
              row
            >
              <v-flex v-for="(url, index) in urls" :key="index" xs12 pa-2>
                <v-img :src="url">
                  <div class="fill-height bottom-gradient"></div>
                </v-img>
              </v-flex>
            </v-layout>
            <!-- <v-layout  v-if="images.length > 0 && !show_progrees_upload" align-center row mr-2 ml-2>
                            
                                <v-flex v-for="image in images" xs6 pa-2>
                                    <v-img :src="image.image_url">
                                    <div class="fill-height bottom-gradient"></div>
                                    </v-img>
                                </v-flex>
                            
                            </v-layout> -->

            <v-flex text-md-right class="mt-3">
              <v-btn color="info" small @click="openAddForm()"> SIMPAN </v-btn>
            </v-flex>
          </v-flex>
        </v-layout>
      </v-flex>
    </v-card>
  </v-layout>
</template>

<style scoped>
.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;
}
</style>

<script>
module.exports = {
  data() {
    return {
      search_branchx: "",
      search_clientx: "",
      xtitle: "",
      xsender: "",
      dialogalert: false,
      msgalert: "",
      clr: "success",
      xdescription: "",
      xdirect: false,
      // error_image:false,
      // url: null,
      urls: [],
      filesToUpload: [],
    };
  },
  mounted() {
    // this.$store.dispatch("ticket/search_client", {
    //   qry: this.search_clientx,
    // });
  },
  computed: {
    selected_client_id() {
      return this.$store.state.ticket.selected_clients.clientId;
    },
    xbranchs() {
      return this.$store.state.ticket.branchs;
    },
    xclients() {
      return this.$store.state.ticket.clients;
    },
    vbranch: {
      get() {
        return this.$store.state.ticket.selected_branch;
      },
      set(val) {
        this.$store.commit("ticket/update_selected_branch", val);
      },
    },
    vclient: {
      get() {
        return this.$store.state.ticket.selected_clients;
      },
      set(val) {
        this.$store.commit("ticket/update_selected_clients", val);
      },
    },
    loading_branch() {
      return this.$store.state.ticket.loading;
    },
    loading_client() {
      return this.$store.state.ticket.loading_client;
    },
    snackbar: {
      get() {
        return this.$store.state.ticket.alert_success;
      },
      set(val) {
        this.$store.commit("ticket/update_alert_success", val);
      },
    },
    msgsnackbar() {
      return this.$store.state.ticket.msg_success;
    },
    dialog_error: {
      get() {
        return this.$store.state.ticket.alert_error;
      },
      set(val) {
        this.$store.commit("ticket/update_alert_error", val);
      },
    },
    msgError() {
      return this.$store.state.ticket.error_message;
    },
    show_progrees_upload: {
      get() {
        return this.$store.state.ticket.show_progrees_upload;
      },
      set(val) {
        this.$store.commit("ticket/update_show_progrees_upload", val);
      },
    },
    images() {
      return this.$store.state.ticket.images;
    },
    lastInsertId: {
      get() {
        return this.$store.state.ticket.lastInsertId;
      },
      set(val) {
        this.$store.commit("ticket/update_lastInsertId", val);
      },
    },
    text_ticket_no() {
      return this.$store.state.ticket.ticket_number;
    },
    dialog: {
      get() {
        return this.$store.state.ticket.dialog_is_active;
      },
      set(val) {
        this.$store.commit("ticket/update_dialog_is_active", val);
      },
    },
  },
  methods: {
    finish: function () {
      this.dialog = false;
      //  location.reload()
    },
    handleFileUploads() {
      // this.files = this.$refs.files.files

      const files = this.$refs.files.files;
      this.urls = [];
      this.filesToUpload = [];
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const url = URL.createObjectURL(file);
        this.urls.push(url);
        this.filesToUpload.push(file);
      }
      // console.log('urls', this.urls)
      console.log("filesToUpload", this.filesToUpload);
    },
    submitFiles() {
      // this.error_image = false
      let formData = new FormData();

      for (var i = 0; i < this.filesToUpload.length; i++) {
        let file = this.filesToUpload[i];
        console.log(file);
        formData.append("files[" + i + "]", file);
      }
      if (this.filesToUpload.length > 0) {
        this.show_progrees_upload = true;
        let insertId = this.$store.state.ticket.lastInsertId;
        console.log("insertId submit", insertId);
        formData.append("ticketid", insertId);
        this.$store.dispatch("ticket/uploadimage", formData);
      }
    },
    thr_search_branch: _.debounce(function () {
      this.$store.dispatch("ticket/search_branch", {
        search: this.search_branchx,
      });
    }, 1000),
    thr_search_client: _.debounce(function () {
      this.$store.dispatch("ticket/search_client", {
        search: this.search_clientx,
      });
    }, 1000),
    checkError(value) {
      var errors = this.$store.state.ticket.errors;
      if (errors.includes(value)) {
        return true;
      } else {
        return false;
      }
    },
    resetAllInput() {
      this.xtitle = "";
      this.xsender = "";
      this.vbranch = "";
      this.vclient = "";
      this.xdirect = "";
      this.xdescription = "";
      this.urls = [];
      this.filesToUpload = [];
    },
    openAddForm() {
      this.$store.commit("ticket/update_errors", []);
      var errors = this.$store.state.ticket.errors;

      if (_.isEmpty(this.vclient)) {
        errors.push("requirevclient");
      }
      if (_.isEmpty(this.xtitle)) {
        errors.push("requirextitle");
      }
      if (_.isEmpty(this.xsender)) {
        errors.push("requirexsender");
      }
      if (_.isEmpty(this.vbranch)) {
        errors.push("requirevbranch");
      }
      if (_.isEmpty(this.xdescription)) {
        errors.push("requirexdescription");
      }

      if (errors.length === 0) {
        this.msgalert =
          "Yakin, Mau Buat Ticket Baru " + "(" + this.xtitle + ")" + " ?";
        this.dialogalert = true;
      } else {
        this.dialogalert = false;
      }
    },
    saveForm() {
      this.$store.commit("ticket/update_errors", []);
      var errors = this.$store.state.ticket.errors;

      if (_.isEmpty(this.vclient)) {
        errors.push("requirevclient");
      }
      if (_.isEmpty(this.xtitle)) {
        errors.push("requirextitle");
      }
      if (_.isEmpty(this.xsender)) {
        errors.push("requirexsender");
      }
      if (_.isEmpty(this.vbranch)) {
        errors.push("requirevbranch");
      }
      if (_.isEmpty(this.xdescription)) {
        errors.push("requirexdescription");
      }

      if (errors.length === 0) {
        var formData = new FormData();
        console.log(this.filesToUpload.length);
        for (var i = 0; i < this.filesToUpload.length; i++) {
          let file = this.filesToUpload[i];

          formData.append("files[" + i + "]", file);
          console.log(formData);
        }

        /*let prm = {}
                prm.title = this.xtitle
                prm.sender = this.xsender
                prm.branch_code = this.vbranch.M_BranchCode
                prm.description = this.xdescription
                prm.is_direct = this.xdirect ? 'Y' : 'N'
                prm.images = formData*/
        formData.append("client_id", this.vclient.clientId);
        formData.append("title", this.xtitle);
        formData.append("sender", this.xsender);
        formData.append("branch_code", this.vbranch.M_BranchCode);
        formData.append("branch_name", this.vbranch.M_BranchName);
        formData.append("description", this.xdescription);
        formData.append("is_direct", this.xdirect ? "Y" : "N");

        this.$store.dispatch("ticket/new_ticket", formData);
        //this.submitFiles();
        this.resetAllInput();
        this.dialogalert = false;
      }
    },
  },
  watch: {
    search_clientx(val, old) {
      if (val == old) return;
      if (!val) return;
      if (val.length > 0) {
        this.$store.dispatch("ticket/search_client", {
          search: this.search_clientx,
        });
        this.thr_search_client;
        // this.$store.dispatch("ticket/search_branch", {
        //   search: this.search_branchx,
        //   client_id: this.$store.state.ticket.selected_clients.clientId,
        // });
        // this.thr_search_branch;
      }
    },
    search_branchx(val, old) {
      if (val == old) return;
      if (!val) return;
      if (val.length > 0) {
        this.$store.dispatch("ticket/search_branch", {
          search: this.search_branchx,
          client_id: this.$store.state.ticket.selected_clients.clientId,
        });
        this.thr_search_branch;
      }
    },
    selected_client_id(val, old) {
      if (val == old) return;
      if (!val) return;
      if (val.length > 0) {
        this.$store.dispatch("ticket/search_branch", {
          search: this.search_branchx,
          client_id: val,
        });
        this.thr_search_branch;
      }
    },
  },
};
</script>
