import {
  MERCHANT_TYPE_PERSON,
  MERCHANT_TYPE_ENTERPRISE,
  VALID_RANGE
} from '@/utils/entryConstants'
import { isMobile } from '@/utils/memberValidate'

const EMAIL_REG = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

function emptyPersonSubject() {
  return {
    merchantType: MERCHANT_TYPE_PERSON,
    personName: '',
    idCardType: '1',
    idCardNo: '',
    birthDate: '',
    idValidType: '1',
    idValidStart: '',
    idValidEnd: '',
    residenceAddress: '',
    gender: '',
    idCardFront: '',
    idCardBack: '',
    contactName: '',
    contactPhone: '',
    contactEmail: '',
    bankName: '',
    bankBranch: '',
    bankAccount: ''
  }
}

function emptyPersonBiz() {
  return {
    merchantType: MERCHANT_TYPE_PERSON,
    merchantName: '',
    servicePhone: '',
    bizRegionCode: '',
    bizRegionName: '',
    bizDetailAddress: ''
  }
}

function emptyEnterpriseSubject() {
  return {
    merchantType: MERCHANT_TYPE_ENTERPRISE,
    companyName: '',
    regRegionCode: '',
    regRegionName: '',
    companyDetailAddress: '',
    businessScope: '',
    creditCode: '',
    licenseValidType: '1',
    licenseValidStart: '',
    licenseValidEnd: '',
    legalName: '',
    legalResidence: '',
    legalGender: '',
    legalBirthDate: '',
    legalIdCardType: '1',
    legalIdCardNo: '',
    legalIdValidType: '1',
    legalIdValidStart: '',
    legalIdValidEnd: '',
    legalIdCardFront: '',
    legalIdCardBack: '',
    contactName: '',
    contactPhone: '',
    contactEmail: '',
    bankName: '',
    bankBranch: '',
    bankAccount: '',
    corpBankAccount: '',
    accountPermit: ''
  }
}

function emptyEnterpriseBiz() {
  return {
    merchantType: MERCHANT_TYPE_ENTERPRISE,
    bizRegionCode: '',
    bizRegionName: '',
    bizDetailAddress: '',
    businessLicense: ''
  }
}

function emptyShop() {
  return {
    shopName: '',
    shopAvatar: '',
    shopPhone: '',
    shopDesc: ''
  }
}

/** 创建空白入驻表单 */
export function createEntryForm(merchantType = MERCHANT_TYPE_PERSON) {
  const isPerson = merchantType === MERCHANT_TYPE_PERSON
  return {
    merchantType,
    subject: isPerson ? emptyPersonSubject() : emptyEnterpriseSubject(),
    biz: isPerson ? emptyPersonBiz() : emptyEnterpriseBiz(),
    shop: emptyShop(),
    agreementAccepted: false
  }
}

/** 省市区写入 biz/reg 字段 */
export function applyRegion(target, region) {
  if (!target || !region) return
  target.bizRegionCode = region.code || ''
  target.bizRegionName = region.name || ''
}

export function applyRegRegion(target, region) {
  if (!target || !region) return
  target.regRegionCode = region.code || ''
  target.regRegionName = region.name || ''
}

function requireText(value, msg) {
  if (!(value || '').trim()) return msg
  return ''
}

function requireEmail(value) {
  const t = (value || '').trim()
  if (!t) return '请输入常用邮箱'
  if (!EMAIL_REG.test(t)) return '邮箱格式不正确'
  return ''
}

function checkValidPeriod(label, type, start, end) {
  if (!type) return `请选择${label}有效期类型`
  if (type === VALID_RANGE && (!start || !end)) {
    return `请填写${label}有效期`
  }
  return ''
}

