var defKey = {
  update_key: ['order_item_color_size_id', 'order_item_color_size_id'],
  color_key: ['color', 'color'],
  color_id: ['color_id', 'color_id'],
  size_key: ['size', 'size'],
  size_id: ['size_id', 'size_id'],
  qty: ['quantity', 'quantity']
}

function data2jsonlist(data) {
  var jsonlist = []
  for (const rindex in data) {
    var r = data[rindex]

    for (const k in r) {
      if (k !== defKey.color_key[1]) {
        var size = r[k]
        var quantity = size[defKey.qty[1]]
        delete size[defKey.qty[1]]

        var rst = {}
        rst[defKey.color_id[0]] = r[defKey.color_key[1]][defKey.color_id[1]]
        // rst[defKey.color_key[0]] = r[defKey.color_key[1]]
        rst[defKey.size_id[0]] = r[k][defKey.size_id[1]]
        if (defKey.update_key[1] in r[k]) {
          rst[defKey.update_key[0]] = r[k][defKey.update_key[1]]
        }
        // rst[defKey.size_key[0]] = size
        rst[defKey.qty[0]] = quantity
        rst.extend = {}
        jsonlist.push(rst)
      } else {
        continue
      }
    }
  }
  return jsonlist
}

function jsonlist2data(jsonlist) {
  var data = []
  var lastColor = {}

  for (const rindex in jsonlist) {
    var r = jsonlist[rindex]

    // console.log(r)
    if (
      defKey.color_key[0] in lastColor &&
      lastColor[defKey.color_key[1]][defKey.color_id[1]] ===
        r[defKey.color_id[0]]
    ) {
      lastColor[r[defKey.size_id[1]]] = r[defKey.size_key[0]]
      if (r[defKey.update_key[0]] !== undefined) {
        lastColor[r[defKey.size_id[1]]][defKey.update_key[1]] =
          r[defKey.update_key[0]]
      }
      lastColor[r[defKey.size_id[1]]][defKey.qty[1]] = r[defKey.qty[0]]
      // console.log(lastColor)
    } else {
      for (const k in lastColor) {
        console.log(k)
        data.push(lastColor)
        break
      }
      lastColor = {}
      lastColor[defKey.color_key[1]] = r[defKey.color_key[0]]
      lastColor[r[defKey.size_id[1]]] = r[defKey.size_key[0]]
      if (r[defKey.update_key[0]] !== undefined) {
        lastColor[r[defKey.size_id[1]]][defKey.update_key[1]] =
          r[defKey.update_key[0]]
      }
      lastColor[r[defKey.size_id[1]]][defKey.qty[1]] = r[defKey.qty[0]]
      // console.log(lastColor)
    }
  }
  data.push(lastColor)
  return data
}

const dataMathods = {
  data2jsonlist: data2jsonlist,
  jsonlist2data: jsonlist2data
}
export default dataMathods
