<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { Computer, PreviewOpen, AllApplication, SettingOne } from '@icon-park/vue-next'
import useTableScrollY from '@/composables/useTableScrollY'
import { copyToClip } from '@/utils/copy'
import { formatDateTime } from '@/utils/date-formatter'
import { ref, watch } from 'vue'
import { PersonalAppConfigState } from '@/store/types/personal-app-config'
import SaleApplicationsConfigurationModal from '@/views/personal-space/personal-app/sale-applications-configuration-modal.vue'
import {
  fetchGetApplicationInfo,
  fetchGetApplicationMallInfo,
  fetchRemoveSalePublishApplication,
} from '@/apis/agent-application'
import { defaultPersonalAppConfigState, usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { ApplicationMallInfo } from '../../personal-app/types'

const { t } = useI18n()

const { pageContentWrapRef, tableContentY } = useTableScrollY()

const router = useRouter()

const isShowSaleApplicationsConfigurationModal = ref(false)
const saleApplicationsInfo = ref<PersonalAppConfigState>(defaultPersonalAppConfigState())
const personalAppConfigStore = usePersonalAppConfigStore()

const applicationMallInfo = ref<ApplicationMallInfo>({
  agentId: '',
  agentPublishId: 1,
  categoryId: 1,
  isCopy: '',
  isSale: '',
  launchTime: '',
})

watch(
  () => saleApplicationsInfo.value,
  (newValue) => {
    saleApplicationsInfo.value = newValue
  },
)

watch(
  () => personalAppConfigStore.baseInfo,
  (newValue) => {
    personalAppConfigStore.baseInfo = newValue
    if (personalAppConfigStore.baseInfo.agentId !== '') {
      handleGetApplicationMallInfo()
      handleGetApplicationInfo()
    }
  },
)
;(function () {
  if (personalAppConfigStore.baseInfo.agentId !== '') {
    handleGetApplicationMallInfo()
    handleGetApplicationInfo()
  }
})()

function handleClickChannelPublishTableAction(actionType: string) {
  switch (actionType) {
    case 'accessPage':
      handleAccessPage()
      break
    case 'copyLink':
      handleCopyShareLink()
      break
    case 'configuration':
      handleConfigurationApplication(saleApplicationsInfo.value)
      break
    case 'modifySetting':
      handleConfigurationApplication(saleApplicationsInfo.value, true)
      break
    case 'unSaleApplication':
      handleUnSaleApplication()
      break
  }
}

function handleAccessPage() {
  router.push({ name: 'ShareWebApplication', params: { agentId: router.currentRoute.value.params.agentId } })
}

function handleCopyShareLink() {
  const channelUrl = `${window.location.origin}/fe/share/web_source/${router.currentRoute.value.params.agentId}`
  copyToClip(channelUrl)
  window.$message.success(
    t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.copy_share_url_success_message'),
  )
}

function handleConfigurationApplication(saleApplications: PersonalAppConfigState, isSale = false) {
  if (isSale) {
    saleApplicationsInfo.value.isCopy = applicationMallInfo.value.isCopy
    saleApplicationsInfo.value.isSale = 'Y'
    saleApplicationsInfo.value.agentPublishId = saleApplications.agentPublishId
  } else {
    saleApplicationsInfo.value.isCopy = 'N'
    saleApplicationsInfo.value.isSale = 'N'
    saleApplicationsInfo.value.agentPublishId = saleApplications.agentPublishId
  }
  isShowSaleApplicationsConfigurationModal.value = true
}

function handleUnSaleApplication() {
  window.$message
    .ctWarning(
      t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.removal_prompt_content'),
      t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.removal_prompt_title'),
    )
    .then(() => {
      fetchRemoveSalePublishApplication(applicationMallInfo.value.agentPublishId)
        .then(() => {
          applicationMallInfo.value.isSale = 'N'
          window.$message.success(t('common_module.removal_successfully'))
        })
        .catch(() => {
          window.$message.error(t('common_module.removal_failed'))
        })
    })
}

function handleGetApplicationMallInfo() {
  fetchGetApplicationMallInfo(personalAppConfigStore.baseInfo.agentId).then((res) => {
    applicationMallInfo.value = res.data as ApplicationMallInfo
    saleApplicationsInfo.value.agentPublishId = applicationMallInfo.value.agentPublishId
    saleApplicationsInfo.value.isCopy = applicationMallInfo.value.isCopy
  })
}

function handleGetApplicationInfo() {
  fetchGetApplicationInfo(personalAppConfigStore.baseInfo.agentId).then((res) => {
    saleApplicationsInfo.value = res.data as PersonalAppConfigState
  })
}

function handleToApplicationSquare() {
  router.push({ name: 'ApplicationsSquare' })
}
</script>

<template>
  <div ref="pageContentWrapRef" class="h-full w-full overflow-hidden p-5">
    <table class="w-full text-left" :max-height="tableContentY">
      <thead>
        <tr>
          <th class="w-[45%] border-[1px] border-[#efeff5] bg-[#f7f7fa] p-[12px] text-[14px] font-medium">
            <span>{{ t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.channel') }}</span>
          </th>
          <th class="w-[17%] border-[1px] border-[#efeff5] bg-[#f7f7fa] p-[12px] text-[14px] font-medium">
            <span>{{ t('common_module.status') }}</span>
          </th>
          <th
            class="w-[38%] rounded-tr-[5px] border-[1px] border-[#efeff5] bg-[#f7f7fa] p-[12px] text-[14px] font-medium"
          >
            <span>{{ t('common_module.data_table_module.action') }}</span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="border-[1px] border-[#efeff5]">
            <div class="flex items-center justify-start p-[12px]">
              <Computer
                theme="multi-color"
                size="24"
                :fill="['#000dff', '#000dff', '#FFF', '#43CCF8']"
                :stroke-width="3"
              />
              <div class="ml-[12px]">
                <div>
                  {{
                    t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.web_channel_name')
                  }}
                </div>
                <div class="text-[#84868c]">
                  {{
                    t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.web_channel_desc')
                  }}
                </div>
              </div>
            </div>
          </td>
          <td class="border-[1px] border-[#efeff5] p-[12px]">
            <div class="flex flex-col items-start justify-center">
              <div class="mb-[4px] rounded-[4px] bg-[#34a853] px-[14px] py-[3px] text-[#fff]">
                {{ t('common_module.published') }}
              </div>
              <div class="text-[#84868c]">
                {{ formatDateTime(saleApplicationsInfo.baseInfo.publishTime) + t('common_module.publish') }}
              </div>
            </div>
          </td>
          <td class="border-[1px] border-[#efeff5] p-[12px]">
            <div class="flex">
              <div
                class="flex cursor-pointer items-center justify-start rounded-[5px] border-[1px] border-[#000DFF] bg-[#f7f7f9] px-[12px] py-[4px] text-[14px] text-[#000DFF] hover:opacity-80"
                @click="handleClickChannelPublishTableAction('accessPage')"
              >
                <PreviewOpen theme="outline" size="16" fill="#000DFF" :stroke-width="4" class="mr-[6px]" />
                <span>{{
                  t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.access_page')
                }}</span>
              </div>
              <div
                class="hover:text-theme-color hover:border-theme-color ml-[16px] flex cursor-pointer items-center justify-start rounded-md border bg-[#f7f7f9] px-[12px] py-[4px] text-[14px]"
                @click="handleClickChannelPublishTableAction('copyLink')"
              >
                <CustomIcon icon="pepicons-pop:share-android-circle" class="mr-[6px]" />

                <span>{{
                  t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.share_link')
                }}</span>
              </div>
            </div>
          </td>
        </tr>
        <tr>
          <td class="border-[1px] border-[#efeff5]">
            <div class="flex items-center justify-start p-[12px]">
              <AllApplication theme="filled" size="24" fill="#000dff" :stroke-width="3" />
              <div class="ml-[12px]">
                <div class="flex">
                  <span
                    class="hover:text-theme-color flex cursor-pointer items-center gap-[4px]"
                    @click="handleToApplicationSquare"
                  >
                    {{ t('router_title_module.application_square') }}
                    <CustomIcon icon="ep:top-right" />
                  </span>
                </div>

                <div class="text-[#84868c]">
                  {{
                    t(
                      'personal_space_module.agent_module.agent_setting_module.agent_publish_module.application_square_desc',
                    )
                  }}
                </div>
              </div>
            </div>
          </td>
          <td class="border-[1px] border-[#efeff5] p-[12px]">
            <div
              v-show="applicationMallInfo?.isSale === null || applicationMallInfo?.isSale === 'N'"
              class="flex flex-col items-start justify-center"
            >
              <div class="rounded-[4px] bg-[#BBB] px-[14px] py-[3px] text-[#fff]">
                {{
                  t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.not_configured_btn')
                }}
              </div>
            </div>
            <div v-show="applicationMallInfo?.isSale === 'Y'" class="flex flex-col items-start justify-center">
              <div class="mb-[4px] rounded-[4px] bg-[#34a853] px-[14px] py-[3px] text-[#fff]">
                {{ t('common_module.published') }}
              </div>
              <div class="text-[#84868c]">
                {{
                  applicationMallInfo?.launchTime
                    ? formatDateTime(applicationMallInfo.launchTime) + t('common_module.publish')
                    : ''
                }}
              </div>
            </div>
          </td>
          <td class="border-[1px] border-[#efeff5] p-[12px]">
            <div v-show="applicationMallInfo?.isSale === null || applicationMallInfo?.isSale === 'N'" class="flex">
              <div
                class="flex cursor-pointer items-center justify-start rounded-[5px] border-[1px] border-[#000DFF] bg-[#f7f7f9] px-[12px] py-[4px] text-[14px] text-[#000DFF] hover:opacity-80"
                @click="handleClickChannelPublishTableAction('configuration')"
              >
                <SettingOne theme="outline" size="16" fill="#000dff" :stroke-width="3" class="mr-[3px]" />
                <span>
                  {{ t('common_module.config') }}
                </span>
              </div>
            </div>
            <div v-show="applicationMallInfo?.isSale === 'Y'" class="flex">
              <!-- <div
                class="flex cursor-pointer items-center justify-start rounded-[5px] border-[1px] border-[#000DFF] bg-[#f7f7f9] px-[12px] py-[4px] text-[14px] text-[#000DFF] hover:opacity-80"
                @click="handleClickChannelPublishTableAction('accessPage')"
              >
                <PreviewOpen theme="outline" size="16" fill="#000DFF" :stroke-width="4" class="mr-[6px]" />
                <span>{{
                  t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.access_page')
                }}</span>
              </div>
              <div
                class="hover:text-theme-color hover:border-theme-color ml-[16px] flex cursor-pointer items-center justify-start rounded-md border bg-[#f7f7f9] px-[12px] py-[4px] text-[14px]"
                @click="handleClickChannelPublishTableAction('copyLink')"
              >
                <CustomIcon icon="pepicons-pop:share-android-circle" class="mr-[6px]" />

                <span>{{
                  t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.share_link')
                }}</span>
              </div> -->
              <div
                class="hover:text-theme-color hover:border-theme-color flex cursor-pointer items-center justify-start rounded-md border bg-[#f7f7f9] px-[12px] py-[4px] text-[14px]"
                @click="handleClickChannelPublishTableAction('modifySetting')"
              >
                <CustomIcon icon="ep:edit" class="mr-[6px]" />

                <span>
                  {{
                    t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.modify_setting_btn')
                  }}
                </span>
              </div>
              <div
                class="hover:text-theme-color hover:border-theme-color ml-[16px] flex cursor-pointer items-center justify-start rounded-md border bg-[#f7f7f9] px-[12px] py-[4px] text-[14px]"
                @click="handleClickChannelPublishTableAction('unSaleApplication')"
              >
                <CustomIcon icon="nonicons:not-found-16" class="mr-[6px]" />

                <span> {{ t('common_module.data_table_module.remove_applications') }} </span>
              </div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>

    <SaleApplicationsConfigurationModal
      v-model="isShowSaleApplicationsConfigurationModal"
      :sale-applications-data="saleApplicationsInfo"
      :application-mall-info="applicationMallInfo"
      @update="(newValue: string) => (applicationMallInfo.isSale = newValue)"
      @trigger-get-application-mall-info="handleGetApplicationMallInfo"
    />
  </div>
</template>
