import Mock from 'mockjs'

// =============================================
// 登录
// =============================================
Mock.mock(/\/api\/login/, 'post', (options) => {
  const { username, password } = JSON.parse(options.body || '{}')
  if (!username || !password) {
    return { code: 400, data: null, msg: '账号或密码不能为空' }
  }
  if (username === 'admin' && password === '123456') {
    return {
      code: 200,
      data: { token: 'mock-token-' + Date.now(), username },
      msg: '登录成功'
    }
  }
  return { code: 401, data: null, msg: '账号或密码错误' }
})

// =============================================
// 页面管理 - 权益介绍页配置
// =============================================
const homeConfigData = {
  premier: {
    tabName: '卓越理财',
    buttons: { unlocked: '进入权益专区', locked: '待解锁' },
    header: {
      imageUrl: 'https://images.unsplash.com/photo-1518893494013-481c1d8ed3fd?w=800',
      mainTitle: '卓越理财',
      subTitle: '为您和您的家人提供尊崇专属礼遇和权益'
    },
    privileges: [
      { imageUrl: '', title: '国际教育', desc: '享专属国际化学校优惠及背景提升项目' },
      { imageUrl: '', title: '酒店礼遇', desc: '高端酒店及商场会籍匹配' }
    ]
  },
  elite: {
    tabName: '卓越理财·尊尚',
    buttons: { unlocked: '进入权益专区', locked: '待解锁' },
    header: {
      imageUrl: 'https://images.unsplash.com/photo-1518893494013-481c1d8ed3fd?w=800',
      mainTitle: '卓越理财·尊尚',
      subTitle: '为您和您的家人提供尊崇专属礼遇和权益'
    },
    privileges: [
      { imageUrl: '', title: '国际教育', desc: '享专属国际化学校优惠及背景提升项目' },
      { imageUrl: '', title: '酒店礼遇', desc: '高端酒店及商场会籍匹配' }
    ]
  },
  global: {
    tabName: '环球私人银行',
    buttons: { unlocked: '进入权益专区', locked: '待解锁' },
    header: {
      imageUrl: 'https://images.unsplash.com/photo-1518893494013-481c1d8ed3fd?w=800',
      mainTitle: '环球私人银行',
      subTitle: '为您和您的家人提供尊崇专属礼遇和权益'
    },
    privileges: [
      { imageUrl: '', title: '国际教育', desc: '享专属国际化学校优惠及背景提升项目' },
      { imageUrl: '', title: '酒店礼遇', desc: '高端酒店及商场会籍匹配' }
    ]
  }
}

let homeStatus = 'published'

Mock.mock(/\/api\/page-config\/home/, 'get', () => {
  return { code: 200, data: { config: homeConfigData, status: homeStatus }, msg: 'ok' }
})

Mock.mock(/\/api\/page-config\/home/, 'put', (options) => {
  const body = JSON.parse(options.body)
  Object.assign(homeConfigData, body.config || {})
  homeStatus = body.status || homeStatus
  return { code: 200, data: null, msg: '保存成功' }
})

// =============================================
// 页面管理 - 权益首页配置
// =============================================
const zoneConfigData = {
  adCarousel: [{
    imageUrl: 'https://images.unsplash.com/photo-1556742049-0cfed4f6a45d?w=800',
    linkH5: '', linkApp: '', wechatAppId: '', wechatPath: '',
    title: '汇丰卓越理财新户达标礼',
    subtitle: '报名参加汇丰活动，体验更多精彩礼遇',
    tags: ['t1', 't2']
  }],
  exchangeConfig: {
    items: [
      { imageUrl: 'https://images.unsplash.com/photo-1436491865332-7a61a109cc05?w=200', title: '航空里程', link: '/flight' },
      { imageUrl: 'https://images.unsplash.com/photo-1518893494013-481c1d8ed3fd?w=200', title: '贵宾厅', link: '/lounge' }
    ]
  },
  ruleModal: {
    title: '积分规则',
    content: '<p>本积分使用规则为汇丰银行（中国）有限公司...</p>'
  }
}

let zoneStatus = 'published'

const availableTags = Array.from({ length: 8 }, (_, i) => ({ id: `t${i + 1}`, name: `人群标签${i + 1}` }))

Mock.mock(/\/api\/page-config\/zone/, 'get', () => {
  return { code: 200, data: { config: zoneConfigData, status: zoneStatus, availableTags }, msg: 'ok' }
})

