import { queryCarModelGroupPackage, queryComponentList } from '@/api/carModel'

const state = {
  treeData: [],
  selectedBrand: {},
  selectAllFlag: false,
  selectAllBrandFlag: false
}

const mutations = {
  RESETALL: (state, value) => {
    state.selectAllBrandFlag = true
    state.selectedBrand = state.treeData[0]
    state.selectAllFlag = true
    state.selectedBrand.sub.forEach(i => i.selected = false)
    state.treeData.forEach(i => i.selected = false)
  },
  CLEARALL: (state, value) => {
    state.selectAllBrandFlag = false
    state.selectedBrand = {}
    state.selectAllFlag = false
    state.treeData = []
  },
  SET_SUB_STATE: (state, value) => {
    state.selectAllFlag = true
    state.selectedBrand.sub.forEach(v => v.selected = value)
  },
  SELECT_SUB: (state, value) => {
    if (state.selectedBrand.sub.filter(i => i.selected).length > 1 || state.selectAllFlag) {
      value.selected = !value.selected
      state.selectAllFlag = false
    } else {
      value.selected = true
    }
  },
  SELECT_ONE_BRAND: (state, value) => {
    state.selectAllBrandFlag = false
    if (value.selected) return
    state.selectedBrand && state.selectedBrand.sub.forEach(i => i.selected = false)
    state.selectAllFlag = true
    value.selected = !value.selected
    state.selectedBrand = value
    state.treeData.filter(k => k.code !== value.code).forEach(v => v.selected = false)
  },
  SET_TREEDATA_STATE: (state, value) => {
    state.selectAllBrandFlag = true
    state.treeData.forEach(i => i.selected = value)
  },
  SET_TREE_DATA: (state, value) => {
    state.treeData = value.map((item, index) => {
      item.sub = item.sub.map((item2, index2) => {
        return {
          ...item2,
          selected: false
        }
      })
      return {
        ...item,
        selected: false
      }
    })
    state.selectedBrand = state.treeData[0]
    state.selectAllFlag = true
    state.selectAllBrandFlag = true
  }
}
const actions = {
  async queryCarBrandList({ commit }) {
    const res = await queryComponentList()
    commit('SET_TREE_DATA', res)
  }
}

export default {
  namespaced: true,
  state,
  actions,
  mutations
}
