<template>
  <el-dialog
    v-model="visible"
    :title="$t('page.form.currentPoolTitle')"
    width="560px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-if="loading && !pool" class="flex justify-center py-8">{{ $t('page.form.loading') }}</div>
    <template v-else-if="pool">
      <div class="pool-info mb-4">
        <div class="flex items-center gap-2 mb-3">
          <span class="text-gray-500">{{ $t('page.form.poolName') }}：</span>
          <span>{{ pool.name }}</span>
        </div>
        <div class="profit-row mb-3">
          <div class="flex items-center gap-2">
            <span class="text-gray-500">{{ $t('page.form.poolProfitAmount') }}</span>
            <span class="font-mono text-lg" :class="profitAmountClass">{{
              displayProfitAmount
            }}</span>
            <span class="realtime-badge">{{ $t('page.form.realtime') }}</span>
          </div>
          <div class="profit-calc-hint">
            {{ $t('page.form.profitCalcHint') }}
          </div>
        </div>
        <div class="tip-block">
          <div class="tip-title">{{ $t('page.form.tierRuleTitle') }}</div>
          <div class="tip-content">
            {{ $t('page.form.tierRuleContent') }}
          </div>
        </div>
      </div>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item :label="$t('page.form.safetyLine')" prop="safety_line">
          <el-input-number
            v-model="formData.safety_line"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
          <div class="text-gray-500 text-xs mt-1">{{ $t('page.table.safetyLineTip') }}</div>
        </el-form-item>
        <el-form-item :label="$t('page.form.enableKillScore')">
          <el-switch v-model="formData.kill_enabled" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item :label="$t('page.form.killScoreWeights')">
          <div class="text-gray-500 text-sm">
            T1: {{ pool.t1_weight }}% / T2: {{ pool.t2_weight }}% / T3: {{ pool.t3_weight }}% / T4: {{ pool.t4_weight }}% / T5: {{ pool.t5_weight }}%
          </div>
        </el-form-item>
        <el-form-item>
          <div class="text-gray-500 text-sm">
            {{ $t('page.form.killWeightNote') }}
          </div>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="handleClose">{{ $t('form.close') }}</el-button>
      <el-button
        v-permission="'dice:lottery_pool_config:index:resetProfitAmount'"
        :loading="resetting"
        :disabled="!pool"
        @click="handleResetProfit"
      >
        {{ $t('page.form.btnResetProfit') }}
      </el-button>
      <el-button
        v-permission="'dice:lottery_pool_config:index:updateCurrentPool'"
        type="primary"
        :loading="saving"
        :disabled="!pool"
        @click="handleSubmit"
      >
        {{ $t('page.form.btnSaveSafetyLine') }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '../../../api/lottery_pool_config/index'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useI18n } from 'vue-i18n'
  import {
    getChannelDeptRequestParams,
    withChannelDeptParams
  } from '@/composables/useChannelDeptScope'

  const { t } = useI18n()
  const channelDeptParams = () => getChannelDeptRequestParams()

  interface PoolData {
    id: number
    name: string
    safety_line: number
    kill_enabled: number
    t1_weight: number
    t2_weight: number
    t3_weight: number
    t4_weight: number
    t5_weight: number
    profit_amount: number
  }

  const props = defineProps<{ modelValue: boolean }>()
  const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'success'): void }>()

  const visible = computed({
    get: () => props.modelValue,
    set: (v) => emit('update:modelValue', v)
  })

  const loading = ref(false)
  const saving = ref(false)
  const resetting = ref(false)
  const pool = ref<PoolData | null>(null)
  const formRef = ref<FormInstance>()

  const formData = reactive({
    safety_line: 0,
    kill_enabled: 1
  })

  const rules = computed<FormRules>(() => ({
    safety_line: [{ required: true, message: t('page.form.ruleSafetyLineRequired'), trigger: 'blur' }]
  }))

  const weightsSum = computed(() => {
    const p = pool.value
    if (!p) return 0
    return (p.t1_weight ?? 0) + (p.t2_weight ?? 0) + (p.t3_weight ?? 0) + (p.t4_weight ?? 0) + (p.t5_weight ?? 0)
  })

  const displayProfitAmount = computed(() => {
    const v = pool.value?.profit_amount
    if (v == null || Number.isNaN(v)) return '-'
    return Number(v).toFixed(2)
  })

  const profitAmountClass = computed(() => {
    const v = pool.value?.profit_amount
    if (v == null) return ''
    if (v > 0) return 'text-green-600'
    if (v < 0) return 'text-red-600'
    return ''
  })

  let pollTimer: ReturnType<typeof setInterval> | null = null
  const POLL_INTERVAL = 2000

  async function loadPool() {
    if (!visible.value) return
    try {
      loading.value = true
      const res = await api.getCurrentPool(channelDeptParams())
      const data = res as unknown as PoolData
      if (data && typeof data === 'object') {
        pool.value = data
        formData.safety_line = data.safety_line ?? 0
        formData.kill_enabled = (data.kill_enabled ?? 1) === 1 ? 1 : 0
      }
    } catch (e: any) {
      ElMessage.error(e?.message ?? t('page.form.msgGetPoolFailed'))
    } finally {
      loading.value = false
    }
  }

  function startPolling() {
    stopPolling()
    pollTimer = setInterval(() => {
      if (!visible.value) {
        stopPolling()
        return
      }
      api.getCurrentPool(channelDeptParams()).then((res) => {
        const data = res as unknown as PoolData
        if (pool.value && data && typeof data === 'object' && data.profit_amount != null) {
          pool.value.profit_amount = data.profit_amount
        }
      })
    }, POLL_INTERVAL)
  }

  function stopPolling() {
    if (pollTimer) {
      clearInterval(pollTimer)
      pollTimer = null
    }
  }

  async function handleSubmit() {
    if (!pool.value) return
    try {
      await formRef.value?.validate?.()
      saving.value = true
      await api.updateCurrentPool(
        withChannelDeptParams({
          safety_line: formData.safety_line,
          kill_enabled: formData.kill_enabled
        })
      )
      ElMessage.success(t('page.form.msgSaveSuccess'))
      await loadPool()
      emit('success')
    } catch (e: any) {
      if (e?.message) ElMessage.error(e.message)
    } finally {
      saving.value = false
    }
  }

  async function handleResetProfit() {
    if (!pool.value) return
    try {
      resetting.value = true
      await api.resetProfitAmount(channelDeptParams())
      ElMessage.success(t('page.form.msgResetProfitSuccess'))
      await loadPool()
      emit('success')
    } catch (e: any) {
      ElMessage.error(e?.message ?? t('page.form.msgResetFailed'))
    } finally {
      resetting.value = false
    }
  }

  function handleClose() {
    stopPolling()
    visible.value = false
    pool.value = null
  }

  watch(
    () => props.modelValue,
    (open) => {
      if (open) {
        // 切换渠道后再打开弹窗时，先清掉旧池数据，避免视觉残留
        pool.value = null
        loadPool().then(() => startPolling())
      } else {
        stopPolling()
      }
    }
  )

  onUnmounted(() => stopPolling())
</script>

<style scoped>
  .pool-info {
    padding: 8px 0;
  }

  .profit-row {
    margin-bottom: 8px;
  }

  .profit-calc-hint {
    margin-top: 4px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
    line-height: 1.4;
  }

  .realtime-badge {
    font-size: 11px;
    padding: 2px 6px;
    border-radius: 4px;
    background: var(--el-color-success-light-9);
    color: var(--el-color-success);
  }

  .tip-block {
    margin-top: 12px;
    padding: 10px 12px;
    background: var(--el-fill-color-light);
    border-radius: 6px;
    border-left: 3px solid var(--el-color-primary);
  }

  .tip-title {
    font-size: 13px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin-bottom: 6px;
  }

  .tip-content {
    font-size: 12px;
    color: var(--el-text-color-regular);
    line-height: 1.5;
  }

  .tip-content strong {
    color: var(--el-color-primary);
  }
</style>