Mock.mock(/\/api\/page-config\/zone/, 'put', (options) => {
  const body = JSON.parse(options.body)
  Object.assign(zoneConfigData, body.config || {})
  zoneStatus = body.status || zoneStatus
  return { code: 200, data: null, msg: '保存成功' }
})

// =============================================
// 页面管理 - 组装页
// =============================================
let assemblyIdCounter = 3000

const assemblyList = [
  {
    id: 'A7538', name: '双十一迎新专属活动页', status: 'published',
    createTime: '2025-10-01 10:00:00', updateTime: '2025-10-15 14:30:00',
    blocks: [
      { type: 'image', id: 'b_init1', data: { imageUrl: 'https://images.unsplash.com/photo-1557683316-973673baf926?w=800' } },
      { type: 'privilege', id: 'b_init2', data: { title: '专属权益', items: [{ id: '1', title: '机场贵宾厅服务', desc: '全年免费使用6次指定机场贵宾厅' }, { id: '2', title: '境内礼宾车', desc: '免费2次接送' }] } },
      { type: 'richtext', id: 'b_init3', data: { content: '<p>欢迎参与双十一专属福利活动...</p>' } },
      { type: 'buttonGroup', id: 'b_init4', data: { buttons: [{ text: '立即参与', link: '/join', style: 'primary', actionType: 'link' }] } }
    ]
  },
  {
    id: 'A2091', name: '私行高净值沙龙引导页', status: 'draft',
    createTime: '2025-11-20 09:15:00', updateTime: '2025-11-20 09:15:00',
    blocks: [
      { type: 'image', id: 'b_init5', data: { imageUrl: 'https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?w=800' } },
      { type: 'privilege', id: 'b_init6', data: { title: '尊享体验', items: [{ id: '1', title: '高尔夫权益', desc: 'VIP高尔夫俱乐部免会籍预约' }] } }
    ]
  }
]

Mock.mock(/\/api\/assembly\/list/, 'get', (options) => {
  const url = new URL(options.url, 'http://localhost')
  const id = url.searchParams.get('id') || ''
  const name = url.searchParams.get('name') || ''
  let filtered = assemblyList
  if (id) filtered = filtered.filter(a => a.id.includes(id))
  if (name) filtered = filtered.filter(a => a.name.includes(name))
  return { code: 200, data: filtered, msg: 'ok' }
})

Mock.mock(/\/api\/assembly\/detail/, 'get', (options) => {
  const url = new URL(options.url, 'http://localhost')
  const id = url.searchParams.get('id')
  const item = assemblyList.find(a => a.id === id)
  return item
    ? { code: 200, data: item, msg: 'ok' }
    : { code: 404, data: null, msg: '未找到' }
})

Mock.mock(/\/api\/assembly\/save/, 'post', (options) => {
  const body = JSON.parse(options.body)
  const now = new Date().toLocaleString('zh-CN', { hour12: false })
  if (body.id) {
    const idx = assemblyList.findIndex(a => a.id === body.id)
    if (idx >= 0) {
      assemblyList[idx] = { ...assemblyList[idx], ...body, updateTime: now }
    }
  } else {
    body.id = 'A' + (++assemblyIdCounter)
    body.createTime = now
    body.updateTime = now
    assemblyList.unshift(body)
  }
  return { code: 200, data: { id: body.id }, msg: '保存成功' }
})

Mock.mock(/\/api\/assembly\/delete/, 'post', (options) => {
  const body = JSON.parse(options.body)
  const idx = assemblyList.findIndex(a => a.id === body.id)
  if (idx >= 0) assemblyList.splice(idx, 1)
  return { code: 200, data: null, msg: '删除成功' }
})

// =============================================
// 渠道管理 - Channel
// =============================================
const channelDict = {
  'Human-assisted': {
    '汇丰中国客户服务号': ['汇丰中国客户服务号'],
    'MGM': ['MGM - Mortgage', 'MGM - Premier'],
    'CCSS': ['CCSS SMS'],
    'Referral': ['GPB Referral', 'HK referral', 'Non WPB staff Referral', 'Pinnacle Referral', 'RBB Refferal'],
    'New staff': ['New staff'],
    'IBC': ['IBC referral staff code'],
    'Group Acct': ['HTC', 'NIVIDA']
  },
  'Unassisted': {
    '汇丰中国APP': ['Mobile X'],
    '汇丰中国官网': ['PWS site'],
    '汇丰中国小程序': ['汇丰中国小程序'],
    '汇丰中国订阅号': ['汇丰中国订阅号', '汇丰中国订阅号推文', '推文尾部入口'],
    'Chatbot': ['Chatbot'],
    'SMS': ['SMS'],
    'Paid Media': ['汇丰中国订阅号推文', 'others'],
    'Others': ['others', 'River APP']
  }
}