/** 前端分步校验，返回错误文案或空 */
export function validateEntryStep(form, stepKey) {
  const { merchantType, subject, biz, shop } = form
  const isPerson = merchantType === MERCHANT_TYPE_PERSON

  if (stepKey === 'type') {
    return merchantType ? '' : '请选择主体类型'
  }

  if (isPerson) {
    if (stepKey === 'subject') {
      return (
        requireText(subject.personName, '请输入姓名') ||
        requireText(subject.residenceAddress, '请输入居住地址') ||
        requireText(subject.gender, '请选择性别') ||
        requireText(subject.birthDate, '请选择出生日期') ||
        requireText(subject.idCardNo, '请输入证件号码') ||
        checkValidPeriod('证件', subject.idValidType, subject.idValidStart, subject.idValidEnd) ||
        requireText(subject.idCardFront, '请上传证件照正面') ||
        requireText(subject.idCardBack, '请上传证件照反面') ||
        requireText(subject.contactName, '请输入联系人姓名') ||
        (!isMobile(subject.contactPhone) ? '请输入正确的联系人手机' : '') ||
        requireEmail(subject.contactEmail) ||
        requireText(subject.bankName, '请输入开户银行') ||
        requireText(subject.bankBranch, '请输入开户支行') ||
        requireText(subject.bankAccount, '请输入银行账号')
      )
    }
    if (stepKey === 'biz') {
      return (
        requireText(biz.merchantName, '请输入商户名称') ||
        requireText(biz.servicePhone, '请输入客服电话') ||
        (requireText(biz.bizRegionCode, '请选择经营地址') || requireText(biz.bizRegionName, '请选择经营地址')) ||
        requireText(biz.bizDetailAddress, '请输入经营详细地址')
      )
    }
  } else {
    if (stepKey === 'subject') {
      return (
        requireText(subject.companyName, '请输入企业名称') ||
        (requireText(subject.regRegionCode, '请选择注册地址') || requireText(subject.regRegionName, '请选择注册地址')) ||
        requireText(subject.companyDetailAddress, '请输入注册详细地址') ||
        requireText(subject.businessScope, '请输入经营范围') ||
        requireText(subject.creditCode, '请输入统一社会信用代码') ||
        checkValidPeriod('营业', subject.licenseValidType, subject.licenseValidStart, subject.licenseValidEnd) ||
        requireText(subject.legalName, '请输入法人姓名') ||
        requireText(subject.legalResidence, '请输入法人居住地址') ||
        requireText(subject.legalGender, '请选择法人性别') ||
        requireText(subject.legalBirthDate, '请选择法人出生日期') ||
        requireText(subject.legalIdCardNo, '请输入法人证件号码') ||
        checkValidPeriod('法人证件', subject.legalIdValidType, subject.legalIdValidStart, subject.legalIdValidEnd) ||
        requireText(subject.legalIdCardFront, '请上传法人证件照正面') ||
        requireText(subject.legalIdCardBack, '请上传法人证件照反面') ||
        requireText(subject.contactName, '请输入联系人姓名') ||
        (!isMobile(subject.contactPhone) ? '请输入正确的联系人手机' : '') ||
        requireEmail(subject.contactEmail) ||
        requireText(subject.bankName, '请输入开户银行') ||
        requireText(subject.bankBranch, '请输入开户支行') ||
        requireText(subject.bankAccount, '请输入银行账号') ||
        requireText(subject.corpBankAccount, '请输入对公银行账号') ||
        requireText(subject.accountPermit, '请上传开户许可证')
      )
    }
    if (stepKey === 'biz') {
      return (
        (requireText(biz.bizRegionCode, '请选择经营地址') || requireText(biz.bizRegionName, '请选择经营地址')) ||
        requireText(biz.bizDetailAddress, '请输入经营详细地址') ||
        requireText(biz.businessLicense, '请上传营业执照')
      )
    }
  }

  if (stepKey === 'shop') {
    return (
      requireText(shop.shopName, '请输入店铺名称') ||
      requireText(shop.shopPhone, '请输入联系电话') ||
      requireText(shop.shopAvatar, '请上传店铺 Logo')
    )
  }

  if (stepKey === 'submit') {
    if (!form.agreementAccepted) return '请先阅读并同意入驻协议'
  }

  return ''
}

/** 提交前组装 DTO */
export function buildEntrySubmitPayload(form) {
  return {
    subject: { ...form.subject, merchantType: form.merchantType },
    biz: { ...form.biz, merchantType: form.merchantType },
    shop: { ...form.shop },
    agreementAccepted: !!form.agreementAccepted
  }
}
