<template>
  <div>
    <h3 class="content-block main-title">Penyusunan DRP</h3>
    <p class="content-block">Penyusunan DRP</p>
    <div class="content-block">
      <div class="dx-card responsive-paddings">
        <div id="app-container">
          <Popup
            v-model:visible="popupVisible"
            :drag-enabled="false"
            :hide-on-outside-click="true"
            :show-close-button="false"
            :show-title="true"
            :width="914"
            :height="672"
            container=".dx-viewport"
            :title="popupTitle"
          >
            <DxPosition at="center" my="center" collision="fit" />
            <DxToolbarItem
              widget="dxButton"
              toolbar="top"
              locate-in-menu="always"
              :options="closeButtonOptions"
              :visible="!isShowButton"
            />
            <DxToolbarItem
              widget="dxButton"
              toolbar="bottom"
              location="after"
              :options="closeButtonOptions"
              v-model:visible="isShowButton"
            />
            <DxToolbarItem
              widget="dxButton"
              toolbar="bottom"
              location="after"
              :options="saveButtonOptions"
              v-model:visible="isShowButton"
            />
            <template #content>
              <div class="dx-fieldset">
                <div class="dx-field">
                  <div class="dx-field-label">Tahun DRP</div>
                  <div class="dx-field-value">
                    <DxSelectBox
                      :data-source="dropdown"
                      drop-down-button-template="imageIcon"
                    >
                      <template #imageIcon="{}">
                        <!-- <img
                          src="images/icons/custom-dropbutton-icon.svg"
                          class="custom-icon"
                        /> -->
                      </template>
                    </DxSelectBox>
                  </div>
                </div>
              </div>
              <DxScrollView width="100%" height="100%" padding="100px">
                <div id="textBlock">
                  <div>
                    <div class="dx-fieldset-header">Dokumen RKAP *</div>
                    <DxDataGrid
                      ref="currDataGrid"
                      :data-source="dataDrpDokumen"
                      key-expr="id"
                      :allow-column-reordering="true"
                      :column-auto-width="true"
                      @row-inserting="
                        ($event) => {
                          $event.data.filename = fileNames.map(
                            (name) => name.name
                          );
                        }
                      "
                    >
                      <DxEditing
                        v-if="isShowButton"
                        :allow-adding="true"
                        :allow-updating="true"
                        :allow-deleting="true"
                        :use-icons="true"
                        mode="popup"
                      >
                        <DxTexts
                          add-row="Tambah"
                          edit-row="Ubah"
                          delete-row="Hapus"
                          confirm-delete-message="Apakah anda yakin untuk menghapus data ini?"
                          save-row-changes="Simpan"
                          cancel-row-changes="Batal"
                        ></DxTexts>
                        <DxForm label-location="top" :col-count="1">
                          <DxItem dataField="jenisDokumenId">
                            <DxRequiredRule
                              message="Jenis dokumen harus diisi"
                            />
                          </DxItem>
                          <DxItem dataField="filename">
                            <div class="fileuploader-container">
                              <DxFileUploader
                                select-button-text="Browse File"
                                label-text=""
                                accept="*"
                                upload-url=""
                                upload-mode="instantly"
                                @value-changed="onChangeUploadFile"
                              />
                            </div>
                          </DxItem>
                          <DxItem dataField="keterangan">
                            <DxRequiredRule message="Keterangan harus diisi">
                              <DxTextArea
                                v-model:height="height"
                                :max-length="maxLength"
                                v-model:value="value"
                                v-model:auto-resize-enabled="autoResizeEnabled"
                              />
                            </DxRequiredRule>
                          </DxItem>
                        </DxForm>
                        <DxPopup
                          :hide-on-outside-click="true"
                          :show-title="true"
                          :width="400"
                          :height="400"
                          title="Form Jenis Pengadaan"
                        >
                          <DxPosition
                            at="center"
                            my="center"
                            v-model:of="positionOf"
                            collision="fit"
                          />
                        </DxPopup>
                      </DxEditing>
                      <DxToolbar>
                        <DxItem name="groupPanel" />
                        <DxItem name="searchPanel" location="before" />
                        <DxItem
                          name="addRowButton"
                          show-text="always"
                          css-class=""
                        >
                          <DxTexts add-row="Tambah"></DxTexts>
                        </DxItem>
                        <DxItem name="exportButton" />
                        <DxItem name="columnChooserButton" />
                      </DxToolbar>
                      <DxFilterRow :visible="false" />
                      <DxColumn
                        cell-template="row-cell-template"
                        caption="No"
                        :width="45"
                      ></DxColumn>
                      <DxColumn
                        data-field="jenisDokumenId"
                        caption="Jenis Dokumen"
                        alignment="left"
                      >
                        <!-- <DxLookup
                          :data-source="jenisDokumen"
                          value-expr="ID"
                          display-expr="Name"
                        /> -->
                      </DxColumn>
                      <DxColumn data-field="filename" caption="File">
                      </DxColumn>
                      <DxColumn
                        data-field="keterangan"
                        caption="Keterangan"
                      ></DxColumn>
                      <DxColumn type="buttons" caption="Aksi">
                        <DxButton text="edit" icon="edit" />
                        <DxButton text="remove" icon="trash" />
                      </DxColumn>
                      <template #row-cell-template="{ data }">
                        {{ data.rowIndex + 1 }}
                      </template>
                    </DxDataGrid>

                    <div class="dx-fieldset-header">Dokumen Pendukung *</div>
                    <DxDataGrid
                      ref="currDataGrid"
                      :data-source="dataDrpDokumenPendukung"
                      key-expr="id"
                      :allow-column-reordering="true"
                      :column-auto-width="true"
                      @row-inserting="
                        ($event) => {
                          $event.data.filename = fileNames.map(
                            (name) => name.name
                          );
                        }
                      "
                    >
                      <DxEditing
                        v-if="isShowButton"
                        :allow-adding="true"
                        :allow-updating="true"
                        :allow-deleting="true"
                        :use-icons="true"
                        mode="popup"
                      >
                        <DxTexts
                          add-row="Tambah"
                          edit-row="Ubah"
                          delete-row="Hapus"
                          confirm-delete-message="Apakah anda yakin untuk menghapus data ini?"
                          save-row-changes="Simpan"
                          cancel-row-changes="Batal"
                        ></DxTexts>
                        <DxForm label-location="top" :col-count="1">
                          <DxItem dataField="jenisDokumenId">
                            <DxRequiredRule
                              message="Jenis dokumen harus diisi"
                            />
                          </DxItem>
                          <DxItem dataField="filename">
                            <div class="fileuploader-container">
                              <DxFileUploader
                                select-button-text="Browse File"
                                label-text=""
                                accept="*"
                                upload-url=""
                                upload-mode="instantly"
                                @value-changed="onChangeUploadFile"
                              />
                            </div>
                          </DxItem>
                          <DxItem dataField="keterangan">
                            <DxRequiredRule message="Keterangan harus diisi">
                              <DxTextArea
                                v-model:height="height"
                                :max-length="maxLength"
                                v-model:value="keterangan"
                                v-model:auto-resize-enabled="autoResizeEnabled"
                              />
                            </DxRequiredRule>
                          </DxItem>
                        </DxForm>
                        <DxPopup
                          :hide-on-outside-click="true"
                          :show-title="true"
                          :width="400"
                          :height="400"
                          title="Tambah"
                        >
                          <DxPosition
                            at="center"
                            my="center"
                            v-model:of="positionOf"
                            collision="fit"
                          />
                        </DxPopup>
                      </DxEditing>
                      <DxToolbar>
                        <DxItem name="groupPanel" />
                        <DxItem name="searchPanel" location="before" />
                        <DxItem
                          name="addRowButton"
                          show-text="always"
                          css-class=""
                        >
                          <DxTexts add-row="Tambah"></DxTexts>
                        </DxItem>
                        <DxItem name="exportButton" />
                        <DxItem name="columnChooserButton" />
                      </DxToolbar>
                      <DxFilterRow :visible="false" />
                      <DxColumn
                        cell-template="row-cell-template"
                        caption="No"
                        :width="45"
                      ></DxColumn>

                      <DxColumn
                        data-field="jenisDokumenId"
                        caption="Jenis Dokumen"
                        alignment="left"
                      >
                        <!-- <DxLookup
                          display-expr="name"
                          value-expr="value"
                          :data-source="jenisDokumen"
                        /> -->
                      </DxColumn>
                      <DxColumn data-field="filename" caption="File">
                      </DxColumn>
                      <DxColumn
                        data-field="keterangan"
                        caption="Keterangan"
                      ></DxColumn>
                      <DxColumn type="buttons" caption="Aksi">
                        <DxButton text="edit" icon="edit" />
                        <DxButton text="remove" icon="trash" />
                      </DxColumn>
                      <template #row-cell-template="{ data }">
                        {{ data.rowIndex + 1 }}
                      </template>
                    </DxDataGrid>
                  </div>
                </div>
              </DxScrollView>
            </template>
          </Popup>

          <DxDataGrid
            ref="currDataGrid"
            :data-source="dataSource"
            key-expr="id"
            :allow-column-reordering="true"
            :column-auto-width="true"
          >
            <DxEditing
              :allow-adding="true"
              :allow-updating="true"
              :allow-deleting="true"
              :use-icons="true"
              mode="popup"
            >
              <DxTexts
                add-row="Tambah"
                edit-row="Ubah"
                delete-row="Hapus"
                confirm-delete-message="Apakah anda yakin untuk menghapus data ini?"
                save-row-changes="Simpan"
                cancel-row-changes="Batal"
              ></DxTexts>
              <DxForm label-location="top" :col-count="1">
                <DxItem dataField="tahun">
                  <DxRequiredRule message="Tahun harus diisi" />
                </DxItem>
              </DxForm>
              <DxPopup
                :hide-on-outside-click="true"
                :show-title="true"
                :width="400"
                :height="400"
                title="Form Jenis Pengadaan"
              >
                <DxPosition
                  at="center"
                  my="center"
                  v-model:of="positionOf"
                  collision="fit"
                />
              </DxPopup>
            </DxEditing>
            <DxToolbar>
              <DxItem name="groupPanel" />
              <DxItem name="searchPanel" location="before" />
              <DxItem name="addRowButton" show-text="always" css-class="">
                <DxTexts add-row="Tambah"></DxTexts>
              </DxItem>
              <DxItem name="exportButton" />
              <DxItem name="columnChooserButton" />
            </DxToolbar>
            <DxPaging :page-size="5" />
            <DxPager
              :visible="true"
              :allowed-page-sizes="[5, 10, 50]"
              display-mode="compact"
              :show-page-size-selector="true"
              :show-info="true"
              :show-navigation-buttons="true"
              info-text="Hal {0} dari {1} ({2} data)"
            />
            <DxFilterRow :visible="false" />
            <DxColumn
              cell-template="row-cell-template"
              caption="No"
              :width="45"
            ></DxColumn>
            <DxColumn
              data-field="tahun"
              caption="Tahun DRP"
              alignment="left"
            ></DxColumn>
            <DxColumn
              data-field="approveStatus"
              caption="Status Approve"
              alignment="left"
            ></DxColumn>
            <DxColumn
              data-field="approveDate"
              caption="Tanggal Approve"
              data-type="date"
            ></DxColumn>
            <DxColumn type="buttons" caption="Aksi">
              <DxButton
                text="Dokumen"
                icon="attach"
                hint="Dokumen Pendukung DRP"
                :on-click="linkDokumen"
              />
              <DxButton
                text="Detil"
                icon="search"
                hint="Detil/Konten DRP "
                :on-click="linkDetail"
              />
              <DxButton
                text="Kirim"
                icon="movetofolder"
                hint="Kirim DRP"
                :on-click="linkKirim"
              />
            </DxColumn>
            <DxColumn type="adaptive" :width="50">
              <DxButton hint="detail" icon="copy" />
            </DxColumn>
            <template #row-cell-template="{ data }">
              {{ data.rowIndex + 1 }}
            </template>
            <DxSearchPanel
              :visible="true"
              :highlight-case-sensitive="true"
              :width="300"
              placeholder="Cari Penyusunan DRP..."
            />
          </DxDataGrid>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import DxDataGrid, {
  DxEditing,
  DxItem,
  DxForm,
  DxColumn,
  DxFilterRow,
  DxPager,
  DxPaging,
  DxSearchPanel,
  DxToolbar,
  DxTexts,
  DxButton,
  DxRequiredRule,
  // DxLookup,
  DxPopup,
} from "devextreme-vue/data-grid";
import CustomStore from "devextreme/data/custom_store";
import {
  DxPopup as Popup,
  DxToolbarItem,
  DxPosition,
} from "devextreme-vue/popup";
import { DxScrollView } from "devextreme-vue/scroll-view";
import { DxSelectBox } from "devextreme-vue/select-box";
import { DxFileUploader } from "devextreme-vue/file-uploader";
import DxTextArea from "devextreme-vue/text-area";