let channelIdCounter = 9
const channelRows = [
  { id: 'CH0001', type: 'Human-assisted', category: '汇丰中国客户服务号', name: '汇丰中国客户服务号', subName: '', owner: '', createTime: '2025-11-20 09:15:00', updateTime: '2025-11-20 09:15:00' },
  { id: 'CH0002', type: 'Human-assisted', category: 'MGM', name: 'MGM - Mortgage', subName: '', owner: '', createTime: '2025-11-20 09:15:00', updateTime: '2025-11-20 09:15:00' },
  { id: 'CH0003', type: 'Human-assisted', category: 'MGM', name: 'MGM - Premier', subName: '双十一特惠', owner: '张经理', createTime: '2025-11-20 09:15:00', updateTime: '2025-11-21 14:30:00' },
  { id: 'CH0004', type: 'Human-assisted', category: 'CCSS', name: 'CCSS SMS', subName: '', owner: '', createTime: '2025-11-20 09:15:00', updateTime: '2025-11-20 09:15:00' },
  { id: 'CH0005', type: 'Human-assisted', category: 'Referral', name: 'GPB Referral', subName: '', owner: '', createTime: '2025-11-20 09:15:00', updateTime: '2025-11-20 09:15:00' },
  { id: 'CH0006', type: 'Unassisted', category: '汇丰中国APP', name: 'Mobile X', subName: '', owner: '', createTime: '2025-11-20 09:15:00', updateTime: '2025-11-20 09:15:00' },
  { id: 'CH0007', type: 'Unassisted', category: '汇丰中国官网', name: 'PWS site', subName: '私行沙龙引导', owner: '', createTime: '2025-11-20 09:15:00', updateTime: '2025-11-20 09:15:00' },
  { id: 'CH0008', type: 'Unassisted', category: '汇丰中国订阅号', name: '汇丰中国订阅号', subName: '', owner: '', createTime: '2025-11-20 09:15:00', updateTime: '2025-11-20 09:15:00' },
  { id: 'CH0009', type: 'Unassisted', category: '汇丰中国订阅号', name: '推文尾部入口', subName: '', owner: '', createTime: '2025-11-20 09:15:00', updateTime: '2025-11-20 09:15:00' }
]

Mock.mock(/\/api\/channel\/dict/, 'get', () => {
  return { code: 200, data: channelDict, msg: 'ok' }
})

Mock.mock(/\/api\/channel\/dict\/save/, 'post', (options) => {
  const body = JSON.parse(options.body)
  const { target, type, category, oldValue, newValue, mode } = body
  if (target === 'type') {
    if (mode === 'add') { channelDict[newValue] = {} }
    else { channelDict[newValue] = channelDict[oldValue]; delete channelDict[oldValue]; channelRows.forEach(r => { if (r.type === oldValue) r.type = newValue }) }
  } else if (target === 'category') {
    if (mode === 'add') { channelDict[type][newValue] = [] }
    else { channelDict[type][newValue] = channelDict[type][oldValue]; delete channelDict[type][oldValue]; channelRows.forEach(r => { if (r.type === type && r.category === oldValue) r.category = newValue }) }
  } else if (target === 'name') {
    const list = channelDict[type][category]
    if (mode === 'add') { list.push(newValue) }
    else { const idx = list.indexOf(oldValue); if (idx >= 0) list[idx] = newValue; channelRows.forEach(r => { if (r.type === type && r.category === category && r.name === oldValue) r.name = newValue }) }
  }
  return { code: 200, data: channelDict, msg: '保存成功' }
})

