<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { VbenButton } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

import { $t } from '@/locales';
import {
  Dropdown,
  Empty,
  Input,
  message,
  Modal,
  Pagination,
  Select,
} from 'antdv-next';

import {
  deleteApplicationApi,
  getMyApplicationListApi,
  getPartnersApi,
  type UserApi,
} from '#/api';

import ApplicationModal from './application-modal.vue';

const applicationMenu = ref<Array<{ label: string; value: any }>>([]);

const modalOpen = ref(false);
const modalMode = ref<'add' | 'edit'>('add');
const currentApplication = ref<any>(null);

const userStore = useUserStore();
const isLogin = computed(() => !!userStore.userInfo);

const applicationList = ref<UserApi.ApplicationModel[]>([]);
const loading = ref(false);

const searchParams = ref({
  applicationName: '',
  applicationId: '',
  cooperatePartner: '',
  activateNow: 'Yes',
  currentPage: 1,
  pageSize: 16,
});

const totalPage = ref(0);
const totalCount = ref(0);

function handleSearch() {
  searchParams.value.currentPage = 1;
  fetchApplicationList();
}

function handleAddNew() {
  modalMode.value = 'add';
  currentApplication.value = null;
  modalOpen.value = true;
}

function handleEdit(item: any) {
  modalMode.value = 'edit';
  currentApplication.value = item;
  modalOpen.value = true;
}

function handleModalSave() {
  modalOpen.value = false;
  fetchApplicationList();
}

function handleMenuClick({ key }: { key: string }, item: any) {
  if (key === 'Edit') {
    handleEdit(item);
  } else if (key === 'Remove') {
    Modal.confirm({
      title: 'Are you sure delete this task?',
      content: 'Some descriptions',
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      onOk() {
        deleteApplication(item);
      },
      onCancel() {},
    });
  }
}

function handleBack() {
  window.history.back();
}

async function fetchApplicationList() {
  if (!isLogin.value) {
    return;
  }

  try {
    loading.value = true;
    const result = await getMyApplicationListApi({
      currentPage: searchParams.value.currentPage,
      pageSize: searchParams.value.pageSize,
      orderByProperty: 'name',
      Ascending: true,
      filters: [
        {
          name: 'isEnable',
          value: searchParams.value.activateNow === 'Yes' ? '1' : '0',
        },
        {
          name: 'name',
          value: searchParams.value.applicationName,
        },
        {
          name: 'partnerInfoId',
          value: searchParams.value.cooperatePartner,
        },
        {
          name: 'code',
          value: searchParams.value.applicationId,
        },
      ],
    });
    if (result?.result?.model) {
      applicationList.value = result.result.model;
      totalPage.value = result.result.totalPages;
      totalCount.value = result.result.totalCount;
    }
  } catch (error) {
    console.error('获取应用列表失败:', error);
  } finally {
    loading.value = false;
  }
}

async function fetchPartners() {
  if (!isLogin.value) {
    return;
  }

  try {
    loading.value = true;
    const result = await getPartnersApi();
    if (result?.result) {
      applicationMenu.value = result.result.map(
        (item: { id: any; name: any }) => ({
          value: item.id,
          label: item.name,
        }),
      );
    }
  } catch (error) {
    console.error('获取合作伙伴失败:', error);
  } finally {
    loading.value = false;
  }
}

async function deleteApplication(item: any) {
  if (!isLogin.value) {
    return;
  }

  try {
    loading.value = true;
    const result = await deleteApplicationApi({
      id: item.id,
    });
    if (result?.result) {
      fetchApplicationList();
      message.success('删除成功！');
    }
  } catch (error) {
    console.error('删除应用失败:', error);
  } finally {
    loading.value = false;
  }
}

watch(
  () => isLogin.value,
  (newValue) => {
    if (newValue) {
      fetchApplicationList();
      fetchPartners();
    }
  },
  { immediate: true },
);
</script>