const approveStatus = [
  { name: "Penyusunan", value: 0 },
  { name: "Approval VP", value: 1 },
  { name: "Rekomendasi Komite", value: 2 },
  { name: "Approval DIRUT", value: 3 },
  { name: "Approved", value: 4 },
  { name: "Revisi DRP", value: 1 },
];

const URL = process.env.VUE_APP_ROOT_API + "/drp";

const dataSource = new CustomStore({
  key: "id",

  load: () => {
    return fetch(URL + process.env.VUE_APP_PAGE_SIZE)
      .then((response) => response.json())
      .then((response) => {
        return {
          data: response.data,
          totalCount: response.pagination.totalRecords,
        };
      })
      .catch(() => {
        throw new Error("Terdapat kesalahan memuat data");
      });
  },

  insert: (values) => {
    return fetch(URL, {
      method: "POST",
      body: JSON.stringify(values),
      headers: {
        "Content-Type": "application/json",
      },
    });
  },

  update: (key, values) => {
    return fetch(URL + "/" + encodeURIComponent(key), {
      method: "PUT",
      body: JSON.stringify(values),
      headers: {
        "Content-Type": "application/json",
      },
    });
  },

  remove: (key) => {
    return fetch(URL + "/" + encodeURIComponent(key), {
      method: "DELETE",
    });
  },
});

