<template>
  <div class="views" id="ib_index">
    <el-dialog
      v-model:visible="dialogLink"
      center
      :modal-append-to-body="false"
      :title="$t('Ib.Index.CreateLink')"
      class="dialog_header_w dialogLink"
    >
      <div class="dia-content">
        <div class="content" style="font-size: 14px; text-align: left">
          <template v-if="type == 1">
            <div class="label forms">{{ $t('Label.Name') }} ：{{ form.name }}</div>
            <div class="label forms">{{ $t('Label.UserNames') }} ：{{ form.username }}</div>
            <div class="label forms">{{ $t('Label.Email') }} ：{{ form.email }}</div>
          </template>
          <template v-if="type == 2">
            <div class="label forms">
              {{ $t('Apply_info.UserInfo.CID') }} ：{{ form.cId || '--' }}
            </div>
            <div class="label forms">
              {{ $t('Label.UserNames') }} ：<span v-if="form.firstName">{{
                form.firstName + ' '
              }}</span>
              <span v-if="form.middle">{{ form.middle + ' ' }}</span>
              <span v-if="form.lastName">{{ form.lastName }}</span>
              <span v-if="!form.firstName && !form.lastName && !form.middle">{{ '--' }}</span>
            </div>
            <div class="label forms">{{ $t('Label.Email') }} ：{{ form.email }}</div>
          </template>

          <template>
            <div class="label">{{ $t('Ib.Index.Spread5') }} ：</div>
            <el-select
              v-model="excludeShowLoginTypes"
              multiple
              size="mini"
              :placeholder="$t('Placeholder.Choose')"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in excludeList"
                :label="item.label"
                :value="item.value"
                :key="index"
              ></el-option>
            </el-select>
            <div class="label">{{ $t('Ib.Index.Spread4') }} ：</div>
            <el-select
              v-model="selectedSpreadId"
              size="mini"
              :placeholder="$t('Placeholder.Choose')"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in spreadList"
                :label="
                  $t('Ib.Index.Commission') +
                  ':' +
                  item.comPoint +
                  '-' +
                  $t('Ib.Index.Hide') +
                  ':' +
                  item.hide
                "
                :value="item.id"
                :key="index"
              ></el-option>
            </el-select>
            <div class="label">{{ $t('Ib.Index.IbInvalid') }}</div>
            <el-select
              v-model="ibInvalid"
              size="mini"
              :placeholder="$t('Placeholder.Choose')"
              style="width: 100%"
            >
              <el-option :label="$t('ibTemplate.Allow')" value="B0"></el-option>
              <el-option :label="$t('ibTemplate.NotAllow')" value="B1"></el-option>
            </el-select>
            <div>
              <span style="line-height: 1.5">{{ $t('ApplicationDialog.item1') }}</span>
            </div>
            <div>
              <span style="line-height: 1.5">{{ $t('ApplicationDialog.item2') }}</span>
              <template v-if="type == 1">
                <a
                  :href="`pdf/pdf6/all/Account Type Allocation Table-${lang}.pdf`"
                  target="_blank"
                  >{{ $t('ApplicationDialog.item3') }}</a
                >
              </template>
              <template v-else>
                <a
                  :href="`pdf/pdf6/all/Account Type Allocation Table-${lang}.pdf`"
                  target="_blank"
                  v-if="country == 'NG' || country == 'TH' || country == 'LA' || isAfterJuly7()"
                  >{{ $t('ApplicationDialog.item3') }}</a
                >
                <a
                  :href="`pdf/pdf6/no/Account Type Allocation Table-${lang}.pdf`"
                  target="_blank"
                  v-else
                  >{{ $t('ApplicationDialog.item3') }}</a
                >
              </template>
            </div>
            <div class="btn">
              <span class="crm-cursor" @click="CreateLink">{{ $t('Ib.Index.CreateLink') }}</span>
            </div>
            <div class="link qrCode" v-if="link">
              <QrCode ref="qrCode" :text="link" :width="200" :height="200"></QrCode>
              <div class="btn">
                <span class="crm-cursor" style="height: 16px" @click="downloadQrCode">{{
                  $t('ibTemplate.item9')
                }}</span>
              </div>
            </div>
            <div class="link">
              <el-input
                readonly
                size="mini"
                v-model.trim="link"
                placeholder=""
                id="custom_link"
              ></el-input>
              <div class="btn">
                <span class="crm-cursor" @click="CopyShareLink('custom_link')">{{
                  $t('Ib.Index.Copy')
                }}</span>
              </div>
            </div>

            <div class="link" style="align-items: center">
              <div style="margin-right: 10px">{{ $t('ibTemplate.item2') }}</div>
              <el-input
                readonly
                size="mini"
                v-model.trim="getInfoId"
                placeholder=""
                id="custom_link_tj"
              ></el-input>
              <div class="btn">
                <span class="crm-cursor" @click="CopyShareLink('custom_link_tj')">{{
                  $t('Ib.Index.Copy')
                }}</span>
              </div>
            </div>
          </template>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import QrCode from '@/components/QRCode/index.vue'
  import Service from '@/service/enter'
  import Config from '@/config/index'
  import { ref, computed, watch, nextTick, inject } from 'vue'
  import { useI18n } from 'vue-i18n'

  const { t } = useI18n()
  const pigeon = inject('pigeon')
  const Session = inject('session')
  const { Code, Host80 } = Config

  // 响应式数据
  const dialogLink = ref(false)
  const linkActivity = ref('')
  const hide = ref(0)
  const country = ref('')
  const getInfoId = ref('')
  const commission = ref(0)
  const excludeList = ref([])
  const spreadList = ref([])
  const excludeShowLoginTypes = ref([])
  const selectedSpreadId = ref('')
  const loginTypes = ref('')
  const ibInvalid = ref('B0')
  const link = ref('')
  const form = ref({})
  const type = ref(0)
  const qrCode = ref(null)

  // 计算属性
  const lang = computed(() => Session.Get('lang'))
  const user = computed(() => JSON.parse(Session.Get('user', true)))

  // 方法
  const isAfterJuly7 = () => {
    const currentDate = new Date()
    const july7 = new Date(currentDate.getFullYear(), 6, 7)
    return currentDate >= july7
  }

  const LinkActivity1 = async ({ form: formData, type: typeData }) => {
    console.log(typeData)
    form.value = formData
    type.value = typeData
    switch (typeData) {
      case 0:
        getInfoId.value = JSON.parse(Session.Get('user', true)).id
        break
      case 1:
        getInfoId.value = formData.id
        break
      case 2:
        getInfoId.value = formData.ibId
        break
    }
    country.value = typeData == 0 ? JSON.parse(Session.Get('user', true)).country : formData.country
    switch (typeData) {
      case 1:
        excludeList.value = [
          { label: t('AccountType.SeniorAccount'), value: '2' },
          { label: t('AccountType.StandardAccount'), value: '7' },
          { label: t('AccountType.CentAccount'), value: '8' },
        ]
        break
      default:
        if (
          country.value == 'NG' ||
          country.value == 'TH' ||
          country.value == 'LA' ||
          isAfterJuly7()
        ) {
          excludeList.value = [
            { label: t('AccountType.SeniorAccount'), value: '2' },
            { label: t('AccountType.StandardAccount'), value: '7' },
            { label: t('AccountType.CentAccount'), value: '8' },
          ]
        } else {
          excludeList.value = [
            { label: t('AccountType.SeniorAccount'), value: '2' },
            { label: t('AccountType.StandardAccount'), value: '7' },
          ]
        }
        break
    }

    excludeList.value = excludeList.value.filter(
      (item) => !user.value.excludeShowLoginTypes.includes(item.value)
    )
    await loginTypeList()
    excludeShowLoginTypes.value = []
    selectedSpreadId.value = ''

    commission.value = 0
    hide.value = 0
    link.value = ''
    dialogLink.value = true
  }

  const downloadQrCode = () => {
    qrCode.value.download()
  }

  const CopyShareLink = (linkId) => {
    let linkEle = document.getElementById(linkId)
    linkEle.select()
    document.execCommand('Copy')
  }

  const CreateLink = async () => {
    const linkValue = await getLink1()
    if (!linkValue) return
    link.value = `${Host80}/#/signup/${getInfoId.value}/${linkValue}/${ibInvalid.value}?oc=${form.value.serial}`
  }

  const getValidAccountTypes = (selectedExcludeValues, selectedSpreadId) => {
    const spread = spreadList.value.find((item) => item.id === selectedSpreadId)
    let data = {
      hide: '',
      commission: '',
      excludeShowLoginTypes: [],
    }
    if (!spread) return data

    const validValues = selectedExcludeValues.filter((value) => spread.loginTypes.includes(value))
    const invalidValues = selectedExcludeValues.filter(
      (value) => !spread.loginTypes.includes(value)
    )

    const invalidLabels = excludeList.value
      .filter((item) => invalidValues.includes(item.value))
      .map((item) => item.label)

    const excludeShowLoginTypes = excludeList.value
      .filter((item) => !validValues.includes(item.value))
      .map((item) => item.value)

    loginTypes.value = invalidLabels.join('、')

    return {
      hide: spread.hide,
      commission: spread.comPoint,
      excludeShowLoginTypes,
      invalidLabels,
      invalidValues,
    }
  }

  const getLink1 = async () => {
    if (excludeShowLoginTypes.value.length === 0) {
      pigeon.MessageWarning(t('Ib.Index.Spread5'))
      link.value = ''
      return
    }
    if (!selectedSpreadId.value) {
      pigeon.MessageWarning(t('Ib.Index.Spread4'))
      link.value = ''
      return
    }

    const validList = getValidAccountTypes(excludeShowLoginTypes.value, selectedSpreadId.value)

    if (validList.excludeShowLoginTypes.length === excludeList.value.length) {
      pigeon.MessageError(t('Ib.Index.Spread3'))
      link.value = ''
      return
    }

    if (validList.invalidLabels.length > 0) {
      return new Promise((resolve) => {
        pigeon.MessageConfirm(
          `${t('Ib.Index.Spread1')}${loginTypes.value}${t('')}`,
          t('Msg.SystemPrompt'),
          t('Btn.Confirm'),
          t('Btn.Cancel'),
          async () => {
            const res = await Service.customLink(validList)
            if (res.code === Code.StatusOK) {
              pigeon.MessageOK(res.msg)
              resolve(res.data)
            } else {
              pigeon.MessageError(res.msg)
              resolve('')
            }
          },
          () => resolve('')
        )
      })
    } else {
      const res = await Service.customLink(validList)
      if (res.code === Code.StatusOK) {
        pigeon.MessageOK(res.msg)
        return res.data
      } else {
        pigeon.MessageError(res.msg)
        return ''
      }
    }
  }

  const loginTypeList = async () => {
    let res = await Service.loginTypeList({
      page: {
        current: 1,
        row: 100,
      },
    })
    if (res.code == Code.StatusOK) {
      spreadList.value = res.data
    } else {
      pigeon.MessageError(res.msg)
    }
  }

  // 生命周期
  nextTick(() => {})

  // 监听器
  watch(commission, () => {
    link.value = ''
  })

  watch(ibInvalid, () => {
    link.value = ''
  })

  // 暴露方法给父组件
  defineExpose({
    LinkActivity1,
  })
</script>

<style lang="scss" scoped>
  @import 'index.scss';
</style>

<style lang="scss">
  #ib_index {
    // 对话框全局样式
    .dialog_header_w.dialogLink {
      .el-dialog__header {
        font-weight: bold;
        border-bottom: 1px solid #dcdfe6;

        .el-dialog__title {
          font-size: 16px;
        }
      }
    }

    // 图表设置样式
    .chartSetting {
      .el-input__inner {
        height: 30px;
        line-height: 30px;
        background-color: transparent;
      }

      .el-form-item {
        margin-bottom: 15px;

        &__label {
          padding-bottom: 0;
        }
      }
    }

    // 图表框样式
    .chart-box {
      .el-input__inner {
        border: none;
        border-bottom: 1px solid #dcdfe6;
        border-radius: 0;
      }
    }

    // 链接容器样式
    .con-link {
      .el-select {
        width: 100%;
      }
    }
  }
</style>
