import MemberSet from '@/api/setting-center/MemberSet'
const log = console.log.bind(console)

class MemberSetApi {
  constructor() {
    this.api = new MemberSet()
  }

  getListByValid(validMemberCondition) {
    const v = validMemberCondition
    let keys = Object.keys(v)
    const list = []

    keys = keys.filter(
      item => item !== 'orderPay' && item !== 'goodsCommission'
    )

    const keysMap = {
      bindPhone: '1',
      tbAuth: '2',
      receive: '3',
      withdraw: '4'
    }

    keys.map(item => {
      if (v[item] === 1) {
        list.push(keysMap[item])
      }
    })
    return list
  }

  getRadioByCondition(newMemberCondition) {
    const n = newMemberCondition
    let radio = '0'
    log(n, 'newMenber')
    const condition = JSON.parse(n)
    const k = Object.keys(condition)
    radio = k.includes('registerIn') ? '0' : '1'
    log(radio, 'radio')
    return radio
  }

  loadClean(data) {
    const d = data
    const list = this.getListByValid(JSON.parse(d.validMemberCondition))
    const radio = this.getRadioByCondition(d.newMemberCondition)
    const dataForm = {
      limitRegister: d.limitRegister,
      limitText: d.limitRegisterText,
      rules: JSON.parse(d.limitRegisterRule),
      validMember: JSON.parse(d.validMemberCondition),
      needInviteCode: d.needInviteCode,
      newMemberCondition: JSON.parse(d.newMemberCondition),
      checkList: list,
      conditionRadio: radio
    }
    log(dataForm, 'clean')
    return dataForm
  }

  // 页面数据初始化
  load() {
    const l = this.api.load()
    return l.then(res => {
      const data = res.data
      log(data, 'in load')
      return this.loadClean(data)
    })
  }

  formateToNumber(obj) {
    const keys = Object.keys(obj)
    for (const k of keys) {
      obj[k] = Number(obj[k])
    }
    return obj
  }

  formateData(data) {
    const f = JSON.parse(JSON.stringify(data))
    const toNum = this.formateToNumber
    let result = {
      limitRegister: Number(f.limitRegister),
      limitRegisterRule: toNum(f.rules),
      limitRegisterText: f.limitText,
      validMemberCondition: toNum(f.validMember),
      newMemberCondition: toNum(f.newMemberCondition),
      needInviteCode: Number(f.needInviteCode)
    }
    log(result, 'result')
    result = JSON.stringify(result)
    return result
  }

  // 保存设置修改
  updataSet(data) {
    const formate = this.formateData(data)
    log(formate, 'formate in here')
    const u = this.api.updataSet(formate)
    log(u, 'formate')
    return u
  }
}

const memberApi = new MemberSetApi()

export default memberApi
