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

import { useUserStore } from '@vben/stores';

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

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

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

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

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: 12,
});

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

const route = useRoute();
const type = route.query.type as string;

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: $t('applicationManagement.deleteConfirm'),
      content: $t('applicationManagement.deleteDescription'),
      okText: $t('btn.yes'),
      okType: 'danger',
      cancelText: $t('btn.no'),
      onOk() {
        deleteApplication(item);
      },
      onCancel() {},
    });
  }
}

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

function handleClear() {
  searchParams.value.applicationName = '';
  searchParams.value.applicationId = '';
  searchParams.value.cooperatePartner = '';
  searchParams.value.activateNow = 'Yes';
  handleSearch();
}

function handlePageChange(page: number) {
  searchParams.value.currentPage = page;
  fetchApplicationList();
}

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,
        },
        {
          name: 'type',
          value: type === '1' ? 'application' : 'product',
        },
      ],
    });
    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 fetchMenuPermissionButtons() {
  if (!isLogin.value) {
    return;
  }

  try {
    const result = await getMenuPermissionButtonsApi({
      menu_code: 'Sys_Menu_Project',
    });
    if (result?.result) {
      permissionButtons.value = result.result;
    }
  } catch (error) {
    console.error('获取菜单权限按钮失败:', error);
  }
}

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($t('applicationManagement.deleteSuccess'));
    }
  } catch (error) {
    console.error('删除应用失败:', error);
  } finally {
    loading.value = false;
  }
}

watch(
  () => isLogin.value,
  (newValue) => {
    if (newValue) {
      fetchApplicationList();
      fetchPartners();
      fetchMenuPermissionButtons();
    }
  },
  { 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">
        {{
          type === '1'
            ? $t('applicationManagement.breadcrumb')
            : $t('productManagement.breadcrumb')
        }}
      </div>
      <div
        class="flex cursor-pointer items-center gap-[9px] text-[16px] font-bold text-[#462424]"
        @click="handleBack"
      >
        <div
          class="global-color flex h-[22px] w-[22px] items-center justify-center rounded-full"
        >
          <img
            alt=""
            class="h-[11px] w-[10px]"
            src="@/assets/image/the-left.png"
          />
        </div>
        {{ $t('btn.back') }}
      </div>
    </div>

    <div class="mb-[21px] mt-[30px] text-[26px] font-bold text-[#462424]">
      {{
        type === '1'
          ? $t('homeModule.applicationManagement')
          : $t('productManagement.title')
      }}
    </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]">{{
          $t('applicationManagement.applicationName')
        }}</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]">{{
          $t('applicationManagement.applicationId')
        }}</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]">{{
          $t('applicationManagement.cooperatePartner')
        }}</label>
        <Select
          v-model:value="searchParams.cooperatePartner"
          :options="applicationMenu"
          :placeholder="$t('applicationManagement.chooseCooperatePartner')"
          class="h-[42px] w-[168px] rounded-[11px] border-[#707070] text-[12px]"
        />
      </div>
      <div class="ml-[86px] flex flex-col gap-1">
        <label class="text-[11px] text-[#000]">{{
          $t('applicationManagement.activateNow')
        }}</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>
            {{ $t('btn.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>
            {{ $t('btn.no') }}
          </label>
        </div>
      </div>
      <div class="ml-auto flex items-center gap-2">
        <Button class="h-[42px]" @click="handleSearch">
          <svg
            class="h-[21.5px] w-[21.5px] cursor-pointer"
            fill="none"
            viewBox="0 0 24 24"
            xmlns="http://www.w3.org/2000/svg"
          >
            <circle
              cx="11"
              cy="11"
              r="8"
              stroke="currentColor"
              stroke-width="2"
            />
            <path
              d="M21 21L16.65 16.65"
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
            />
          </svg>
          {{ $t('btn.search') }}
        </Button>
        <Button class="h-[42px]" @click="handleClear">
          <svg
            class="h-[21.5px] w-[21.5px] cursor-pointer"
            fill="none"
            viewBox="0 0 24 24"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M3 6H5"
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
            />
            <path
              d="M19 6V20C19 21.1046 18.1046 22 17 22H7C5.89543 22 5 21.1046 5 20V6M8 6V4C8 3.79086 8.79086 3 10 3H14C15.2091 3 16 3.79086 16 6V8M10 11V17M14 11V17"
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
            />
          </svg>
          {{ $t('btn.reset') }}
        </Button>
        <Button
          v-if="permissionButtons.includes('add')"
          class="h-[42px]"
          type="primary"
          @click="handleAddNew"
        >
          <img
            alt=""
            class="h-[21.5px] w-[21.5px] cursor-pointer"
            src="@/assets/image/new.png"
          />
          {{ $t('btn.addNew') }}
        </Button>
      </div>
    </div>

    <div v-if="loading" class="py-8 text-center">
      {{ $t('applicationManagement.loading') }}
    </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 rounded-[11px] bg-[#fff] px-[20px] shadow-md"
      >
        <img
          :src="`/File/Download?fileId=${item.imgLogoFileId}`"
          alt=""
          class="h-[48px] w-auto object-contain"
        />
        <span
          class="ml-[10px] font-['Open_Sans'] text-[13px] font-medium text-[#000]"
        >
          {{ item.name }}
        </span>
        <Dropdown
          v-if="
            permissionButtons.includes('edit') ||
            permissionButtons.includes('del')
          "
          :menu="{
            items: [
              ...(permissionButtons.includes('edit')
                ? [{ key: 'Edit', label: $t('applicationManagement.edit') }]
                : []),
              ...(permissionButtons.includes('del')
                ? [{ key: 'Remove', label: $t('applicationManagement.remove') }]
                : []),
            ],
          }"
          placement="bottom"
          @menu-click="(info: any) => handleMenuClick(info, item)"
        >
          <div class="ml-[25px] 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 class="list-pagination">
      <Pagination
        v-model:current="searchParams.currentPage"
        :hide-on-single-page="true"
        :page-size="12"
        :show-size-changer="false"
        :total="totalCount"
        @change="handlePageChange"
      />
    </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>
