<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-row">
        <el-button type="primary" class="mb" @click="fnAddRouter({}, '新增一级菜单')">
          新增一级菜单
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      ref="multipleTable"
      :data="varList"
      :header-cell-style="{
        'font-weight': 'bold',
        'color': '#000'
      }"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      row-key="ROUTE_ID"
      tooltip-effect="dark"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="名称" prop="meta.title" />
      <el-table-column label="路由地址" prop="path" show-overflow-tooltip />
      <el-table-column label="文件位置" show-overflow-tooltip>
        <template slot-scope="{row}">
          {{
            row.component === "children"
              ? "/src/components/children/index.vue"
              : "/src/views/" + row.component + ".vue"
          }}
        </template>
      </el-table-column>
      <el-table-column label="序号" prop="ROUTE_ORDER" width="50" />
      <el-table-column label="是否显示在菜单">
        <template slot-scope="{row}">
          {{
            row.meta && row.meta.isMenu !== false && !row.meta.activeMenu && row.path
              ? "是"
              : "否"
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="400">
        <template slot-scope="{row}">
          <el-button v-if="row.meta && row.meta.isMenu !== false && !row.meta.activeMenu && row.path" type="success" icon="el-icon-picture-outline-round" size="mini" @click="handleEditIcon(row.ROUTE_ID)">图标</el-button>
          <el-button type="primary" icon="el-icon-edit-outline" size="mini" @click="fnAddRouter(row, '编辑')">编辑</el-button>
          <el-button v-if="row.component === 'children'" type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="fnAddRouter(row, '新增下级')">新增下级</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.ROUTE_ID, row.meta.title)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="60%"
      @close="dialog.visible = false">
      <el-form
        ref="formRef"
        :model="dialog.form"
        :rules="dialog.rules"
        label-position="top"
      >
        <el-form-item label="上级菜单" prop="parentMenuId">
          {{ dialog.form.parentName }}
        </el-form-item>
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="dialog.form.title" />
        </el-form-item>
        <el-form-item label="路由地址(从/开始)" prop="path">
          <el-input v-model="dialog.form.path" />
        </el-form-item>
        <el-form-item
          label="路由重定向地址(重定向到哪一个路由，子级路由第一个的路由地址，（没有子级路由不需要填写）)"
          prop="redirect"
        >
          <el-input v-model="dialog.form.redirect" />
        </el-form-item>
        <el-form-item
          label="文件位置(路由对应的组件位置（必填，views下的文件，views和.vue不需要填写，如果是children只需要填写children）)"
          prop="component"
        >
          <el-input v-model="dialog.form.component" />
        </el-form-item>
        <el-form-item
          label="model(归类到头部导航哪一级中（一级路由需要填写）)"
          prop="model"
        >
          <el-select v-model="dialog.form.model" clearable>
            <el-option
              v-for="item in MENU"
              :key="item.model"
              :label="item.title"
              :value="item.model"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限标识" prop="permissionId">
          <el-input v-model="dialog.form.permissionId" />
        </el-form-item>
        <el-form-item label="序号" prop="index">
          <el-input v-model.number="dialog.form.index" />
        </el-form-item>
        <el-form-item
          label="选中的菜单(当前路由选中状态是哪个导航（只有当父级路由或祖先级路由’当前菜单是否显示子菜单为否‘时需要填写，设置‘当前菜单是否显示子菜单为否’的路由地址）)"
          prop="activeMenu"
        >
          <el-input v-model="dialog.form.activeMenu" />
        </el-form-item>
        <el-form-item label="是否显示当前菜单" prop="isMenu">
          <el-select v-model="dialog.form.isMenu">
            <el-option :value="true" label="是" />
            <el-option :value="false" label="否" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否需要登录才可以访问" prop="isLogin">
          <el-select v-model="dialog.form.isLogin">
            <el-option :value="true" label="是" />
            <el-option :value="false" label="否" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前页是否显示在面包屑中" prop="breadcrumb">
          <el-select v-model="dialog.form.breadcrumb">
            <el-option :value="true" label="是" />
            <el-option :value="false" label="否" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前页是否显示面包屑" prop="isBreadcrumb">
          <el-select v-model="dialog.form.isBreadcrumb">
            <el-option :value="true" label="是" />
            <el-option :value="false" label="否" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="当前菜单是否显示子菜单(菜单有增删改查等等子路由的情况下需要勾选为否)"
          prop="isSubMenu"
        >
          <el-select v-model="dialog.form.isSubMenu">
            <el-option :value="true" label="是" />
            <el-option :value="false" label="否" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="iconDialog.visible"
      :close-on-click-modal="false"
      title="设置图标"
      width="40%"
      @close="iconDialog.visible = false">
      <div class="link">
        <a href="https://iconpark.oceanengine.com/official" target="_blank">
          点击此处
        </a>
        查看所有图标
      </div>
      <div>
        <el-form label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="图标名称">
                <el-input v-model="iconDialog.KEYWORDS" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="10px">
                <el-button type="primary" @click="fnSearchIcon">搜索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="icon_container">
        <template v-for="(item, index) in iconDialog.svgList">
          <el-tooltip :content="item.title" :key="index">
            <div
              :class="{ active: iconDialog.iconIndex === index }"
              class="item"
              @click="iconDialog.iconIndex = index"
            >
              <component
                :is="'icon-' + item.name"
                :stroke-width="3"
                theme="outline"
                fill="#a5b2c2"
                size="38"
              />
            </div>
          </el-tooltip>
        </template>
      </div>
      <pagination
        :total="iconDialog.pagination.total"
        :page.sync="iconDialog.pagination.currentPage"
        :limit.sync="iconDialog.pagination.pageSize"
        small
        layout="total, sizes, prev, pager, next, jumper"
        @pagination="fnSearchIcon" />
      <template #footer>
        <el-button type="primary" @click="confirmIcon">保存</el-button>
        <el-button @click="iconDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import icons from '@icon-park/vue/icons.json'
import { requestFN } from '@/utils/request'

export default {
  name: 'Icons',
  components: { Pagination },
  data() {
    return {
      activeName: '1',
      listLoading: false,			// 加载状态
      radio: 1,
      dialogType: 'add',
      // 列表
      varList: [],	// list
      ROUTE_ID: '0',	// 主键ID
      add: false,
      del: false,
      edit: false,
      MENU: [
        { title: '双重预防', model: 'prevention' },
        { title: '教育培训', model: 'educationAndTraining' },
        { title: '高危作业管理', model: 'highRisk' },
        { title: '监测预警', model: 'monitor' },
        { title: '综合管理', model: 'comprehensive' },
        { title: '定位管理', model: 'positioning' },
        //  东方石油专用
        { title: '企业管理-东方石油', model: 'dfPre' }
      ],
      dialog: {
        visible: false,
        title: '',
        form: {
          parentMenuId: '',
          parentName: '',
          parentIdS: '',
          title: '',
          path: '',
          redirect: '',
          component: '',
          model: '',
          permissionId: '',
          index: '',
          activeMenu: '',
          menuId: '',
          icon: '',
          isMenu: true,
          isLogin: true,
          breadcrumb: true,
          isBreadcrumb: true,
          isSubMenu: true
        },
        rules: {
          component: [
            { required: true, message: '请输入文件位置', trigger: 'blur' }
          ],
          index: [
            { required: true, message: '请输入序号', trigger: 'blur' },
            { type: 'number', message: '序号必须是数字', trigger: 'blur' }
          ]
        }
      },
      iconDialog: {
        visible: false,
        svgList: [],
        pagination: {
          currentPage: 1,
          pageSize: 50,
          total: icons.length
        },
        iconIndex: '',
        menuId: '',
        KEYWORDS: ''
      }
    }
  },
  created() {
    this.getList(this.ROUTE_ID)
    this.fnInitIcon()
  },
  methods: {
    indexMethod(index) {
      return index + 1
    },
    handleNodeClick(node, data, value) {
      this.handleEdit(node.id)
    },
    fnAddRouter(row, type) {
      this.resetForm()
      this.dialogType = 'add'
      if (type === '编辑') {
        this.dialogType = 'edit'
        this.dialog.form = {
          menuId: row.ROUTE_ID,
          index: +row.ROUTE_ORDER,
          permissionId: row.SHIRO_KEY,
          path: row.path,
          redirect: row.REDIRECT,
          component: row.component,
          parentMenuId: row.PARENT_ID,
          parentName: row.PARENT_NAME,
          parentIdS: row.PARENT_IDS,
          title: row.meta.title,
          model: row.meta.model,
          activeMenu: row.meta.activeMenu,
          isMenu: row.meta.isMenu,
          isLogin: row.meta.isLogin,
          breadcrumb: row.meta.breadcrumb,
          isBreadcrumb: row.meta.isBreadcrumb,
          isSubMenu: row.meta.isSubMenu,
          icon: row.meta.icon
        }
      } else if (type === '新增下级') {
        this.dialog.form.parentMenuId = row.ROUTE_ID
        this.dialog.form.parentName = row.meta.title
        this.dialog.form.parentIdS = (this.isEmpty(row.PARENT_IDS) ? ',' : row.PARENT_IDS) + row.ROUTE_ID + ','
        if (row.meta.isSubMenu === false) this.dialog.form.activeMenu = row.path
        else this.dialog.form.activeMenu = row.meta.activeMenu || ''
        if (row.children) {
          this.dialog.form.index = row.children.length + 1
        } else {
          this.dialog.form.index = 1
        }
      } else {
        this.dialog.form.parentMenuId = row.PARENT_ID === '0' ? '' : row.PARENT_ID
        this.dialog.form.parentName = '（无）'
        this.dialog.form.parentIdS = ''
        this.dialog.form.index = this.varList.length + 1
      }
      this.dialog.visible = true
      this.dialog.title = type
    },
    isEmpty(value) {
      return (
        value === undefined ||
        value === null ||
        (typeof value === 'object' && Object.keys(value).length === 0) ||
        (typeof value === 'string' && value.trim().length === 0)
      )
    },
    handleEdit(ROUTE_ID) {
      this.resetForm()
      this.dialogType = 'edit'
      requestFN(
        '/route/toEdit',
        {
          ROUTE_ID: ROUTE_ID
        }
      ).then((data) => {
        this.dialog.form = data.pd // copy obj
      }).catch((e) => {
        this.listLoading = false
      })
      this.dialog.visible = true
    },

    buttonList(ROUTE_ID) {
      this.$parent.ROUTE_ID = ROUTE_ID
      this.$parent.activeName = 'button'
    },
    confirm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.listLoading = true
          console.log(this.dialog.form)
          const meta = {
            title: this.dialog.form.title,
            model: this.dialog.form.model,
            activeMenu: this.dialog.form.activeMenu,
            isMenu: this.dialog.form.isMenu,
            isLogin: this.dialog.form.isLogin,
            breadcrumb: this.dialog.form.breadcrumb,
            isBreadcrumb: this.dialog.form.isBreadcrumb,
            isSubMenu: this.dialog.form.isSubMenu,
            icon: this.dialog.form.icon
          }
          const params = {
            NAME: this.dialog.form.title,
            PATH: this.dialog.form.path,
            PARENT_ID: this.dialog.form.parentMenuId || '0',
            PARENT_IDS: this.dialog.form.parentIdS,
            ROUTE_ORDER: this.dialog.form.index,
            COMPONENT: this.dialog.form.component,
            SHIRO_KEY: this.dialog.form.permissionId,
            REDIRECT: this.dialog.form.redirect,
            ROUTE_STATE: this.dialog.form.isMenu ? 1 : 0,
            SHOW_MODEL: this.dialog.form.model,
            META: JSON.stringify(meta)
          }
          requestFN(
            '/route/' + this.dialogType,
            {
              ...params,
              ROUTE_ID: this.dialog.form.menuId
            }
          ).then((data) => {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.listLoading = false
            this.dialog.visible = false
            this.getList()
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },
    handleDelete(id, name) {
      this.$confirm('确定要删除[' + name + ']吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/route/delete',
          {
            ROUTE_ID: id
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.getList(this.ROUTE_ID)
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    fnInitIcon() {
      this.iconDialog.pagination = {
        currentPage: 1,
        pageSize: 50,
        total: icons.length
      }
      this.iconDialog.svgList = this.paging(
        icons,
        this.iconDialog.pagination.currentPage,
        this.iconDialog.pagination.pageSize
      )
      console.log(this.iconDialog.svgList)
    },
    fnSearchIcon() {
      const { KEYWORDS } = this.iconDialog
      const filterIcons = icons.filter(
        (item) =>
          item.name.indexOf(KEYWORDS) !== -1 || item.title.indexOf(KEYWORDS) !== -1
      )
      this.iconDialog.svgList = this.paging(
        filterIcons,
        this.iconDialog.pagination.currentPage,
        this.iconDialog.pagination.pageSize
      )
      this.iconDialog.pagination.total = filterIcons.length
    },
    paging(list, currentPage, pageSize) {
      return list.filter((item, index) => {
        return (
          index < +currentPage * +pageSize &&
          index >= (+currentPage - 1) * +pageSize
        )
      })
    },

    handleEditIcon(ROUTE_ID) {
      this.iconDialog.visible = true
      this.iconDialog.iconIndex = ''
      this.ROUTE_ID = ROUTE_ID
    },
    confirmIcon() {
      this.listLoading = true
      console.log(this.iconDialog.iconIndex)
      console.log(this.iconDialog.svgList[this.iconDialog.iconIndex].name)
      requestFN(
        '/route/icon',
        {
          ROUTE_ID: this.ROUTE_ID,
          ICON: this.iconDialog.iconIndex !== ''
            ? this.iconDialog.svgList[this.iconDialog.iconIndex].name
            : ''
        }
      ).then((data) => {
        this.listLoading = false
        this.iconDialog.visible = false
        this.getList(this.ROUTE_ID)
      }).catch((e) => {
        this.listLoading = false
      })
    },
    generateIconCode(symbol) {
      return `<svg-icon icon-class="${symbol}" />`
    },
    getList(ROUTE_ID) {
      this.listLoading = true
      this.varList = []
      this.ROUTE_ID = ROUTE_ID
      requestFN(
        '/route/treeAll',
        {
          ROUTE_ID: this.ROUTE_ID
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.menuList
        this.hasButton()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    resetForm() {
      this.dialog.form = {
        parentMenuId: '',
        parentName: '',
        parentIdS: '',
        title: '',
        path: '',
        redirect: '',
        component: '',
        model: '',
        permissionId: '',
        index: '',
        activeMenu: '',
        menuId: '',
        isMenu: true,
        isLogin: true,
        breadcrumb: true,
        isBreadcrumb: true,
        isSubMenu: true
      }
    },
    hasButton: function() {
      var keys = 'menu:add,menu:del,menu:edit'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.menufhadminadd
        this.del = data.menufhadmindel
        this.edit = data.menufhadminedit
      }).catch((e) => {
        this.listLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.link{
  margin-bottom: 10px;
  a{
    color: #409EFF;
  }
}
  .icon_container {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 10px;

    .item {
      flex-basis: calc(10% - 13px);
      border: 1px solid #ccc;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 10px;
      margin-right: 13px;
      padding: 10px;
      cursor: pointer;
      box-sizing: border-box;

      &:nth-child(10n) {
        margin-right: 0;
      }

      &:hover,
      &.active {
        border: 1px solid #79bbff;
      }
    }
  }
</style>
