<script setup lang="ts">
import { fetchSalePublishApplication } from '@/apis/agent-application'
import { fetchGetMallCategoryList } from '@/apis/application-square'
import { PersonalAppConfigState } from '@/store/types/personal-app-config'
import { Close, Help, Notes, CheckSmall } from '@icon-park/vue-next'
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ApplicationMallInfo } from './types'

interface MallCategory {
  id: number
  categoryName: string
}

const isShowSaleApplicationsConfigurationModal = defineModel<boolean>()

const props = defineProps<{
  saleApplicationsData: PersonalAppConfigState
  applicationMallInfo?: ApplicationMallInfo
}>()
const emit = defineEmits<{
  update: [value: string]
  'trigger-get-application-mall-info': []
}>()

const { t } = useI18n()
const checkedClassifyValue = ref<number | null>(props.applicationMallInfo?.categoryId ?? 0)

const isCopy = ref(props.saleApplicationsData.isCopy === 'Y')
const isClassifyError = ref(false)
const applicationsClassify = ref<MallCategory[]>([])
const agentPublishId = ref(props.saleApplicationsData.agentPublishId)

;(function () {
  handleGetMallCategoryList()
})()

watch(
  () => checkedClassifyValue.value,
  () => {
    if (checkedClassifyValue.value !== null) isClassifyError.value = false
  },
)

watch(
  () => props.saleApplicationsData.agentPublishId,
  (newValue) => {
    agentPublishId.value = newValue
  },
)

function handleApplicationsSaleSettingModalClose() {
  isShowSaleApplicationsConfigurationModal.value = false
  checkedClassifyValue.value = null
  isCopy.value = false
}

function handleApplicationReleaseBtn() {
  if (!checkedClassifyValue.value) {
    isClassifyError.value = true
    return
  }

  if (props.applicationMallInfo?.agentPublishId) {
    agentPublishId.value = props.applicationMallInfo.agentPublishId
  }

  const payload = {
    agentPublishId: agentPublishId.value,
    categoryId: checkedClassifyValue.value,
    isCopy: isCopy.value ? 'Y' : 'N',
    isSale: 'Y',
  }

  fetchSalePublishApplication(payload)
    .then(() => {
      emit('update', 'Y')
      handleApplicationsSaleSettingModalClose()
      window.$message.success(
        t(
          'personal_space_module.agent_module.agent_setting_module.agent_publish_module.successfully_configured_published',
        ),
      )
      emit('trigger-get-application-mall-info')
      isClassifyError.value = false
    })
    .catch(() => {
      window.$message.success(t('common_module.listing_failed'))
    })
}

function handleIsCopySwitchUpdateValue(value: boolean) {
  isCopy.value = value
}

function handleGetMallCategoryList() {
  fetchGetMallCategoryList().then((res) => {
    if (res.code !== 0) return
    applicationsClassify.value = res.data as MallCategory[]
  })
}

function handleModalOpenAfter() {
  if (props.saleApplicationsData.isCopy) isCopy.value = props.saleApplicationsData.isCopy === 'Y'
  if (props.saleApplicationsData.isSale === 'Y') {
    checkedClassifyValue.value = props.applicationMallInfo!.categoryId
  } else {
    checkedClassifyValue.value = 0
  }
}
</script>

