<template>
  <view class="page" id="more">
    <!-- 顶部搜索栏 -->
    <l-banner v-model="searchText" :focus="focus" placeholder="搜索应用名" type="search" noSearchButton fill fixed />

    <!-- 「我的应用」列表 -->
    <l-title v-if="searchText.length <= 0">我的应用</l-title>
    <view v-if="searchText.length <= 0" class="col-4 function-list cu-list grid no-border">
      <view
        v-for="(item, index) in myListDisplay"
        :key="index"
        class="cu-item text-center flex flex-wrap justify-center align-center"
      >
        <!-- 图标 -->
        <view
          @click="funcListClick(item)"
          style="background-color: #fe955c;"
          class="app-item align-center flex flex-wrap justify-center align-center"
        >
          <l-icon :type="item.icon" color="white" class="text-sl" />
        </view>
        <text>{{ item && item.F_Name }}</text>

        <!-- 图标下方按钮 -->
        <l-button v-if="edit" @click="removeClick(item.F_Id)" line="red" class="margin-top-sm">移出</l-button>
      </view>
    </view>

    <!-- 操作区按钮 -->
    <view v-if="searchText.length <= 0" class="padding-lr padding-bottom bg-white margin-bottom">
      <l-button @click="editClick" :line="edit ? 'green' : 'blue'" block>
        {{ edit ? '完成编辑' : '编辑“我的应用”列表' }}
      </l-button>
      <l-button v-if="edit" @click="cancelClick" line="red" class="margin-top block" block>放弃编辑</l-button>
    </view>

    <!-- 分块显示功能区 -->
    <template v-for="(group, title) in groupList">
      <view :key="title" class="margin-bottom">
        <!-- 区块标题 -->
        <l-title>{{ title }}</l-title>
        <!-- 按钮组 -->
        <view class="function-list cu-list grid no-border col-4">
          <view
            v-for="(item, index) in group"
            :key="index"
            class="cu-item text-center flex flex-wrap justify-center align-center"
          >
            <view
              @click="funcListClick(item)"
              :style="{ backgroundColor: funcListIconColor(item) }"
              class="app-item align-center flex flex-wrap justify-center align-center"
            >
              <l-icon :type="item.icon" color="white" class="text-sl" />
            </view>
            <text>{{ item && item.F_Name }}</text>

            <!-- 编辑模式按钮 -->
            <l-button
              v-if="edit"
              @click="itemClick(item.F_Id)"
              :line="editList.includes(item.F_Id) ? 'red' : 'green'"
              class="margin-top-sm"
            >
              {{ editList.includes(item.F_Id) ? '移出' : '添加' }}
            </l-button>
          </view>
        </view>
      </view>
    </template>
  </view>
</template>

<script>
import without from 'lodash/without'
import concat from 'lodash/concat'
import keyBy from 'lodash/keyBy'
import mapKeys from 'lodash/mapKeys'
import mapValues from 'lodash/mapValues'
import groupBy from 'lodash/groupBy'

export default {
  data() {
    return {
      allList: [],
      myList: [],
      editList: [],
      searchText: '',

      focus: false,
      edit: false
    }
  },

  async onLoad({ search }) {
    await this.init(search)
  },

  methods: {
    // 页面初始化
    async init(search) {
      this.focus = !!search
      this.LOADING('加载菜单中…')

      // 同时发出请求，获取“所有功能按钮列表”和“我的功能按钮列表”
      const [allList, myList] = await Promise.all([
        this.HTTP_GET('learun/adms/function/list').then(result => result.data),
        this.HTTP_GET('learun/adms/function/mylist')
      ])

      this.myList = myList.filter(t => allList.find(item => item.F_Id === t))
      this.allList = allList.map(item => {
        const icon = item.F_Icon ? item.F_Icon.replace(`iconfont icon-`, ``) : ''
        const existsIcon = this.getUiIcons().some(t => t === icon)

        return {
          ...item,
          icon: existsIcon ? icon : 'roundright'
        }
      })

      this.HIDE_LOADING()
    },

    // 点击编辑按钮，开启编辑模式
    async editClick() {
      if (!this.edit) {
        this.editList = [...this.myList]
        this.edit = true

        return
      }

      const success = await this.HTTP_POST(
        'learun/adms/function/mylist/update',
        this.editList.join(','),
        '「我的应用」列表更新失败'
      )

      if (!success) {
        this.editList = [...this.myList]
        this.edit = false
        return
      }

      this.myList = [...this.editList]
      this.edit = false
      this.EMIT('home-list-change')
    },

    // 获取按钮图标背景色（已在列表中的为橙色，不在的为蓝色）
    funcListIconColor(item) {
      if (this.edit) {
        return this.editList.includes(item.F_Id) ? '#fe955c' : '#62bbff'
      }

      return this.myList.includes(item.F_Id) ? '#fe955c' : '#62bbff'
    },

    // 点击按钮
    funcListClick(item) {
      if (item.F_IsSystem === 2) {
        this.NAV_TO(`/pages/customapp/list?formId=${item.F_FormId}`, item, true)
        return
      }
      
      this.NAV_TO(`/pages/${item.F_Url}/list`)
    },

    // 取消编辑按钮
    cancelClick() {
      this.edit = false
    },

    // 我的应用列表：点击移出按钮
    removeClick(id) {
      this.editList = without(this.editList, id)
    },

    // 编辑模式，功能区点击添加/移除按钮
    itemClick(id) {
      if (this.editList.includes(id)) {
        this.editList = without(this.editList, id)
        return
      }

      this.editList = concat(this.editList, id)
    }
  },

  computed: {
    // 我的应用列表
    myListDisplay() {
      const list = this.edit ? this.editList : this.myList
      return list.reduce((list, id) => [...list, this.allList.find(t => t.F_Id === id)], [])
    },

    // 获取列表分组
    groupList() {
      const typeTable = mapValues(keyBy(Object.values(this.GET_GLOBAL('dataDictionary').function), 'value'), 'text')

      return mapKeys(
        groupBy(this.allList.filter(item => item.F_Name.includes(this.searchText)), 'F_Type'),
        (v, k) => typeTable[k]
      )
    }
  }
}
</script>

<style lang="less" scoped>
.function-list {
  padding-bottom: 0;

  .cu-item {
    .app-item {
      border-radius: 50%;
      height: 45px;
      width: 45px;
    }
  }
}
</style>

<style lang="less">
#more {
  .function-list .cu-item text[class*='cuIcon'] {
    margin-top: 0 !important;
  }
}

page {
  padding-top: 100rpx;
}
</style>
