<template>
  <v-layout class="fill-height" column>
    <v-dialog v-model="dialogsuccess" persistent max-width="290">
      <v-card>
        <v-card-title color="success" class="headline">Berhasil !</v-card-title>
        <v-card-text>
          {{ msgsuccess }}
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="green darken-1" flat @click="closeDialogSuccess"
            >OK</v-btn
          >
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-card color="orange accent-1" class="mb-2 pa-2 searchbox">
      <v-layout row>
        <v-flex xs12>
          <v-card>
            <v-layout pa-1 row>
              <v-flex class="text-xs-center pa-2" xs9>
                <v-text-field
                  color="orange"
                  label="KODE SETUP"
                  placeholder="Masukkan kode setup"
                  v-model="setupcode"
                  outline
                  hide-details
                ></v-text-field>
              </v-flex>
              <v-flex class="text-xs-left pa-2" xs3>
                <v-btn
                  @click="generateSetup()"
                  title="generate"
                  style="min-width: 30px; min-height: 25px;"
                  color="orange"
                  dark
                >
                  <v-icon>system_update_alt</v-icon>
                </v-btn>
              </v-flex>
            </v-layout>
            <v-divider></v-divider>
            <v-layout row>
              <v-flex xs12 pa-2>
                <v-card color="orange" dark>
                  <v-card-text>
                    <v-layout align-center row>
                      <v-flex pb-2 xs12>
                        SETUP : {{ xsetup.McuOfflinePrepareCode }}
                      </v-flex>
                    </v-layout>
                    <v-divider dark></v-divider>
                    <v-layout pt-2 align-center row>
                      <v-flex xs12>
                        {{ xsetup.M_CompanyName }}
                      </v-flex>
                    </v-layout>
                    <v-layout row>
                      <v-flex xs12>
                        <p class="mb-0 caption">
                          Periode : {{ xsetup.start_date }} -
                          {{ xsetup.end_date }}
                        </p>
                      </v-flex>
                    </v-layout>
                  </v-card-text>
                </v-card>
              </v-flex>
            </v-layout>
            <v-divider></v-divider>
            <v-layout row>
              <v-flex xs12 pa-2>
                <v-card>
                  <v-layout row>
                    <v-flex xs12>
                      <v-subheader
                        class="pl-3 white--text"
                        style="background: #ff9800;"
                        >AGREEMENT</v-subheader
                      >
                    </v-flex>
                  </v-layout>
                  <v-card-text>
                    <v-layout align-center wrap>
                      <v-flex pb-2 xs12>
                        <v-card
                          dark
                          class="mb-1"
                          v-if="xsetup && xsetup.agreements.length > 0"
                          v-for="agreement in xsetup.agreements"
                          color="orange"
                        >
                          <v-layout wrap>
                            <v-flex pa-2 xs12 text-xs-center
                              ><p style="font-size: 12px;" class="mb-0">
                                {{ agreement.name }}
                              </p></v-flex
                            >
                          </v-layout>
                        </v-card>
                      </v-flex>
                    </v-layout>
                  </v-card-text>
                </v-card>
              </v-flex>
            </v-layout>
            <v-divider></v-divider>
            <v-layout row>
              <v-flex xs12 pa-2>
                <v-card color="orange" dark>
                  <v-card-text>
                    <v-layout align-center row>
                      <v-flex xs5>
                        JANJI HASIL
                      </v-flex>
                      <v-flex text-xs-right xs7>
                        <p class="mb-0">
                          {{ xsetup.promise_date }} {{ xsetup.promise_time }}
                        </p>
                      </v-flex>
                    </v-layout>
                  </v-card-text>
                </v-card>
              </v-flex>
            </v-layout>
            <v-layout row>
              <v-flex pa-2 xs12>
                <v-btn block @click="downloadxapp()" class="" color="info"
                  >download</v-btn
                >
              </v-flex>
            </v-layout>
          </v-card>
        </v-flex>
      </v-layout>
    </v-card>
    <v-card color="orange accent-1" class="mb-2 pa-2 searchbox">
      <v-layout pa-1 row>
        <v-flex class="text-xs-center" xs12>
          <p class="mb-0 caption">
            silahkan download template di
            <span
              @click="downloadcsv()"
              style="cursor: pointer;"
              class="info--text lighten-3--text"
              >sini</span
            >
          </p>
        </v-flex>
      </v-layout>
      <v-divider></v-divider>
      <v-layout pt-2 pb-1 row>
        <v-flex class="text-xs-left" xs12>
          <input
            accept=".xlsx"
            type="file"
            id="csv_file"
            name="csv_file"
            class="form-control"
            @change="loadCSV($event)"
          />
        </v-flex>
      </v-layout>
    </v-card>

    <one-dialog-alert
      :status="openalertconfirmation"
      :msg="msgalertconfirmation"
      @forget-dialog-alert="forgetAlertConfirmation()"
      @close-dialog-alert="closeAlertConfirmation()"
    ></one-dialog-alert>
  </v-layout>
