import assessConfig from '@/utils/assessConfig'

export function backfill(baseConfig, assessDetail) {
  return assessConfig.reduce((prev, curr, index) => {
    const baseItem = baseConfig[index]
    const { alias_name, name } = baseItem
    const obj = {
      label: name,
      children: []
    }
    curr.forEach(citem => {
      const hasTitle = citem[0].type === 'title'
      const cItemArr = []
      citem.forEach(ccitem => {
        if (!assessDetail[alias_name]) return { label: '', value: '' }
        let ccitempropitem = assessDetail[alias_name][ccitem.prop]
        if (hasTitle) {
          ccitempropitem = assessDetail[alias_name][citem[0].prop][ccitem.prop]
        }
        if (ccitem.id) {
          const pOptions = baseItem.params[ccitem.id].children
          // console.log(ccitempropitem)
          let value = ccitempropitem ? ccitempropitem[ccitem.id] : ''
          if (typeof value !== 'object') {
            value = [value]
          }
          const valuearr = value.map(vitem => {
            const findOption = pOptions.find(pitem => Number(pitem.id) === Number(vitem))
            if (!findOption) return ''
            return findOption.name
          })
          // console.log(valuearr)
          ccitem.value = valuearr
          const newItem = {
            value: valuearr.join(' / '),
            prop: ccitem.prop,
            label: ccitem.title
          }
          if ('other' in ccitempropitem) {
            ccitem.other = ccitempropitem.other
            newItem.other = ccitempropitem.other
          }
          cItemArr.push(newItem)
          // console.log(newItem)
        } else if (ccitem.prop && ccitem.type !== 'title') {
          const newItem = {
            label: ccitem.title,
            value: ccitempropitem,
            prop: ccitem.prop
          }
          if (ccitem.label) newItem.value += ccitem.label
          if (ccitem.options) newItem.value = ccitem.options.find(o => Number(o.value) === Number(ccitempropitem)).label
          if (ccitem.prop === 'zsld' || ccitem.prop === 'ysld') {
            const [ccitemId] = Object.keys(ccitempropitem)
            const pOptions = baseItem.params[ccitemId].children
            const findOption = pOptions.find(pitem => Number(pitem.id) === Number(ccitempropitem[ccitemId]))
            if (!findOption) {
              newItem.value = ''
            } else {
              newItem.value = findOption.name
            }
          }
          cItemArr.push(newItem)
        }
      })
      if (hasTitle) {
        obj.children.push({
          label: citem[0].title,
          children: cItemArr
        })
      } else {
        obj.children = obj.children.concat(cItemArr)
      }
    })
    prev.push(obj)
    return prev
  }, [])
}