Mock.mock(/\/api\/channel\/list/, 'get', (options) => {
  const url = new URL(options.url, 'http://localhost')
  const sId = (url.searchParams.get('id') || '').toLowerCase()
  const sType = url.searchParams.get('type') || ''
  const sCategory = (url.searchParams.get('category') || '').toLowerCase()
  const sName = (url.searchParams.get('name') || '').toLowerCase()
  const sSubName = (url.searchParams.get('subName') || '').toLowerCase()
  const sOwner = (url.searchParams.get('owner') || '').toLowerCase()
  let filtered = channelRows
  if (sId) filtered = filtered.filter(c => c.id.toLowerCase().includes(sId))
  if (sType) filtered = filtered.filter(c => c.type === sType)
  if (sCategory) filtered = filtered.filter(c => c.category.toLowerCase().includes(sCategory))
  if (sName) filtered = filtered.filter(c => c.name.toLowerCase().includes(sName))
  if (sSubName) filtered = filtered.filter(c => c.subName.toLowerCase().includes(sSubName))
  if (sOwner) filtered = filtered.filter(c => c.owner.toLowerCase().includes(sOwner))
  return { code: 200, data: filtered, msg: 'ok' }
})

Mock.mock(/\/api\/channel\/save/, 'post', (options) => {
  const body = JSON.parse(options.body)
  const now = new Date().toLocaleString('zh-CN', { hour12: false })
  if (body.id) {
    const idx = channelRows.findIndex(c => c.id === body.id)
    if (idx >= 0) channelRows[idx] = { ...channelRows[idx], ...body, updateTime: now }
  } else {
    body.id = 'CH' + String(++channelIdCounter).padStart(4, '0')
    body.createTime = now
    body.updateTime = now
    channelRows.unshift(body)
  }
  return { code: 200, data: { id: body.id }, msg: '保存成功' }
})

Mock.mock(/\/api\/channel\/delete/, 'post', (options) => {
  const body = JSON.parse(options.body)
  const idx = channelRows.findIndex(c => c.id === body.id)
  if (idx >= 0) channelRows.splice(idx, 1)
  return { code: 200, data: null, msg: '删除成功' }
})

// =============================================
// 渠道管理 - Campaign
// =============================================
let campaignIdCounter = 9002
const campaignRows = [
  { id: 'CP9001', name: 'Q3 大客户回馈', owner: 'Market Team', staff: '王专员', createTime: '2025-10-01 10:00:00', updateTime: '2025-10-15 14:30:00' },
  { id: 'CP9002', name: '新春开户活动', owner: 'Retail Team', staff: '李专员', createTime: '2025-11-20 09:15:00', updateTime: '2025-11-20 09:15:00' }
]

Mock.mock(/\/api\/campaign\/list/, 'get', (options) => {
  const url = new URL(options.url, 'http://localhost')
  const sId = (url.searchParams.get('id') || '').toLowerCase()
  const sName = (url.searchParams.get('name') || '').toLowerCase()
  const sOwner = (url.searchParams.get('owner') || '').toLowerCase()
  const sStaff = (url.searchParams.get('staff') || '').toLowerCase()
  let filtered = campaignRows
  if (sId) filtered = filtered.filter(c => c.id.toLowerCase().includes(sId))
  if (sName) filtered = filtered.filter(c => c.name.toLowerCase().includes(sName))
  if (sOwner) filtered = filtered.filter(c => c.owner.toLowerCase().includes(sOwner))
  if (sStaff) filtered = filtered.filter(c => c.staff.toLowerCase().includes(sStaff))
  return { code: 200, data: filtered, msg: 'ok' }
})

Mock.mock(/\/api\/campaign\/save/, 'post', (options) => {
  const body = JSON.parse(options.body)
  const now = new Date().toLocaleString('zh-CN', { hour12: false })
  if (body.id) {
    const idx = campaignRows.findIndex(c => c.id === body.id)
    if (idx >= 0) campaignRows[idx] = { ...campaignRows[idx], ...body, updateTime: now }
  } else {
    body.id = 'CP' + (++campaignIdCounter)
    body.createTime = now
    body.updateTime = now
    campaignRows.unshift(body)
  }
  return { code: 200, data: { id: body.id }, msg: '保存成功' }
})

Mock.mock(/\/api\/campaign\/delete/, 'post', (options) => {
  const body = JSON.parse(options.body)
  const idx = campaignRows.findIndex(c => c.id === body.id)
  if (idx >= 0) campaignRows.splice(idx, 1)
  return { code: 200, data: null, msg: '删除成功' }
})

export default Mock
