<template>

  <div class="q-pa-md">
    <div class="q-gutter-sm row items-start">
    <q-breadcrumbs>
      <q-breadcrumbs-el icon="assignment_ind" label="ドメイン適用" />
    </q-breadcrumbs>
  </div>
    <q-table :loading="loading" grid grid-header title="Domain" selection="single" :rows="rows" :columns="columns" row-key="name"
      :filter="userDomainTableFilter" virtual-scroll v-model:pagination="pagination">
      <template v-slot:top>

        <q-btn class="q-mx-none" color="primary" label="追加" @click="clickAddDomain()" />

        <q-space />
        <div class="row q-gutter-md">
          <!-- <q-item v-if="authStore.permissions === 'admin'" tag="label" dense @click="clickSwitchUser()">
            <q-item-section>
              <q-item-label>適用するユーザ : </q-item-label>
            </q-item-section>
            <q-item-section avatar>
              {{ currentUserName }}
            </q-item-section>
          </q-item> -->

          <q-input borderless dense filled debounce="300" v-model="userDomainTableFilter" placeholder="Search">
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
        </div>
      </template>

      <template v-slot:header>
        <div style="height: 1dvh">
        </div>
      </template>

      <template v-slot:item="props">
        <div class="q-pa-sm">
          <q-card>
            <q-card-section>
              <div class="q-table__grid-item-row">
                <div class="q-table__grid-item-title">Domain</div>
                <div class="q-table__grid-item-value">{{ props.row.name }}</div>
              </div>
              <div class="q-table__grid-item-row">
                <div class="q-table__grid-item-title">URL</div>
                <div class="q-table__grid-item-value" style="width: 22rem;">{{ props.row.url }}</div>
              </div>
              <div class="q-table__grid-item-row">
                <div class="q-table__grid-item-title">Account</div>
                <div class="q-table__grid-item-value">{{ props.row.kintoneuser }}</div>
              </div>
            </q-card-section>
            <q-separator />
            <q-card-actions align="right">
              <div style="width: 98%;">
                <div class="row items-center justify-between">
                  <div class="q-table__grid-item-value"
                    :class="isActive(props.row.id) ? 'text-positive' : 'text-negative'">{{
                      isActive(props.row.id)?'既定':'' }}</div>
                  <div class="col-auto">
                    <q-btn v-if="!isActive(props.row.id)" flat
                      @click="activeDomain(props.row)">既定にする</q-btn>
                    <q-btn flat @click="clickDeleteConfirm(props.row)">削除</q-btn>
                  </div>
                </div>
              </div>
            </q-card-actions>
          </q-card>
        </div>
      </template>
    </q-table>

    <show-dialog v-model:visible="showAddDomainDg" name="ドメイン" @close="addUserDomainFinished">
      <domain-select ref="addDomainRef" name="ドメイン" type="single" :filterInitRowsFunc="filterAddDgInitRows"></domain-select>
    </show-dialog>

    <show-dialog v-model:visible="showSwitchUserDd" name="ドメイン" minWidth="35vw" @close="switchUserFinished">
      <template v-slot:toolbar>
        <q-input dense placeholder="検索" v-model="switchUserFilter">
          <template v-slot:append>
            <q-icon name="search" />
          </template>
        </q-input>
      </template>
      <div class="q-gutter-md">
        <q-item tag="label" class="q-pl-sm q-pr-none q-py-xs">
          <q-item-section>
            <q-item-label>他のユーザーを選択する</q-item-label>
          </q-item-section>
          <q-item-section avatar>
            <q-toggle v-model="useOtherUser" />
          </q-item-section>
        </q-item>
        <div v-if="useOtherUser">
          <user-list ref="switchUserRef" name="ドメイン" :filter="switchUserFilter" />
        </div>
      </div>

    </show-dialog>

    <q-dialog v-model="showDeleteConfirm" persistent>
      <q-card>
        <q-card-section class="row items-center">
          <div class="q-ma-sm q-mt-md">
            <q-icon name="warning" color="warning" size="2em" />
            <span class="q-ml-sm">削除してもよろしいですか？</span>
          </div>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="Cancel" color="primary" v-close-popup />
          <q-btn flat label="OK" color="primary" v-close-popup @click="deleteDomainFinished()" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { api } from 'boot/axios';
