// 元规则（Meta Rule）字典
// 每个元规则定义编号、名称、配置字段，并提供 buildDescription / buildParams
// 用于在规则列表中自动渲染"规则描述"和"规则参数"

// 规则组类型选项
export const GROUP_TYPES = [
  { value: 'debitCard', label: '借记卡圈客规则' },
  { value: 'creditCard', label: '信用卡圈客规则' }
]

// 规则逻辑
export const LOGIC_OPTIONS = [
  { value: 'AND', label: '且（AND）' },
  { value: 'OR', label: '或（OR）' }
]

// 状态
export const STATUS_OPTIONS = [
  { value: 'draft', label: '新建' },
  { value: 'online', label: '已上线' }
]

// 常用比较运算符（用于 TRB / 余额 / 年龄等数值字段）
const NUMERIC_OPS = [
  { value: '>', label: '大于 >' },
  { value: '<', label: '小于 <' },
  { value: '=', label: '等于 =' },
  { value: '>=', label: '大于等于 >=' },
  { value: '<=', label: '小于等于 <=' },
  { value: '!=', label: '不等于 !=' }
]

// 日期比较运算符
const DATE_OPS = [
  { value: '<', label: '在...前' },
  { value: '>', label: '在...后' },
  { value: '=', label: '在...当日' }
]

// 集合运算符
const SET_OPS = [
  { value: 'in', label: '属于' },
  { value: 'not_in', label: '不属于' },
  { value: '=', label: '等于' },
  { value: '!=', label: '不等于' }
]

// =============================================
// 工具函数
// =============================================
function formatMonthCN(yyyymm) {
  if (!yyyymm) return ''
  const [y, m] = yyyymm.split('-')
  return `${y}年${parseInt(m, 10)}月`
}
function formatMonthCompact(yyyymm) {
  return yyyymm ? yyyymm.replace('-', '') : ''
}
function formatDateSlash(yyyymmdd) {
  if (!yyyymmdd) return ''
  const [y, m, d] = yyyymmdd.split('-')
  return `${y}/${parseInt(m, 10)}/${parseInt(d, 10)}`
}
function formatAmount(num) {
  if (num === '' || num === null || num === undefined) return ''
  const n = Number(num)
  if (Number.isNaN(n)) return String(num)
  if (n >= 10000) return `${n / 10000}万`
  return String(n)
}
function dateOpSuffix(op) {
  return { '<': '前', '>': '后', '=': '当日' }[op] || op || ''
}

