<template>
  <div v-if="pagedata">
    <p class="has-text-right has-text-grey is-italic fs-13 mb-1">Chọn để ẩn hiện cột, kéo thả thay đổi vị trí</p>
        <b-table
          class="fs-13"
          :data="fields"
          draggable
          @dragstart="dragstart"
          @drop="drop"
          @dragover="dragover"
          @dragleave="dragleave"
        >
          <b-table-column field="index" label="Tt cột" numeric v-slot="props">
          {{ `C${props.index}` }}
          </b-table-column>
          <b-table-column field="label" label="Tên trường" v-slot="props">
            <span class="hyperlink" @click="openField(props.row)" v-if="1>0">{{ props.row.name }}</span>
            <span v-else>{{  props.row.name }}</span>
            <a @click="copyContent(props.row.name)">
            <span class="icon"><i class="mdi mdi-content-copy"/></span>
          </a>
          </b-table-column>
          <b-table-column>
          <template v-slot:header="{}">
            Tên cột
            <a class="ml-2" @click="edit=!edit">{{edit? 'Cập nhật' : 'Sửa tên'}}</a>
        </template>
         <template v-slot="props" v-if="edit">
           <input class="input is-small" type="text" placeholder="" v-model="props.row.label" @change="checkChange(props.row)">
         </template>
        <template v-slot="props" v-else>
           {{$stripHtml(props.row.label, 80)}}
         </template>
         </b-table-column>
          <b-table-column field="check" width="80px">
          <template v-slot:header="{}">
            <span :class="`material-symbols-outlined fs-18 ${checkAll? 'has-text-primary' : 'has-text-grey'} is-clickable`" @click="multiCheck()">
  {{ checkAll? 'visibility' : 'visibility_off' }}
  </span>
  
            <span class="is-clickable" @click="deleteConfirm()"> 
              <span class="material-symbols-outlined fs-18 ml-3">delete</span>
            </span>
        </template>
        <template v-slot="props">
        <span class="is-clickable" v-if="!(props.row.required || props.row.mandatory)" @click="checkChange(props.row)">
          <span :class="`material-symbols-outlined fs-18 ${props.row.show? 'has-text-primary' : 'has-text-grey'}`">
  {{ props.row.show? 'visibility' : 'visibility_off' }}
  </span>
        </span>
             <span class="is-clickable ml-3" v-if="!(props.row.required || props.row.mandatory)" @click="deleteRow(props.index)">
              <span class="material-symbols-outlined fs-18">delete</span>
            </span>
        </template>
      </b-table-column>
      </b-table>
      <Modal @close="showmodal=undefined" v-bind="showmodal" v-if="showmodal" @update="updateField"></Modal>
  </div>
  </template>
  <script>
  export default {
    props: ['pagename', 'detail'],
    data() {
      return {
        fields: [],
        draggingRow: undefined,
        draggingRowIndex: undefined,
        checkAll: true,
        change: false,
        edit: false,
        showmodal: undefined
      }
    },
    created() {
      if (this.pagedata) this.fields = this.$copy(this.pagedata.fields)
    },
    watch: {
      'pagedata.fields': function(newVal) {
        if(this.change) this.change = false
        else this.fields = this.$copy(this.pagedata.fields)
      }
    },
    computed: {
      pagedata: {
        get: function() {return this.$store.state[this.pagename]},
        set: function(val) {this.$store.commit('updateStore', {name: this.pagename, data: val})}
      },
      settingclass: {
        get: function() {return this.$store.state.settingclass},
        set: function(val) {this.$store.commit("updateSettingClass", { settingclass: val })}
      }
    },
    methods: {
      multiCheck() {
        this.checkAll = !this.checkAll
        let newVal = this.checkAll
        this.fields.filter((v) => !v.mandatory).map((x) => (x.show = newVal));
        this.fields = this.$copy(this.fields);
        this.change = true
        this.$store.commit("updateState", {name: this.pagename, key: "update", data: {fields: this.$copy(this.fields)}})
      },
      openField(v) {
        this.showmodal = {title: `${v.name} / ${this.$stripHtml(v.label,50)}`, component: "datatable/FieldAttribute", vbind: {field: v}, width: '40%', height: '600px'}
      },
      deleteConfirm() {
        this.$buefy.dialog.confirm({
          message: 'Bạn có chắc chắc muốn xóa tất cả các trường không?.',
          confirmText: 'Có',
          cancelText: 'Không',
          onConfirm: () => {this.deleteFields()}
        })
      },
      copyContent(value) {
        this.$copyToClipboard(value)
      },
      checkChange(row) {
        row.show = !row.show
        this.change = true
        this.$store.commit("updateState", {name: this.pagename, key: "update", data: {fields: this.$copy(this.fields)}})
      },
      deleteRow(idx) {
        this.change = true
        this.$delete(this.fields, idx)
        this.$store.commit("updateState", {name: this.pagename, key: "update", data: {fields: this.$copy(this.fields)}})
      },
      deleteFields() {
        let filter = this.fields.filter(
          (v) => !v.mandatory && !v.required
        );
        if (filter.length === 0) return;
        filter.map((v) => {
          let idx = this.fields.findIndex((x) => x.name === v.name);
          if (idx >= 0) this.$delete(this.fields, idx);
        });
        this.change = true
        this.$store.commit("updateState", {name: this.pagename, key: "update", data: {fields: this.$copy(this.fields)}})
      },
      dragstart(payload) {
        this.draggingRow = payload.row;
        this.draggingRowIndex = payload.index;
        payload.event.dataTransfer.effectAllowed = "copy";
      },
      dragover(payload) {
        payload.event.dataTransfer.dropEffect = "copy";
        payload.event.target.closest("tr").classList.add("is-selected");
        payload.event.preventDefault();
      },
      dragleave(payload) {
        payload.event.target.closest("tr").classList.remove("is-selected");
        payload.event.preventDefault();
      },
      drop(payload) {
        payload.event.target.closest("tr").classList.remove("is-selected")
        this.$arrayMove(this.fields, this.draggingRowIndex, payload.index)
        this.change = true
        this.$store.commit("updateState", {name: this.pagename, key: "update", data: {fields: this.$copy(this.fields)}})
      },
      exportData() {
        this.$exportExcel(this.pagedata.dataFilter || this.pagedata.data, 'data-export', this.pagedata.fields.filter(v=>v.show))
      },
      updateField(field) {
        let copy = this.$copy(this.pagedata.fields)
        let idx = copy.findIndex(v=>v.name===field.name)
        copy[idx] = field
        this.$store.commit("updateState", {name: this.pagename, key: "update", data: {fields: copy}})
      }
    }
  }
  </script>
  
  <style scoped>
    * >>> .table tbody tr td {
      height: 14px !important;
      padding-top: 0px !important;
      padding-bottom: 0px !important;
    }
  </style>