import { useAuthStore } from 'stores/useAuthStore';
import { useDomainStore } from 'stores/useDomainStore';

import ShowDialog from 'components/ShowDialog.vue';
import DomainSelect from 'components/DomainSelect.vue';
import UserList from 'components/UserList.vue';

const authStore = useAuthStore();
const domainStore = useDomainStore();
const pagination = ref({ sortBy: 'id', rowsPerPage: 0 });
const rows = ref([] as any[]);
const rowIds = new Set<string>();
const loading = ref(true);

const columns = [
  { name: 'id' },
  { name: 'name', required: true, label: 'Name', align: 'left', field: 'name', sortable: true },
  { name: 'url', align: 'center', label: 'Domain', field: 'url', sortable: true },
  { name: 'kintoneuser', label: 'User', field: 'kintoneuser', sortable: true },
  { name: 'kintonepwd' },
];
const userDomainTableFilter = ref();

const currentUserName = ref('');
const useOtherUser = ref(false);
const otherUserId = ref('');

let editId = ref(0);

const showAddDomainDg = ref(false);
const addDomainRef = ref();

const filterAddDgInitRows = (row: {domainActive: boolean, id: string}) => {
  return row.domainActive && !rowIds.has(row.id);
}

const clickAddDomain = () => {
  editId.value = 0;
  showAddDomainDg.value = true;
};

const addUserDomainFinished = (val: string) => {
  const selected = addDomainRef.value.selected;
  if (val == 'OK' && selected.length > 0) {
    api.post(`api/domain/${useOtherUser.value ? otherUserId.value : authStore.userId}?domainid=${selected[0].id}`)
      .then(async ({ data }) => {
        if (rows.value.length === 0 && data.data) {
          const domain = data.data;
          await authStore.setCurrentDomain({
            id: domain.id,
            kintoneUrl: domain.url,
            domainName: domain.name
          });
        }
        getDomain(useOtherUser.value ? otherUserId.value : undefined);
      });
  }
};

const showDeleteConfirm = ref(false);

const clickDeleteConfirm = (row: any) => {
  showDeleteConfirm.value = true;
  editId.value = row.id;
};

const deleteDomainFinished = async () => {
  await api.delete(`api/domain/${editId.value}/${useOtherUser.value ? otherUserId.value : authStore.userId}`).then(({ data }) => {
    if (data.msg == 'OK' && authStore.currentDomain.id === editId.value) {
      authStore.setCurrentDomain();
    }
    getDomain(useOtherUser.value ? otherUserId.value : undefined);
  })
  editId.value = 0;
};

const activeDomain = async (domain: any) => {
  if (useOtherUser.value) {
    // TODO
    return;
  }
  await authStore.setCurrentDomain({
    id: domain.id,
    kintoneUrl: domain.url,
    domainName: domain.name
  });
  getDomain();
};

let activeDomainId = ref(0);

const isActive = computed(() => (id: number) => {
  return id == activeDomainId.value;
});


const showSwitchUserDd = ref(false);
const switchUserRef = ref();
const switchUserFilter = ref('')

const clickSwitchUser = () => {
  showSwitchUserDd.value = true;
  useOtherUser.value = false;
};

const switchUserFinished = async (val: string) => {
  if (val == 'OK') {
    if (useOtherUser.value) {
      const user = switchUserRef.value.selected[0]
      currentUserName.value = user.email;
      otherUserId.value = user.id
      await getDomain(user.id)
    } else {
      currentUserName.value = authStore.userInfo.email
      await getDomain();
    }

  }
};

const getDomain = async (userId? : string) => {
  loading.value = true;
  rowIds.clear();
  if (useOtherUser.value) {
    // TODO
    return;
  }
  const resp = await api.get(`api/defaultdomain`);
  activeDomainId.value = resp?.data?.data?.id;
  const domainResult = userId ? await api.get(`api/domain?userId=${userId}`) : await api.get(`api/domain`);
  const domains = domainResult.data as any[];
  rows.value = domains.map((item) => {
    rowIds.add(item.id);
    return { id: item.id, name: item.name, url: item.url, kintoneuser: item.kintoneuser, kintonepwd: item.kintonepwd }
  });
  loading.value = false;
}

onMounted(async () => {
  currentUserName.value = authStore.userInfo.email
  await getDomain();
})

</script>
