<template>
  <div id="index">
    <el-row>
      <el-col :span="24" style="text-align: right; padding: 10px">
        <el-button type="primary" size="small" @click="toAdd">添加</el-button>
      </el-col>
      <el-col :span="24">
        <el-table :data="list" row-key="_id" border>
          <el-table-column align="center" label="菜单名称" prop="name"></el-table-column>
          <el-table-column align="center" label="父级菜单" prop="parent_name"></el-table-column>
          <el-table-column align="center" label="图标" width="80">
            <template #default="{ row }"><span :class="['iconfont', row.icon]"></span></template>
          </el-table-column>
          <el-table-column align="center" label="顺序" sortable prop="order_num" width="80"></el-table-column>
          <el-table-column align="center" label="路由地址" prop="path"></el-table-column>
          <el-table-column align="center" label="组件地址" prop="component"></el-table-column>
          <el-table-column align="center" label="菜单类型" prop="type">
            <template #default="{ row }">{{ getType(row) }} </template>
          </el-table-column>
          <el-table-column align="center" label="状态" prop="status" width="50">
            <template #default="{ row }">{{ getStatus(row) }} </template>
          </el-table-column>
          <el-table-column align="center" label="备注" prop="remark"> </el-table-column>
          <el-table-column align="center" label="操作">
            <template #default="{ row }">
              <el-link :underline="false" type="primary" size="mini" @click="toUpdate(row)" style="margin-right: 10px">修改</el-link>
              <el-link :underline="false" type="primary" size="mini" @click="toAddNext(row)" style="margin-right: 10px">添加下一级</el-link>
              <el-link :underline="false" type="danger" size="mini" @click="toDelete(row)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="dialog" title="菜单信息" :destroy-on-close="false" @close="toClose">
      <el-tabs v-model="tab" type="card">
        <el-tab-pane label="基本信息" name="basic">
          <el-form label-position="left" label-width="120px">
            <el-form-item label="菜单名称">
              <el-input v-model="form.name" placeholder="请填写菜单名称"></el-input>
            </el-form-item>
            <el-form-item label="菜单类型">
              <el-select v-model="form.type" placeholder="请选择菜单类型">
                <el-option v-for="(i, index) in typeList" :key="`t${index}`" :label="i.label" :value="i.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="父级菜单">
              <el-select v-model="form.parent_id" placeholder="" :disabled="true">
                <el-option v-for="(i, index) in getOneDimensionList()" :key="`m${index}`" :label="i.name" :value="i._id"></el-option>
              </el-select>
            </el-form-item>
            <template v-if="form.type === '1' || form.type === '2'">
              <el-form-item label="路由地址">
                <el-input v-model="form.path" placeholder="请填写路由地址"></el-input>
              </el-form-item>
              <el-form-item label="组件地址">
                <el-input v-model="form.component" placeholder="请填写组件地址"></el-input>
              </el-form-item>
            </template>
            <el-form-item label="顺序">
              <el-input-number v-model="form.order_num"></el-input-number>
            </el-form-item>
            <el-form-item label="图标">
              <el-select v-model="form.icon" clearable filterable placeholder="请选择图标">
                <el-option v-for="item in iconList" :key="item.dict_label" :label="item.dict_label" :value="item.dict_label">
                  <span style="float: left" :class="['iconfont', item.dict_label]"></span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dict_label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio label="0">使用</el-radio>
                <el-radio label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :autosize="{ minRows: 5, maxRows: 5 }"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="设置" name="config" v-if="form.type && form.type !== '0'">
          <el-row>
            <el-col :span="24" style="text-align: right; margin: 10px 0">
              <el-button size="mini" type="primary" @click="toAddConfig()">添加功能</el-button>
            </el-col>
            <el-col :span="24">
              <el-table :data="form.config">
                <el-table-column align="center" label="中文">
                  <template #default="{ row }">
                    <el-input v-model="row.zh"></el-input>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="code">
                  <template #default="{ row }">
                    <el-input v-model="row.code"></el-input>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作">
                  <template #default="{ $index }">
                    <el-button size="mini" type="danger" @click="deleteConfig($index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <el-row type="flex" justify="space-around" style="margin-top: 10px">
        <el-col :span="6">
          <el-button @click="toSave" size="small" type="primary">保存</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