</template>

<style scoped>
  table.v-table tbody td,
  table.v-table tbody th {
    height: 35px;
  }

  table.v-table thead tr {
    height: 35px;
  }
</style>
<script>
  module.exports = {
    components: {
      "one-dialog-info": httpVueLoader("../../common/oneDialogInfo.vue"),
      "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue"),
    },
    mounted() {
      //this.setNewSetup()
    },
    methods: {
      downloadxapp() {
        var start = Date.now();
        location.replace("/install-mcu.zip?tm=" + start);
      },
      generateSetup() {
        this.$store.commit("patient/update_patients", []);
        this.$store.commit("patient/update_total_patients", 0);
        this.$store.dispatch("patient/generatesetup", {
          setupcode: this.setupcode,
        });
      },
      downloadcsv() {
        window.open("./csv-mcu.xlsx");
      },
      editRow(row) {
        console.log(row);
        this.$store.commit("patient/update_act", "edit");
        this.$store.commit("patient/update_xid", row.McuOfflinePrepareID);
        this.$store.commit("patient/update_companies", [
          { id: row.McuOfflinePrepareM_CompanyID, name: row.M_CompanyName },
        ]);
        this.$store.commit("patient/update_company", {
          id: row.McuOfflinePrepareM_CompanyID,
          name: row.M_CompanyName,
        });
        this.$store.commit("patient/update_mous", row.allmous);
        this.$store.commit("patient/update_mou", {});
        this.$store.commit("patient/update_selected_mous", row.mous);
        this.$store.commit("patient/update_selected_doctors", row.doctors);

        this.$store.commit(
          "patient/update_start_date",
          moment(row.McuOfflinePrepareStartDate).format("YYYY-MM-DD")
        );
        this.$store.commit(
          "patient/update_end_date",
          moment(row.McuOfflinePrepareEndDate).format("YYYY-MM-DD")
        );
      },
      isSelected(p) {
        return (
          p.M_PatientID ==
          this.$store.state.patient.selected_patient.M_PatientID
        );
      },
      searchPatient() {
        this.$store.dispatch("patient/search", {
          status: this.status,
          current_page: 1,
          lastid: -1,
        });
        this.$store.commit("patient/update_current_page", 1);
      },
      selectMe(pat) {
        if (this.$store.state.patient.no_save == 0) {
          this.$store.commit("patient/update_selected_patient", pat);
        } else {
          this.$store.commit("patient/update_open_alert_confirmation", true);
        }
      },
      closeAlertConfirmation() {
        this.$store.commit("patient/update_open_alert_confirmation", false);
      },
      forgetAlertConfirmation() {
        this.$store.commit("patient/update_no_save", 0);
        this.$store.commit("patient/update_open_alert_confirmation", false);
      },
      updateAlert_success(val) {
        this.$store.commit("patient/update_alert_success", val);
      },
      closeDialogSuccess() {
        let arrpatient = this.$store.state.patient.patients;
        var idx = _.findIndex(
          arrpatient,
          (item) => item.M_PatientID === this.$store.state.patient.last_id
        );
        console.log(idx);
        this.$store.dispatch("patient/search", {
          status: this.status,
          current_page: this.curr_page,
          lastid: idx,
        });
        this.$store.commit("patient/update_dialog_success", false);
      },
      setNewSetup() {
        this.$store.commit("patient/update_act", "new");
        this.$store.commit("patient/update_xid", -1);
        this.$store.commit("patient/update_company", {});
        this.$store.commit("patient/update_mous", []);
        this.$store.commit("patient/update_mou", {});
        this.$store.commit("patient/update_default_mou", {});
        this.$store.commit("patient/update_default_doctor", {});
        this.$store.commit("patient/update_selected_mous", []);
        this.$store.commit("patient/update_selected_doctors", []);
        this.$store.commit(
          "patient/update_start_date",
          moment(new Date()).format("YYYY-MM-DD")
        );
        this.$store.commit(
          "patient/update_end_date",
          moment(new Date()).format("YYYY-MM-DD")
        );
      },
      deleteData(row) {
        this.$store.commit("patient/update_selected_patient", row);
        console.log(this.$store.state.patient.selected_patient);
        let msg =
          "Yakin, akan menghapus data setup " +
          this.$store.state.patient.selected_patient.McuOfflinePrepareCode +
          " ?";
        this.$store.commit("patient/update_msg_confirmation_delete", msg);
        this.$store.commit("patient/update_dialog_confirmation_delete", true);
      },
      doDeleteData() {
        var prm = {};
        prm.id = this.$store.state.patient.selected_patient.McuOfflinePrepareID;
        prm.code = this.$store.state.patient.selected_patient.McuOfflinePrepareCode;
        console.log(prm);
        this.$store.dispatch("patient/delete", prm);
      },
      csvJSON(csv) {
        var vm = this;
        var lines = csv.split("\n");
        var result = [];
        var headers = lines[0].split(",");
        vm.parse_header = lines[0].split(",");
        lines[0].split(",").forEach(function (key) {
          vm.sortOrders[key] = 1;
        });

        lines.map(function (line, indexLine) {
          if (indexLine < 1) return; // Jump header line

          var obj = {};
          var currentline = line.split(",");

          headers.map(function (header, indexHeader) {
            var header = header.trim();
            obj[header] = currentline[indexHeader];
          });

          result.push(obj);
        });

        result.pop(); // remove the last item because undefined values

        return result; // JavaScript object
      },
      loadCSV_old(e) {
        var vm = this;
        if (window.FileReader) {
          var reader = new FileReader();
          reader.readAsText(e.target.files[0]);
          // Handle errors load
          reader.onload = function (event) {
            var csv = event.target.result;
            vm.parse_csv = vm.csvJSON(csv);
            var prm = {
              xid: vm.$store.state.patient.data_setup.McuOfflinePrepareID,
              data: vm.parse_csv,
            };
            console.log(prm);
            vm.$store.dispatch("patient/savecsv", prm);
          };
          reader.onerror = function (evt) {
            if (evt.target.error.name == "NotReadableError") {
              alert("Canno't read file !");
            }
          };
        } else {
          alert("FileReader are not supported in this browser.");
        }
      },
      loadCSV(e) {
        var vm = this;
        var files = e.target.files,
          f = files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
          var data = new Uint8Array(e.target.result);
          var workbook = XLSX.read(data, {
            type: "array",
            cellText: true,
            cellDates: true,
          });
          let sheetName = workbook.SheetNames[0];
          /* DO SOMETHING WITH workbook HERE */
          console.log(workbook);
          let worksheet = workbook.Sheets[sheetName];
          // console.log(XLSX.utils.sheet_to_json(worksheet));
          //var xdata = XLSX.utils.sheet_to_json(worksheet,{ raw:false,  dateNF: 'FMT 22'})
          var data_json = [];
          // console.log(xdata)
          var date_data = XLSX.utils.sheet_to_json(worksheet, {
            raw: false,
            dateNF: "22",
          });
          var ktp_data = XLSX.utils.sheet_to_json(worksheet, {
            cellText: true,
          });
          //console.log(zdata)
          date_data.forEach(function (entry, iidx) {
            if (iidx > 0) {
              //entry.TANGGAL_LAHIR =  moment(entry.TANGGAL_LAHIR).format('DD-MM-YYYY')
              entry.KTP = ktp_data[iidx].KTP;
              data_json.push(entry);
            }
          });
          var prm = {
            xid: vm.$store.state.patient.data_setup.McuOfflinePrepareID,
            data: data_json,
          };
          console.log(data_json);
          //XLSX.utils.sheet_to_json(ws, {dateNF:"YYYY-MM-DD"})
          //   vm.$store.dispatch("patient/savecsv", prm);
        };
        reader.readAsArrayBuffer(f);
      },
    },
    computed: {
      setupcode: {
        get() {
          return this.$store.state.patient.setupcode;
        },
        set(val) {
          this.$store.commit("patient/update_setupcode", val);
        },
      },
      xsetup() {
        return this.$store.state.patient.data_setup;
      },
      dialogconfirmationdelete: {
        get() {
          return this.$store.state.patient.dialog_confirmation_delete;
        },
        set(val) {
          this.$store.commit("patient/update_dialog_confirmation_delete", val);
        },
      },
      msgconfirmationdelete() {
        return this.$store.state.patient.msg_confirmation_delete;
      },
      status: {
        get() {
          return this.$store.state.patient.status;
        },
        set(val) {
          this.$store.commit("patient/update_status", val);
          this.$store.dispatch("patient/search", {
            status: val,
            current_page: this.curr_page,
            lastid: -1,
          });
        },
      },
      dialogsuccess: {
        get() {
          return this.$store.state.patient.dialog_success;
        },
        set(val) {
          this.$store.commit("patient/update_dialog_success", val);
        },
      },
      msgsuccess() {
        return this.$store.state.patient.msg_success;
      },
      snackbar: {
        get() {
          return this.$store.state.patient.alert_success;
        },
        set(val) {
          this.$store.commit("patient/update_alert_success", val);
        },
      },
      isLoading() {
        return this.$store.state.patient.search_status == 1;
      },
      openalertconfirmation: {
        get() {
          return this.$store.state.patient.open_alert_confirmation;
        },
        set(val) {
          this.$store.commit("patient/update_open_alert_confirmation", val);
        },
      },
    },
    filters: {
      capitalize: function (str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
      },
    },
    data() {
      return {
        channel_name: "",
        channel_fields: [],
        channel_entries: [],
        parse_header: [],
        parse_csv: [],
        sortOrders: {},
        sortKey: "",
        statuses: [
          { id: "N", name: "Belum di download" },
          { id: "Y", name: "Sudah di download" },
        ],
        msgalertconfirmation:
          "Perubahan yang telah dilakukan belum disimpan dong !",
        items: [],
        name: "",
        snorm: "",
        page: 1,
        headers: [
          {
            text: "KODE",
            align: "left",
            sortable: false,
            value: "mr",
            width: "20%",
            class: "pa-2 deep-orange accent-1 white--text",
          },
          {
            text: "KEL. PELANGGAN",
            align: "left",
            sortable: false,
            value: "lab",
            width: "55%",
            class: "pa-2 deep-orange accent-1 white--text",
          },
          {
            text: "AKSI",
            align: "left",
            sortable: false,
            value: "lab",
            width: "15%",
            class: "pa-2 deep-orange accent-1 white--text",
          },
        ],
        pagination: {
          descending: false,
          page: 1,
          rowsPerPage: 5,
          sortBy: "M_PatientName",
          totalItems: this.$store.state.patient.total_patients,
        },
      };
    },
  };
</script>