// const dataDrpDokumen = new CustomStore({
//   key: "id",
//   load: (key) => {
//     return fetch(URL + "/" + encodeURIComponent(key) + "?size=100")
//       .then((response) => response.json())
//       .then((response) => {
//         console.log("res", response.dataDrpDokumen);
//         console.log("key: ", key);
//         return {
//           data: response.dataDrpDokumen,
//         };
//       })
//       .catch(() => {
//         throw new Error("Terdapat kesalahan memuat data");
//       });
//   },

//   insert: (values) => {
//     return fetch(URL, {
//       method: "POST",
//       body: JSON.stringify(values),
//       headers: {
//         "Content-Type": "application/json",
//       },
//     });
//   },

//   update: (key, values) => {
//     return fetch(URL + "/" + encodeURIComponent(key), {
//       method: "PUT",
//       body: JSON.stringify(values),
//       headers: {
//         "Content-Type": "applicatoin/json",
//       },
//     });
//   },

//   remove: (key) => {
//     return fetch(URL + "/" + encodeURIComponent(key), {
//       method: "DELETE",
//     });
//   },
// });
let dataDrpDokumen = [];
let dataDrpDokumenPendukung = [];

export default {
  setup() {
    return {
      approveStatus,
    };
  },
  components: {
    DxDataGrid,
    DxEditing,
    DxItem,
    DxForm,
    DxColumn,
    DxFilterRow,
    DxPager,
    DxPaging,
    DxSearchPanel,
    DxToolbar,
    DxTexts,
    DxButton,
    DxRequiredRule,
    // DxLookup,
    DxPopup,
    DxScrollView,
    Popup,
    DxToolbarItem,
    DxPosition,
    DxSelectBox,
    DxFileUploader,
    DxTextArea,
  },
  methods: {
    linkDokumen($event) {
      fetch(URL + "/" + $event.row.data.id)
        .then((response) => response.json())
        .then((response) => {
          return (
            (this.dataDrpDokumen = response.dataDrpDokumen),
            (this.dataDrpDokumenPendukung = response.dataDrpDokumenPendukung)
          );
        })
        .catch(() => {
          throw new Error("Terdapat kesalahan memuat data");
        });
      // dataDrpDokumen.key($event.row.data.id)
      // dataDrpDokumen.load($event.row.data.id);

      this.popupVisible = true;
      this.popupTitle = "Upload Dokumen Pendukung";
      this.isShowButton = true;
    },
    linkDetail() {
      this.popupVisible = true;
      this.popupTitle = "Lihat Dokumen Pendukung";
      this.isShowButton = false;
    },
    linkKirim($event) {
      console.log("event: ", $event.row.values);
      this.popupVisible = true;
      this.popupTitle = "Review & Approval DRP";
      this.dataDrp = $event.row.values;
      this.isShowButton = true;
      console.log("drp: ", this.dataDrp);
    },
    onChangeUploadFile($event) {
      this.fileNames = $event.value;
      console.log("file", this.fileNames);
    },
    logEvent(eventName) {
      console.log("event", eventName.value);
    },
  },
  data() {
    return {
      //jsonUrl: URL,
      dataSource,
      dropdown: "",
      popupVisible: false,
      popupTitle: "",
      isShowButton: true,
      dataDrpDokumen,
      dataDrpDokumenPendukung,
      fileNames: [],
      saveButtonOptions: {
        text: "Simpan",
        onClick: () => {
          this.popupVisible = false;
          console.log("simpan");
        },
      },
      closeButtonOptions: {
        text: "Batal",
        onClick: () => {
          this.popupVisible = false;
        },
      },
    };
  },
};
</script>

<style lang="scss">
.dx-link.dx-icon-attach.dx-link-icon {
  color: #dbd203;
}
.dx-link.dx-icon-search.dx-link-icon {
  color: #ff9a62;
}
.dx-link.dx-icon-movetofolder.dx-link-icon {
  color: #0996c2;
}
.dx-scrollable {
  padding-bottom: 50px;
}
.dx-field {
  display: flex;
  flex-direction: column;
}
.dx-fieldset-header {
  position: relative;
  margin-bottom: -30px;
  z-index: 20;
  width: fit-content;
}
.fileuploader-container {
  border: solid 1px #dbd203;
  padding: 0;
}
.dx-fileuploader-wrapper {
  padding: 0;
}
</style>