const _ = require('lodash');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: maM } = createNamespacedHelpers('menus');
// const { mapActions: sysdictdata } = createNamespacedHelpers('dictData');

export default {
  name: 'index',
  props: {},
  components: {},
  data: function () {
    return {
      list: [],
      form: {},
      dialog: false,
      typeList: [
        { label: '目录', value: '0' },
        { label: '菜单', value: '1' },
        { label: '子页面', value: '2' },
      ],
      // 图标列表
      iconList: [],
      tab: 'basic',
    };
  },
  async created() {
    this.searchOther();
    this.search();
    await this.initRouter();
  },
  methods: {
    // ...sysdictdata({ sQuery: 'query' }),
    ...maM(['query', 'create', 'update', 'delete']),
    async search() {
      let res = await this.query();
      if (this.$checkRes(res)) {
        this.$set(this, `list`, res.data);
      }
    },
    toAdd() {
      this.dialog = true;
      this.form = { config: [] };
    },
    toUpdate(row) {
      if (!row.config) row.config = [];
      this.$set(this, `form`, _.cloneDeep(row));
      this.dialog = true;
    },
    toAddNext(row) {
      const obj = { parent_id: row._id };
      this.$set(this, `form`, obj);
      this.dialog = true;
    },
    async toSave() {
      const data = _.cloneDeep(this.form);
      let res;
      if (data._id) res = await this.update(data);
      else res = await this.create(data);
      if (this.$checkRes(res, '操作成功', '操作失败')) {
        this.toClose();
        this.search();
      }
    },
    async toDelete(row) {
      this.$confirm('删除该菜单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let res = await this.delete(row._id);
          if (this.$checkRes(res, '删除成功', '删除失败')) {
            this.search();
          }
        })
        .catch(() => {});
    },
    toClose() {
      this.form = {};
      this.tab = 'basic';
      this.dialog = false;
    },
    getType(row) {
      let word = '';
      const r = this.typeList.find((f) => f.value === row.type);
      if (r) word = r.label;
      return word;
    },
    getStatus(row) {
      let word = '';
      switch (row.status) {
        case '0':
          word = '使用';
          break;
        case '1':
          word = '禁用';
          break;

        default:
          break;
      }
      return word;
    },
    // 获取一维(平面)的菜单数据
    getOneDimensionList() {
      let dup = _.cloneDeep(this.list);
      let arr = this.getAllChild(dup);
      return arr;
    },
    // 获取所有的子菜单
    getAllChild(children) {
      let arr = [];
      for (const i of children) {
        const { children, ...others } = i;
        arr.push(others);
        if (children) {
          const marr = this.getAllChild(children);
          arr.push(...marr);
        }
      }
      return arr;
    },

    async initRouter() {
      // const obj = {
      //   path: '/adminCenter/homeIndex',
      //   name: 'adminCenter',
      //   component: (resolve) => require([`@common/src/components/admin-frame/Home.vue`], resolve),
      //   children: [{ path: '/system/user', meta: { title: '用户管理' }, component: this.loadView('/system/user/index') }],
      // };
      // console.log(obj);
      // router.addRoute(obj);
    },
    loadView(view) {
      // 路由懒加载
      return (resolve) => require([`@/views${view}.vue`], resolve);
    },
    // 查询其他信息
    async searchOther() {
      // let res = await this.sQuery({ dict_type: 'info_icon' });
      // if (this.$checkRes(res)) {
      //   this.$set(this, `iconList`, res.data);
      // }
    },

    toAddConfig() {
      this.form.config.push({});
    },
    deleteConfig(index) {
      this.form.config.splice(index, 1);
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  watch: {
    test: {
      deep: true,
      immediate: true,
      handler(val) {},
    },
  },
};
</script>

<style lang="less" scoped></style>
