<template>
  <div>
    <table
      :id="id"
      class="table table-striped table-bordered table-hover"
    />
  </div>
</template>

<script>
const _ = require('lodash');
let host = require('./js/const').apiHost;

const $ = (window.jQuery = require('jquery'));
require('@/components/js/datatable');

let table;

export default {
  name: 'UpdateItemTable',
  props: ['id', 'data', 'meta'],
  data() {
    return {
      rows: [],
      header: [],
      total: 0,
      isDev: process.env.NODE_ENV === 'development',
    };
  },
  computed: {
    jwt: function () {
      return this.$store.getters['User/jwt'];
    },
    getRole: function () {
      return this.$store.getters['User/userRole'];
    },
  },
  mounted() {
    const vm = this;
    vm.createTable(vm.id);
  },
  methods: {
    editUpdateItem(id) {
      // eslint-disable-next-line
      this.$router.push("/updateitem/" + id);
    },
    createTable(id) {
      const vm = this;

      const columns = [
        {
          title: 'ID',
          data: 'id',
          fnCreatedCell: (nTd, sData, oData) => {
            $(nTd).html(`<a href="" class="edit-link"> ${sData}</a>`);
          },
        },
        {
          title: 'Resource Name',
          data: 'attributes.Entity',
        },
        {
          title: 'Resource ID',
          data: 'attributes.EntityId',
          className: 'whitespace-normal break-all',
          fnCreatedCell: (nTd, sData, oData) => {
            if (oData.attributes.Entity === 'protein') {
              $(nTd).html(
                `<a href='/protein/${sData}' class='resource-link'> ${sData}</a>`
              );
            } else if (oData.attributes.Entity === 'condensate') {
              $(nTd).html(
                `<a href='/condensate/${sData}' class='resource-link'> ${sData}</a>`
              );
            } else if (oData.attributes.Entity === 'condensate_protein') {
              $(nTd).html(
                `<a href='/condensate/${
                  sData.split('==')[0]
                }' class='resource-link'> ${sData}</a>`
              );
            } else {
              $(nTd).html(`${sData}`);
            }
          },
        },
        {
          title: 'Attribute',
          data: 'attributes.Attribute',
        },
        {
          title: 'Value',
          data: 'attributes.Value',
           render: function (data, type, row, meta) {
                
                if(data==='frap'){
                  return data.toUpperCase();
                }else if(data === 'self_ps'){
                  return 'Self-PS'
                }else{
                  return _.startCase(data)
                }
                // console.log(_.flatMap(row.condensates, c => c.data_sources))
                // if (!vm.proteinDriverCriterion) {
                //   return;
                // }
                // let dat = vm.proteinDriverCriterion[row.uniprot_id];
                // if (dat) {
                 
                //  const val= dat.map(i=> i==='self_ps'? dat[i]='Self-PS': _.startCase(i))
                  
                //   return val.join(', ');
                // }
                // return '';
              },
        },
        {
          title: 'Change Operation',
          data: 'attributes.ChangeOperation',
        },
        {
          title: 'Status',
          data: 'attributes.Status',
          //         render: function(row, data, index){
          //           console.log("in color new", data);
          //   if(data.attributes.Status === 'rejected'){
          //     console.log("working in rejected");
          //       $(row).find('td:eq(3)').css('color', 'red');
          //   }

          // }
          fnCreatedCell: (nTd, sData, oData) => {
            if (sData === 'synced') {
              $(nTd).html(
                `<div class="rounded-full font-bold capitalize px-4 mr-2 bg-gray-500 text-white p-2 rounded flex items-center justify-center">${sData}</div>`
              );
            } else if (sData === 'accepted') {
              $(nTd).html(
                `<div class="rounded-full font-bold capitalize px-4 mr-2 bg-green-500 text-white p-2 rounded flex items-center justify-center">${sData}</div>`
              );
            } else if (sData === 'rejected') {
              $(nTd).html(
                `<div class="rounded-full font-bold capitalize px-4 mr-2 bg-red-500 text-white p-2 rounded flex items-center justify-center">${sData}</div>`
              );
            } else if (sData === 'requested') {
              $(nTd).html(
                `<div class="rounded-full font-bold capitalize px-4 mr-2 bg-yellow-500 text-white p-2 rounded flex items-center justify-center">${sData}</div>`
              );
            }
          },
        },
        {
          title: 'Submitted at',
          data: 'attributes.SubmittedAt',
          className: 'whitespace-normal',
          render: function (data, type, row, meta) {
            return new Date(Date.parse(data)).toLocaleString();
          },
        },

        {
          title: 'Action',
          // data: `<button class="btn btn-primary edit-link btn-outline font-bold" style="font-weight:bold">
          //           View<i class="fa fa-edit" style="font-weight:bold"></i>
          //           </button>`,
          defaultContent: `<button class=" rounded-md bg-transparent hover:bg-blue-600 text-blue-700
                                           hover:text-white
                                           border border-blue-500
                                           hover:border-transparent
                                           focus:ring-2 focus:ring-blue-300
                                            items-center
                                            px-4
                                            py-2
                                            font-bold
                                            text-center view-link">
                    View
                    </button>`,
          // render: function (data, type, row, meta) {

          //   if(vm.getRole === "Maintainer"){
          //     console.log(" yea true", data.data.attributes);
          //     console.log(data.data.attributes);
          //     if(data.data.attributes.Status==="requested"){
          //       console.log(data.data.attributes.Status);
          //       return `<button class="btn btn-primary edit-link btn-outline font-bold" style="font-weight:bold">
          //           Accept<i class="fa fa-edit" style="font-weight:bold"></i>
          //           </button>`
          //     }
          //     else{
          //       return `<button class="btn btn-primary edit-link btn-outline font-bold" style="font-weight:bold">
          //           Synced<i class="fa fa-edit" style="font-weight:bold"></i>
          //           </button>`
          //     }
          //   }

          // },
          //  fnCreatedCell: (nTd, sData, oData) => {
          //       $(nTd).html(
          //         `<button class="btn btn-primary edit-link btn-outline font-bold" style="font-weight:bold">
          //           <i class="fa fa-edit" style="font-weight:bold"></i>
          //           </button>
          //           <button class="btn btn-danger delete-link btn-outline font-bold" style="font-weight:bold">
          //           <i class="fa fa-trash" style="font-weight:bold"></i>
          //           </button>
          //           `
          //       );
          //     },
        },
        // {
        //   title: "Reviewer",
        //   data: "attributes.reviewedBy",
        //   render: function (data, type, row, meta) {
        //     if (data.data) {
        //       return data.data.attributes.username;
        //     } else {
        //       return "";
        //     }
        //   },
        // },
      ];

      vm.headers = columns;

      const nTableOptions = {
        columns,
        // aaSorting: [[ 0, 'asc' ]],
        lengthMenu: [
          [10, 25, 50, 100],
          [10, 25, 50, 100],
        ],
        paging: true,
        searching: true,
        info: true,
        bProcessing: true,
        bServerSide: true,
        order: [], // order: [[0, 'asc']],
        bDestroy: true, // Add this property to new setting,
        oLanguage: {
          sSearch: 'Filter',
        },
        rowCallback: function (row, data) {
          if (
            !data.attributes.SyncResponse &&
            data.attributes.Status != 'rejected'
          ) {
            $(row).css('background-color', '#e6e6e6');
          }
        },
        fnServerData: function (sSource, aoData, fnCallback, oSettings) {
          oSettings.jqXHR = vm.fetchCallback(vm.rows, aoData, fnCallback);
        },
        dom: '<"row"<"col-sm-2"l><"col-sm-2"f><"col-sm-8"p>><"row"t><"row"<"col-sm-4"i><"col-sm-8"p>>',
      };

      const tableId = `#${id}`;
      if (table) {
        table.destroy();
        $(tableId).empty();
      }

      table = $(tableId).DataTable(nTableOptions);

      const tableBody = `${tableId} tbody`;

      $(table.row(1).nodes()).addClass('Highlight_inUse');

      $(tableBody).on('click', 'tr td a.edit-link', (e) => {
        e.preventDefault();
        const tr = $(e.target).parent().parent();
        const row = table.row(tr);
        vm.editUpdateItem(row.data().id);
      });
      $(tableBody).on('click', 'tr td button.view-link', (e) => {
        e.preventDefault();
        const tr = $(e.target).parent().parent();
        const row = table.row(tr);
        vm.editUpdateItem(row.data().id);
      });
    },
    async fetchCallback(data, aoData, fnCallback) {
      let vm = this;

      // console.log(aoData)
      let orderItem = aoData.find((x) => x.name === 'order');
      let startItem = aoData.find((x) => x.name === 'start');
      let lengthItem = aoData.find((x) => x.name === 'length');
      let searchItem = aoData.find((x) => x.name === 'search');
      // console.log(`length = ${lengthItem.value}, offset = ${startItem.value}`)
      // console.log(`orderItem = ${orderItem.value}, searchItem = ${searchItem.value.value}`)

      const page = startItem.value / lengthItem.value + 1;

      let search = searchItem.value.value;

      if (vm.isDev) {
        host = require('./js/const').devApiHost;
      }

      const qs = require('qs');
      const query = {
        pagination: {
          pageSize: lengthItem.value,
          page: page,
        },
      };

      const columns = [
        'id',
        'Entity',
        'EntityId',
        'Attribute',
        'Value',
        'ChangeOperation',
        'Status',
        'SubmittedAt',
      ];

      let order = ['SubmittedAt:desc'];
      if (orderItem.value.length > 0) {
        orderItem.value.forEach(function (data) {
          // console.log(data)
          order = `${columns[data.column]}:${data.dir}`;
        });
        // console.log(order)
      }

      query['sort'] = order;

      if (searchItem.value.value) {
        query['filters'] = {
          $or: [
            {
              Entity: {
                $containsi: search,
              },
            },
            {
              EntityId: {
                $containsi: search,
              },
            },
            {
              ChangeOperation: {
                $containsi: search,
              },
            },
            {
              Attribute: {
                $containsi: search,
              },
            },
            {
              Value: {
                $containsi: search,
              },
            },
          ],
        };
      }

      const queryString = qs.stringify(query, {
        encodeValuesOnly: true,
      });

      let url = `${host}/api/update-item/filterCondensateRequest/${vm.data}?${queryString}`;

      const jwt = vm.jwt;
      if (jwt === null) {
        return;
      }

      try {
        const res = await this.axios.get(url, {
          headers: {
            Authorization: `Bearer ${jwt}`,
          },
        });

        if (res.data) {
          let dat = {
            draw: aoData.draw,
            recordsTotal: query['filters']
              ? vm.total
              : (vm.total = res.data.meta.pagination.total),
            recordsFiltered: res.data.meta.pagination.total,
            data: res.data.data,
          };

          fnCallback(dat);
        }
      } catch (error) {
        this.error = true;
        this.errorMsg = 'You are not authorized to access this item.';
      }
    },
    exportTsv() {
      // const vm = this;
    },
  },
};
</script>

<style>
@import url("~@/assets/datatable.css");

select.form-control {
  font-size: 12px;
  padding: 3px 12px;
}

ul.pagination {
  font-size: 1rem;
}

.form-inline .form-control {
  height: 25px;
  line-height: 25px;
  vertical-align: middle;
}

.edit-link {
  font-weight: bold;
  color: #0065b9;
}

.resource-link {
  font-weight: bold;
  color: #0065b9;
}

.pagination {
  font-size: 1.2rem;
}

table.Highlight {
  background-color: #ffa;
}

.panel-table {
  font-size: 1.4rem;
  margin-bottom: 20px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}
</style>