<template>
  <div class="p-5">
    <div class="mb-4 flex items-center justify-between">
      <div class="text-sm text-[#462424] text-gray-500">
        Dashboard / Application Management
      </div>
      <div
        class="cursor-pointer text-[16px] font-bold text-[#462424]"
        @click="handleBack"
      >
        Back
      </div>
    </div>

    <div class="mb-[21px] mt-[30px] text-[26px] font-bold text-[#462424]">
      {{ $t('homeModule.applicationManagement') }}
    </div>

    <div class="mb-4 flex flex-wrap items-center gap-4">
      <div class="flex flex-col gap-1">
        <label class="text-[11px] text-[#000]">Application Name:</label>
        <Input
          v-model:value="searchParams.applicationName"
          class="h-[42px] w-[147px] rounded-[11px] border-[#707070]"
          placeholder=""
        />
      </div>
      <div class="flex flex-col gap-1">
        <label class="text-[11px] text-[#000]">Application ID:</label>
        <Input
          v-model:value="searchParams.applicationId"
          class="h-[42px] w-[89px] rounded-[11px] border-[#707070]"
          placeholder=""
        />
      </div>
      <div class="flex flex-col gap-1">
        <label class="text-[11px] text-[#000]">Cooperate Partner:</label>
        <Select
          v-model:value="searchParams.cooperatePartner"
          :options="applicationMenu"
          class="h-[42px] w-[168px] rounded-[11px] border-[#707070] text-[12px]"
          placeholder="Choose Coope Partner"
        />
      </div>
      <div class="ml-[86px] flex flex-col gap-1">
        <label class="text-[11px] text-[#000]">Activate Now:</label>
        <div class="flex h-[42px] items-center gap-2">
          <label
            class="flex cursor-pointer items-center gap-2 text-sm"
            @click="searchParams.activateNow = 'Yes'"
          >
            <div
              class="flex h-[20px] w-[20px] items-center justify-center rounded-[5px] border-[1px] border-[#707070]"
            >
              <div
                v-if="searchParams.activateNow === 'Yes'"
                class="h-[14px] w-[14px] flex-shrink-0 rounded-[3px] bg-[#462424]"
              ></div>
            </div>
            Yes
          </label>
          <label
            class="flex cursor-pointer items-center gap-2 text-sm"
            @click="searchParams.activateNow = 'No'"
          >
            <div
              class="flex h-[20px] w-[20px] items-center justify-center rounded-[5px] border-[1px] border-[#707070]"
            >
              <div
                v-if="searchParams.activateNow === 'No'"
                class="h-[14px] w-[14px] flex-shrink-0 rounded-[3px] bg-[#462424]"
              ></div>
            </div>
            No
          </label>
        </div>
      </div>
      <div class="ml-auto flex items-center gap-2">
        <VbenButton
          class="flex h-[42px] w-[102px] items-center gap-[7px] rounded-[25px] border-[#000] bg-transparent text-sm font-medium"
          variant="outline"
          @click="handleSearch"
        >
          <img
            alt=""
            class="h-[21.5px] w-[21.5px] cursor-pointer"
            src="@/assets/image/search.png"
          />
          Search
        </VbenButton>
        <VbenButton
          class="flex h-[42px] w-[133px] items-center gap-[7px] rounded-[25px] text-sm font-medium text-white"
          style="background: linear-gradient(to right, #8b0046, #460023)"
          @click="handleAddNew"
        >
          <img
            alt=""
            class="h-[21.5px] w-[21.5px] cursor-pointer"
            src="@/assets/image/new.png"
          />
          Add New
        </VbenButton>
      </div>
    </div>

    <div v-if="loading" class="py-8 text-center">加载中...</div>
    <div
      v-else-if="applicationList.length === 0"
      class="mt-[100px] py-8 text-center text-gray-500"
    >
      <Empty />
    </div>
    <div v-else class="mb-[76px] mt-[38px] flex flex-wrap gap-[18px]">
      <div
        v-for="item in applicationList"
        :key="item.id"
        class="flex h-[78px] cursor-pointer items-center gap-[25px] rounded-[11px] bg-[#fff] px-[20px] shadow-md"
      >
        <img
          :src="`/File/Download?fileId=${item.imgPhotoFileId}`"
          alt=""
          class="h-[48px] w-auto object-contain"
        />
        <Dropdown
          :menu="{
            items: [
              { key: 'Edit', label: 'Edit' },
              { key: 'Remove', label: 'Remove' },
            ],
          }"
          placement="bottom"
          @menu-click="(info: any) => handleMenuClick(info, item)"
        >
          <div class="flex cursor-pointer items-center gap-2">
            <img
              alt=""
              class="h-[19px] w-[19px] cursor-pointer"
              src="@/assets/image/more-tow.png"
            />
          </div>
        </Dropdown>
      </div>
    </div>

    <div v-if="totalCount > 16" class="list-pagination">
      <Pagination
        v-model:current="searchParams.currentPage"
        :show-size-changer="false"
        :total="totalCount"
      />
    </div>

    <ApplicationModal
      v-model:open="modalOpen"
      :application-data="currentApplication"
      :mode="modalMode"
      @save="handleModalSave"
    />
  </div>
</template>

<style lang="scss">
.ant-pagination-item-active {
  color: #7a003d !important;
  background-color: #f8f2f5 !important;
  border-color: transparent !important;

  a {
    color: #c48da8 !important;
  }
}
</style>