<template>
  <n-modal
    v-model:show="isShowSaleApplicationsConfigurationModal"
    :on-after-enter="handleModalOpenAfter"
    class="h-auto max-h-[720px]"
    :mask-closable="false"
  >
    <div class="flex flex-col items-center justify-center">
      <div class="max-h-[720px] w-[720px] rounded-lg bg-white p-[24px]">
        <div class="mb-[24px] flex items-center justify-between text-[20px] font-medium">
          <div class="flex items-center">
            <span class=" ">{{
              t(
                'personal_space_module.agent_module.agent_setting_module.agent_sale_module.application_square_release_setting',
              )
            }}</span>
            <Notes theme="outline" size="17" fill="#333" class="ml-[8px]" />
          </div>

          <Close
            theme="outline"
            size="12"
            fill="#00000073"
            class="cursor-pointer"
            @click="handleApplicationsSaleSettingModalClose"
          />
        </div>

        <div class="items-center justify-center rounded-[4px]">
          <div class="mb-[16px] flex items-center text-[14px] text-[#151B26]">
            <div class="bg-theme-color mr-[8px] h-[20px] w-[20px] rounded-2xl text-center text-[#fff]">1</div>
            <div class="text-[16px]">
              {{
                t(
                  'personal_space_module.agent_module.agent_setting_module.agent_sale_module.application_classification',
                )
              }}
            </div>
            <div class="text-[#f33e3e]">*</div>
          </div>
          <div class="flex flex-wrap">
            <button
              v-for="classify in applicationsClassify"
              :key="classify.id"
              :class="['classify-radio-button', { active: checkedClassifyValue === classify.id }]"
              class="relative mb-[8px] mr-[8px] h-[26px] cursor-pointer rounded-[6px] border-[1px] border-[#edeef7] bg-[#edeef7] px-[8px] text-[12px]"
              @click="checkedClassifyValue = classify.id"
            >
              <div
                v-show="checkedClassifyValue === classify.id"
                class="bg-theme-color absolute left-0 top-[-1px] h-[14px] w-[14px] rounded-[3px]"
                style="clip-path: polygon(0 0, 100% 0, 0 100%)"
              >
                <CheckSmall theme="outline" size="10" fill="#fff" />
              </div>
              {{ classify.categoryName }}
            </button>
          </div>
          <div class="mb-[10px] h-[16px] text-red-500">
            <div v-show="isClassifyError">
              {{
                t(
                  'personal_space_module.agent_module.agent_setting_module.agent_sale_module.application_classification_null',
                )
              }}
            </div>
          </div>
          <div class="mb-[12px] flex items-center">
            <div class="bg-theme-color mr-[8px] h-[20px] w-[20px] rounded-2xl text-center text-[#fff]">2</div>
            {{ t('personal_space_module.agent_module.agent_setting_module.agent_sale_module.is_copy') }}
            <n-popover trigger="hover">
              <template #trigger>
                <Help theme="outline" size="16" fill="#333" class="ml-[5px] cursor-pointer" />
              </template>
              <div class="w-[250px]">
                {{ t('personal_space_module.agent_module.agent_setting_module.agent_sale_module.copy_tip') }}
              </div>
            </n-popover>
          </div>
          <n-switch v-model:value="isCopy" size="small" @update:value="handleIsCopySwitchUpdateValue"
            ><template #checked
              >{{ t('personal_space_module.agent_module.agent_setting_module.agent_sale_module.yes') }}
            </template>
            <template #unchecked>
              {{ t('personal_space_module.agent_module.agent_setting_module.agent_sale_module.no') }}
            </template></n-switch
          >
        </div>
        <div>
          <div class="flex max-h-[490px] justify-center overflow-y-hidden bg-[#f3f4fb]"></div>

          <div class="mt-[24px] flex justify-end">
            <button
              class="hover:text-theme-color hover:border-theme-color !mr-[12px] box-content !h-[38px] !w-[74px] cursor-pointer rounded-[6px] border-[1px] border-solid border-[#dde3f0] px-[10px] outline-none transition-all duration-300 hover:border-[theme-color]"
              @click="handleApplicationsSaleSettingModalClose"
            >
              {{ t('common_module.cancel_btn_text') }}
            </button>
            <button
              class="bg-theme-color !box-content !h-[38px] cursor-pointer rounded-[6px] border-[1px] border-solid border-[#dde3f0] bg-[te] px-[10px] text-[#ffffff] transition-all duration-300 hover:bg-[#528EFF]"
              @click="handleApplicationReleaseBtn()"
            >
              {{ t('personal_space_module.agent_module.agent_setting_module.agent_sale_module.confirm_release') }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </n-modal>
</template>

<style lang="scss" scoped>
.classify-radio-button {
  &.active {
    background-color: #eef3fe;
    border: 1px solid #000dff;
  }

  &:focus {
    outline: none;
  }
}
</style>