// =============================================
// 元规则列表
// =============================================
export const META_RULES = [
  {
    code: '001',
    name: '开户时间(open_date)',
    paramKey: 'open_date',
    fields: [
      {
        key: 'accountType', label: '账户类型', type: 'select', required: true,
        options: [
          { value: 'I', label: 'I类账户' },
          { value: 'II', label: 'II类账户' },
          { value: 'III', label: 'III类账户' }
        ]
      },
      { key: 'operator', label: '比较方式', type: 'select', required: true, options: DATE_OPS },
      { key: 'date', label: '开户时间', type: 'datePicker', required: true }
    ],
    buildDescription(c) {
      if (!c.accountType || !c.date) return ''
      return `开户时间（${c.accountType}类账户）在${formatDateSlash(c.date)}${dateOpSuffix(c.operator)}`
    },
    buildParams(c) {
      if (!c.operator || !c.date) return ''
      return `{open_date,${c.operator},(${c.date})}`
    }
  },
  {
    code: '010',
    name: 'MSC',
    paramKey: 'MSC',
    fields: [
      { key: 'operator', label: 'MSC表达式', type: 'select', required: true, options: SET_OPS },
      {
        key: 'values', label: 'MSC值', type: 'multiSelect', required: true,
        options: [
          { value: 'premier', label: 'premier（卓越理财）' },
          { value: 'advance', label: 'advance（运筹理财）' },
          { value: 'excellence', label: 'excellence（卓越理财·尊尚）' },
          { value: 'global', label: 'global（环球私人银行）' }
        ]
      }
    ],
    buildDescription(c) {
      const vals = (c.values || []).join('/')
      if (!vals) return ''
      const opText = c.operator === 'not_in' || c.operator === '!=' ? '≠' : '='
      return `MSC${opText}${vals}`
    },
    buildParams(c) {
      const vals = (c.values || []).join('/')
      if (!c.operator || !vals) return ''
      return `{MSC,${c.operator},(${vals})}`
    }
  },
  {
    code: '050',
    name: 'TRB值-Avg TRB口径（不含家庭账户余额）',
    paramKey: 'Avg_TRB',
    fields: [
      { key: 'month', label: '开始月份', type: 'monthPicker', required: true },
      { key: 'nm', label: '连续达标月数/时间范围（月）', type: 'nm', required: false, defaultValue: { n: 3, m: 6 } },
      { key: 'operator', label: 'Avg TRB表达式', type: 'select', required: true, options: NUMERIC_OPS },
      { key: 'amount', label: 'Avg TRB值', type: 'number', required: true, min: 0 }
    ],
    buildDescription(c) {
      if (!c.month || !c.operator || c.amount === '' || c.amount == null) return ''
      const n = c.nm && c.nm.n ? `（连续${c.nm.n}个月达标）` : ''
      return `${formatMonthCN(c.month)}月末 TRB值-Avg TRB口径（不含家庭账户余额）${c.operator}${formatAmount(c.amount)}${n}`
    },
    buildParams(c) {
      if (!c.month || !c.operator) return ''
      const month = formatMonthCompact(c.month)
      const nm = c.nm && c.nm.n ? `;{${c.nm.n}/${c.nm.m || ''}}` : ''
      return `{month,=,${month}};{Avg_TRB,${c.operator},${c.amount}}${nm}`
    }
  },
  {
    code: '051',
    name: '月末余额(End of day balance)',
    paramKey: 'balance',
    fields: [
      { key: 'month', label: '开始月份', type: 'monthPicker', required: true },
      { key: 'nm', label: '连续达标月数/时间范围（月）', type: 'nm', required: false, defaultValue: { n: 3, m: 6 } },
      { key: 'operator', label: '余额表达式', type: 'select', required: true, options: NUMERIC_OPS },
      { key: 'amount', label: '余额值', type: 'number', required: true, min: 0 }
    ],
    buildDescription(c) {
      if (!c.month || !c.operator || c.amount === '' || c.amount == null) return ''
      const n = c.nm && c.nm.n ? `（连续${c.nm.n}个月达标）` : ''
      return `${formatMonthCN(c.month)}月末 End of day balance （所有资金含产品）${c.operator}${formatAmount(c.amount)}${n}`
    },
    buildParams(c) {
      if (!c.month || !c.operator) return ''
      const month = formatMonthCompact(c.month)
      const nm = c.nm && c.nm.n ? `;{${c.nm.n}/${c.nm.m || ''}}` : ''
      return `{month,=,${month}};{balance,${c.operator},${c.amount}}${nm}`
    }
  }
]

// 元规则下拉显示文本：编号-名称
export function metaRuleLabel(meta) {
  return `${meta.code}-${meta.name}`
}

// 根据 code 查询元规则
export function getMetaRule(code) {
  return META_RULES.find((m) => m.code === code)
}

// 计算一条规则的描述
export function buildRuleDescription(metaCode, config) {
  const meta = getMetaRule(metaCode)
  if (!meta || !meta.buildDescription) return ''
  return meta.buildDescription(config || {})
}

// 计算一条规则的参数
export function buildRuleParams(metaCode, config) {
  const meta = getMetaRule(metaCode)
  if (!meta || !meta.buildParams) return ''
  return meta.buildParams(config || {})
}
