<template>
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <FormItem
                        :label="t('channel.code')"
                        type="string"
                        v-model="baTable.form.items!.code"
                        prop="code"
                        :placeholder="t('Please input field', { field: t('channel.code') })"
                    />
                    <FormItem
                        :label="t('channel.name')"
                        type="string"
                        v-model="baTable.form.items!.name"
                        prop="name"
                        :placeholder="t('Please input field', { field: t('channel.name') })"
                    />
                    <FormItem
                        :label="t('channel.agent_mode')"
                        type="radio"
                        v-model="baTable.form.items!.agent_mode"
                        prop="agent_mode"
                        :input-attr="{ content: { turnover: t('channel.agent_mode turnover'), affiliate: t('channel.agent_mode affiliate') } }"
                    />
                    <el-alert
                        :title="currentAgentMode === 'turnover' ? t('channel.agent_mode_title_turnover') : t('channel.agent_mode_title_affiliate')"
                        type="info"
                        show-icon
                        :closable="false"
                        class="agent-mode-alert"
                    >
                        <template #default>
                            <ul class="agent-mode-desc-list">
                                <li v-for="item in currentAgentModeDescList" :key="item">{{ item }}</li>
                            </ul>
                        </template>
                    </el-alert>
                    <FormItem
                        v-if="currentAgentMode === 'turnover'"
                        :label="t('channel.turnover_share_rate')"
                        type="number"
                        v-model="baTable.form.items!.turnover_share_rate"
                        prop="turnover_share_rate"
                        :input-attr="{ step: 0.01, precision: 2, min: 0, max: 100 }"
                        :placeholder="`${t('Please input field', { field: t('channel.turnover_share_rate') })} (例如 30.5)`"
                    />
                    <FormItem
                        v-if="currentAgentMode === 'affiliate'"
                        :label="t('channel.affiliate_contract_no')"
                        type="string"
                        v-model="baTable.form.items!.affiliate_contract_no"
                        prop="affiliate_contract_no"
                        :placeholder="t('Please input field', { field: t('channel.affiliate_contract_no') })"
                    />
                    <FormItem
                        v-if="currentAgentMode === 'affiliate'"
                        :label="t('channel.affiliate_contract_name')"
                        type="string"
                        v-model="baTable.form.items!.affiliate_contract_name"
                        prop="affiliate_contract_name"
                        :placeholder="t('Please input field', { field: t('channel.affiliate_contract_name') })"
                    />
                    <FormItem
                        v-if="currentAgentMode === 'affiliate'"
                        :label="t('channel.affiliate_share_rate')"
                        type="number"
                        v-model="baTable.form.items!.affiliate_share_rate"
                        prop="affiliate_share_rate"
                        :input-attr="{ step: 0.0001, precision: 2, min: 0, max: 1 }"
                        :placeholder="`${t('Please input field', { field: t('channel.affiliate_share_rate') })} (例如 0.240000)`"
                    />
                    <FormItem
                        v-if="currentAgentMode === 'affiliate'"
                        :label="t('channel.affiliate_fee_rate')"
                        type="number"
                        v-model="baTable.form.items!.affiliate_fee_rate"
                        prop="affiliate_fee_rate"
                        :input-attr="{ step: 0.0001, precision: 2, min: 0, max: 1 }"
                        :placeholder="`${t('Please input field', { field: t('channel.affiliate_fee_rate') })} (例如 0.070000)`"
                    />
                    <el-form-item :label="t('channel.settle_cycle')" prop="settle_plan">
                        <el-tree-select
                            v-model="settlePlanValue"
                            class="w100"
                            clearable
                            filterable
                            :data="settlePlanTree"
                            :props="settlePlanTreeProps"
                            :render-after-expand="false"
                            :placeholder="t('channel.settle_cycle_placeholder')"
                            @change="onSettlePlanChange"
                        />
                    </el-form-item>
                    <FormItem :label="t('channel.settle_time')" type="time" v-model="baTable.form.items!.settle_time" prop="settle_time" />
                    <FormItem
                        v-if="currentAgentMode === 'affiliate'"
                        :label="t('channel.affiliate_effective_start_at')"
                        type="datetime"
                        v-model="baTable.form.items!.affiliate_effective_start_at"
                        prop="affiliate_effective_start_at"
                    />
                    <FormItem
                        v-if="currentAgentMode === 'affiliate'"
                        :label="t('channel.affiliate_effective_end_at')"
                        type="datetime"
                        v-model="baTable.form.items!.affiliate_effective_end_at"
                        prop="affiliate_effective_end_at"
                    />
                    <el-form-item v-if="currentAgentMode === 'affiliate'" :label="t('channel.affiliate_ladder_rules')" prop="affiliate_ladder_rules">
                        <div class="ladder-rule-box">
                            <div class="ladder-rule-row ladder-rule-head">
                                <span>{{ t('channel.ladder_min_loss') }}</span>
                                <span>{{ t('channel.ladder_share_rate') }}</span>
                                <span>{{ t('Operate') }}</span>
                            </div>
                            <div v-for="(item, idx) in ladderRuleList" :key="idx" class="ladder-rule-row">
                                <el-input-number v-model="item.minLoss" class="w100" :precision="4" :step="0.0001" :min="0" />
                                <el-input-number v-model="item.shareRate" class="w100" :precision="6" :step="0.0001" :min="0" :max="1" />
                                <el-button type="danger" link @click="removeLadderRule(idx)">{{ t('Delete') }}</el-button>
                            </div>
                            <el-button type="primary" link @click="addLadderRule">{{ t('Add') }}</el-button>
                        </div>
                    </el-form-item>
                    <FormItem
                        v-if="currentAgentMode === 'affiliate'"
                        :label="t('channel.carryover_balance')"
                        type="number"
                        v-model="baTable.form.items!.carryover_balance"
                        prop="carryover_balance"
                        :input-attr="{ step: 0.0001, precision: 4 }"
                        :placeholder="t('Please input field', { field: t('channel.carryover_balance') })"
                    />
                    <FormItem
                        :label="t('channel.status')"
                        type="switch"
                        v-model="baTable.form.items!.status"
                        prop="status"
                        :input-attr="{ content: { '0': t('channel.status 0'), '1': t('channel.status 1') } }"
                    />
                    <FormItem
                        :label="t('channel.remark')"
                        type="textarea"
                        v-model="baTable.form.items!.remark"
                        prop="remark"
                        :input-attr="{ rows: 3 }"
                        @keyup.enter.stop=""
                        @keyup.ctrl.enter="baTable.onSubmit(formRef)"
                        :placeholder="t('Please input field', { field: t('channel.remark') })"
                    />
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormItemRule } from 'element-plus'
import { ElMessage } from 'element-plus'
import { computed, inject, nextTick, onMounted, reactive, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'

const config = useConfig()
const formRef = useTemplateRef('formRef')
const baTable = inject('baTable') as baTableClass

const { t } = useI18n()

type LadderRuleRow = { minLoss: number; shareRate: number }
const ladderRuleList = ref<LadderRuleRow[]>([])

const settlePlanTree = computed(() => [
    { value: 'daily', label: t('channel.settle_cycle daily'), children: [] },
    {
        value: 'weekly',
        label: t('channel.settle_cycle weekly'),
        disabled: true,
        children: [1, 2, 3, 4, 5, 6, 7].map((n) => ({ value: `weekly:${n}`, label: t(`channel.weekday ${n}`), is_leaf: true })),
    },
    {
        value: 'monthly',
        label: t('channel.settle_cycle monthly'),
        disabled: true,
        children: Array.from({ length: 31 }).map((_, i) => {
            const day = i + 1
            return { value: `monthly:${day}`, label: `${day}${t('channel.day_suffix')}`, is_leaf: true }
        }),
    },
])
const settlePlanTreeProps = { value: 'value', label: 'label', children: 'children', disabled: 'disabled' }
const settlePlanValue = ref<string | null>(null)

const syncSettlePlanToItems = () => {
    const items = baTable.form.items
    if (!items) return
    ;(items as any).settle_plan = settlePlanValue.value ?? ''
}

const syncSettlePlanFromItems = () => {
    const items = baTable.form.items
    if (!items) return
    const cycle = items.settle_cycle || 'weekly'
    if (cycle === 'daily') {
        settlePlanValue.value = 'daily'
        syncSettlePlanToItems()
        return
    }
    if (cycle === 'monthly') {
        settlePlanValue.value = `monthly:${items.settle_monthday || 1}`
        syncSettlePlanToItems()
        return
    }
    settlePlanValue.value = `weekly:${items.settle_weekday || 1}`
    syncSettlePlanToItems()
}

watch(settlePlanValue, (val) => {
    if (!baTable.form.items) return
    if (!val) {
        syncSettlePlanToItems()
        return
    }
    if (val === 'daily') {
        baTable.form.items.settle_cycle = 'daily'
        baTable.form.items.settle_weekday = 1
        baTable.form.items.settle_monthday = 1
        return
    }
    if (val.startsWith('weekly:')) {
        const day = parseInt(val.split(':')[1] || '1', 10)
        baTable.form.items.settle_cycle = 'weekly'
        baTable.form.items.settle_weekday = Number.isNaN(day) ? 1 : day
        baTable.form.items.settle_monthday = 1
        return
    }
    if (val.startsWith('monthly:')) {
        const day = parseInt(val.split(':')[1] || '1', 10)
        baTable.form.items.settle_cycle = 'monthly'
        baTable.form.items.settle_monthday = Number.isNaN(day) ? 1 : day
        baTable.form.items.settle_weekday = 1
    }
    syncSettlePlanToItems()
})

const onSettlePlanChange = () => {
    nextTick(() => {
        formRef.value?.validateField('settle_plan')
    })
}

const currentAgentMode = computed(() => baTable.form.items?.agent_mode ?? 'turnover')
const currentAgentModeDescList = computed(() => {
    if (currentAgentMode.value === 'turnover') {
        return [t('channel.agent_mode_desc_turnover_1'), t('channel.agent_mode_desc_turnover_2'), t('channel.agent_mode_desc_turnover_3')]
    }
    return [t('channel.agent_mode_desc_affiliate_1'), t('channel.agent_mode_desc_affiliate_2'), t('channel.agent_mode_desc_affiliate_3')]
})

const normalizeLadderRulesToText = (val: unknown): string | null => {
    if (val === null || val === undefined || val === '') {
        return null
    }
    if (typeof val === 'string') {
        return val
    }
    try {
        return JSON.stringify(val, null, 2)
    } catch {
        return String(val)
    }
}

const parseLadderRulesText = (val: unknown): unknown => {
    if (val === null || val === undefined) {
        return null
    }
    if (typeof val !== 'string') {
        return val
    }
    const text = val.trim()
    if (!text) {
        return null
    }
    try {
        return JSON.parse(text)
    } catch {
        return text
    }
}

const syncLadderRuleRowsFromItems = () => {
    const items = baTable.form.items
    if (!items) return
    const raw = parseLadderRulesText(items.affiliate_ladder_rules)
    if (!Array.isArray(raw)) {
        ladderRuleList.value = []
        return
    }
    ladderRuleList.value = raw
        .map((r: any) => ({
            minLoss: Number(r.minLoss ?? r.min_loss ?? 0),
            shareRate: Number(r.shareRate ?? r.share_rate ?? 0),
        }))
        .filter((r: LadderRuleRow) => Number.isFinite(r.minLoss) && Number.isFinite(r.shareRate))
}

const addLadderRule = () => {
    ladderRuleList.value.push({ minLoss: 0, shareRate: 0 })
}

const removeLadderRule = (idx: number) => {
    ladderRuleList.value.splice(idx, 1)
}

onMounted(() => {
    syncSettlePlanFromItems()
})

watch(
    () => [baTable.form.operate, baTable.form.items?.id] as const,
    () => {
        const items = baTable.form.items
        if (!items || baTable.form.operate !== 'Edit') {
            return
        }
        items.affiliate_ladder_rules = normalizeLadderRulesToText(items.affiliate_ladder_rules) as any
        syncSettlePlanFromItems()
        syncLadderRuleRowsFromItems()
    }
)

watch(
    () => baTable.form.items?.agent_mode,
    (mode) => {
        if (!baTable.form.items) {
            return
        }
        if (mode === 'turnover') {
            baTable.form.items.affiliate_share_rate = null
            baTable.form.items.affiliate_fee_rate = null
            baTable.form.items.carryover_balance = 0
            baTable.form.items.affiliate_contract_no = null
            baTable.form.items.affiliate_contract_name = null
            baTable.form.items.affiliate_ladder_rules = null
            baTable.form.items.affiliate_effective_start_at = null
            baTable.form.items.affiliate_effective_end_at = null
            ladderRuleList.value = []
            return
        }
        if (mode === 'affiliate') {
            baTable.form.items.turnover_share_rate = null
            if (!baTable.form.items.settle_cycle) {
                baTable.form.items.settle_cycle = 'weekly'
            }
            syncLadderRuleRowsFromItems()
        }
        syncSettlePlanFromItems()
    }
)

const turnoverRateValidator = (label: string) => {
    return (_rule: any, value: string | number | null, callback: (error?: Error) => void) => {
        if (currentAgentMode.value !== 'turnover') {
            callback()
            return
        }
        if (value === null || value === undefined || value === '') {
            callback()
            return
        }
        const str = String(value).trim()
        if (!/^\d+(\.\d{1,6})?$/.test(str)) {
            callback(new Error(`${label}仅支持最多六位小数`))
            return
        }
        const num = Number(str)
        if (Number.isNaN(num) || num < 0 || num > 100) {
            callback(new Error(`${label}必须在0到100之间`))
            return
        }
        callback()
    }
}

const settlePlanValidator = (_rule: unknown, _value: unknown, callback: (error?: Error) => void) => {
    const v = settlePlanValue.value
    if (v !== null && v !== undefined && v !== '') {
        callback()
        return
    }
    callback(new Error(t('Please input field', { field: t('channel.settle_cycle') })))
}

const affiliateRateValidator = (label: string) => {
    return (_rule: any, value: string | number | null, callback: (error?: Error) => void) => {
        if (currentAgentMode.value !== 'affiliate') {
            callback()
            return
        }
        if (value === null || value === undefined || value === '') {
            callback()
            return
        }
        const str = String(value).trim()
        if (!/^\d+(\.\d{1,6})?$/.test(str)) {
            callback(new Error(`${label}仅支持最多六位小数`))
            return
        }
        const num = Number(str)
        if (Number.isNaN(num) || num < 0 || num > 1) {
            callback(new Error(`${label}必须在0到1之间`))
            return
        }
        callback()
    }
}

baTable.before.onSubmit = ({ items }) => {
    if (!items) {
        return
    }
    if (Object.prototype.hasOwnProperty.call(items, 'settle_plan')) {
        delete (items as any).settle_plan
    }
    if (items.agent_mode === 'affiliate') {
        if (ladderRuleList.value.length === 0) {
            ElMessage.error(t('channel.ladder_rule_required'))
            return false
        }
        const sorted = [...ladderRuleList.value].sort((a, b) => a.minLoss - b.minLoss)
        for (let i = 0; i < sorted.length; i++) {
            const row = sorted[i]
            if (!Number.isFinite(row.minLoss) || row.minLoss < 0) {
                ElMessage.error(t('channel.ladder_min_loss_invalid'))
                return false
            }
            if (!Number.isFinite(row.shareRate) || row.shareRate < 0 || row.shareRate > 1) {
                ElMessage.error(t('channel.ladder_share_rate_invalid'))
                return false
            }
            if (i > 0 && row.minLoss <= sorted[i - 1].minLoss) {
                ElMessage.error(t('channel.ladder_min_loss_order_invalid'))
                return false
            }
        }
        items.affiliate_ladder_rules = sorted.map((r) => ({
            minLoss: Number(r.minLoss).toFixed(2),
            shareRate: Number(r.shareRate).toFixed(6),
        }))
    } else {
        items.affiliate_ladder_rules = null
    }
    items.settle_cycle = items.settle_cycle || 'weekly'
    items.settle_weekday = items.settle_weekday || 1
    items.settle_monthday = items.settle_monthday || 1
    items.settle_time = items.settle_time || '02:00:00'
}

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    code: [buildValidatorData({ name: 'required', title: t('channel.code') })],
    name: [buildValidatorData({ name: 'required', title: t('channel.name') })],
    agent_mode: [buildValidatorData({ name: 'required', title: t('channel.agent_mode') })],
    turnover_share_rate: [{ validator: turnoverRateValidator(t('channel.turnover_share_rate')), trigger: 'blur' }],
    affiliate_share_rate: [{ validator: affiliateRateValidator(t('channel.affiliate_share_rate')), trigger: 'blur' }],
    affiliate_fee_rate: [{ validator: affiliateRateValidator(t('channel.affiliate_fee_rate')), trigger: 'blur' }],
    settle_plan: [{ validator: settlePlanValidator, trigger: ['change', 'blur'] }],
    settle_time: [buildValidatorData({ name: 'required', title: t('channel.settle_time') })],
    affiliate_effective_start_at: [buildValidatorData({ name: 'required', title: t('channel.affiliate_effective_start_at') })],
    carryover_balance: [buildValidatorData({ name: 'number', title: t('channel.carryover_balance') })],
})
</script>

<style scoped lang="scss">
.agent-mode-alert {
    margin-bottom: 12px;
}

.agent-mode-desc-list {
    margin: 6px 0 0;
    padding-left: 18px;
    line-height: 1.6;
}
</style>
