
function flatten (parent, data = [], menusRaw = []) {
  return data.reduce((acc, { name, children }) => {
    // console.log('menusRaw:', menusRaw)
    const menu = (menusRaw || []).filter(x => x.Url === name)[0]
    if (!menu) return acc

    const MenuName = menu.MenuName
    const item = { Url: name, MenuName, parent }
    if (children && children.length) {
      const p = parent.concat({ Url: name, MenuName })
      return acc.concat(item, flatten(p, children, menusRaw))
    }

    return acc.concat(item)
  }, [])
}

function packChildren (data) {
  let cp = data.slice()
  const res = []

  cp.map(x => {
    x.id = x.MenuId
    x.label = x.MenuName
    return x
  })

  data.forEach((it, inx) => {
    let found = false
    for (let i = 0; i < cp.length; i += 1) {
      if (cp[i].MenuId === it.FatherId) {
        found = true
        if (it.IsShow === 1) {
          cp[i].children = [...(cp[i].children || []), cp[inx]]
        }
        break
      }
    }

    if (!found && cp[inx].IsShow === 1) {
      res.push(cp[inx])
    }
  })

  return res
}

export default {
  state: {
    menusRaw: [],
    menus: [],
    breadcrumb: [],
    cases: {
      list: [],
      default: '',
      belongCase: null,
    },
    roles: [],
    user: {},
    clientUrl: '',
    picSize: {
      w: 0,
      height: 0
    }
  },
  mutations: {
    init (state, data) { // 这里的state对应着上面这个state
      state.menusRaw = data.menus
      state.roles = data.roles
      state.user = data.user
      state.menus = packChildren(data.menus || [])
      state.clientUrl = data.clienturl
      let defaultCase = ''
      for (let i = 0; i < data.cases.length; i++) {
        if (data.cases[i].IsBelong === 1) {
          defaultCase = data.cases[i].CaseId
        }
      }

      state.cases = {
        list: data.cases,
        default: defaultCase,
        belongCase: defaultCase,
      }
    },

    updateBread (state, { routerData, Url }) {
      // 扁平 routerData
      // 同时构造出 含有 title 的 parent 数据
      const routeList = flatten([], routerData[1].children, state.menusRaw)
      // console.log(routerData[1].children, state.menusRaw)

      // 过滤出与 name 相同的 route 节点
      const currentRoute = routeList.filter(x => x.Url === Url)[0]
      // console.log(currentRoute)

      // 获取 面包屑
      if (currentRoute) state.breadcrumb = currentRoute.parent.slice(1).concat(currentRoute)
      // console.log(state.breadcrumb)
    },
    setPicSize (state, data) { // 设置图片尺寸限制
      state.picSize = data
    },
  },
  actions: {
    updateSystemInfo (context) { // 这里的context和我们使用的$store拥有相同的对象和方法
      return new Promise((resolve) => {
        this.$ajax(this.$api.system.init.url, {
          method: this.$api.system.init.method
        }).then(res => {
          context.commit('init', res)
          resolve()
        })
      })
    },
    picSize (context, data) {
      context.commit('setPicSize', data)
    }
  }
}
