<template>
  <div class="page-menu-wrap">

    <div class="vue-element-page-wrap" ref="tableContainer">
      <el-row class="page-search" justify="space-between" align="middle">
        <!-- <el-row :gutter="20">
          <div class="page-table-operate">
            <span>更新时间：{{ currentTime }}</span>
          </div>
        </el-row> -->
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="" prop="params.code">
                <CustomInput v-model:params="queryParams.menuName" placeholder="请输入菜单名" clearable
                  @keyUpEvent="handleQuery" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="page-search-btns">
          <el-button type="primary" @click="openAddDialog">新增</el-button>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
        </div>
      </el-row>

      <div class="vue-element-page-table">
        <div class="tree">
          <el-tree :data="state.pageList" v-loading="state.loading" node-key="menuName"
            :default-expanded-keys="defaultExpand">
            <template #default="{ data }">
              <div class="custom-tree-node">
                <span v-if="data.platform != 'APP'">{{ data.menuName }}</span>
                <span v-else>{{ data.menuName }} (APP)</span>
                <span style="padding-left:20px">
                  <el-button v-if="!data.leafFlag" :disabled="data.platform == 'APP'" :icon="'Plus'" circle @click.stop="openAddDialog(data)" />
                  <el-button :icon="'EditPen'" :disabled="data.platform == 'APP'" circle @click.stop="openEditDialog(data)" />
                  <el-button :icon="'Delete'" :disabled="data.platform == 'APP'" circle @click.stop="delItem(data)" />
                </span>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
      <!--  新增或编辑页面  -->
      <el-drawer :title="dialog.title" :close-on-click-modal="false" v-model="dialog.visible" @close="cancel"
        @opened="dialogOpend">
        <el-form ref="formDataRef" :model="formData" :rules="rules" label-position="top">
          <el-form-item label="页面类型" prop="leafFlag">
            <el-radio-group v-model="formData.leafFlag">
              <el-radio :label="0">菜单</el-radio>
              <el-radio :label="1">页面</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="平台" prop="platform">
            <el-radio-group v-model="formData.platform">
              <el-radio :label="'PC'">PC</el-radio>
              <!-- <el-radio :label="'APP'">APP</el-radio> -->
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="typeName + 'ID'" prop="id" v-if="!state.selectItem">
            <el-input v-model="formData.id" placeholder="请输入ID" />
          </el-form-item>
          <el-form-item :label="typeName + '名称'" prop="menuName">
            <el-input v-model="formData.menuName" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="路由路径" prop="routePath">
            <el-input v-model="formData.routePath" placeholder="请输入页面地址" />
          </el-form-item>

          <el-form-item label="组件路径" prop="componentPath" v-if="formData.leafFlag">
            <el-input v-model="formData.componentPath" placeholder="请输入页面地址" />
          </el-form-item>
          <el-form-item label="显示菜单" prop="hiddenFlag">
            <el-radio-group v-model="formData.hiddenFlag">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="缓存" prop="cacheFlag" v-if="formData.leafFlag">
            <el-radio-group v-model="formData.cacheFlag">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- TODO: 排序暂时不加 -->
          <!-- <el-form-item label="排序号" prop="seq">
            <el-input-number style="width: 100%;" v-model="formData.seq" :min="1" controls-position="right" />
          </el-form-item> -->
        </el-form>

        <template #footer>
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </template>
      </el-drawer>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'menuInfo'
};
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, watch, computed } from 'vue';
import { ElForm, ElMessageBox, ElTree } from 'element-plus';
import {
  updateMenu,
  addMenu,
  delMenu
} from '@/api/menu';
import { getMenu } from '@/api/menu';
import useStore from "@/store";

const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();
const { app } = useStore();

interface Tree {
  label: string
  children?: Tree[]
}

const defaultProps = {
  children: 'children',
  menuName: 'menuName',
}

const state = reactive({
  pageList: [] as any,
  dialog: {
    title: '新增',
    visible: false,
    type: ''
  },
  loading: false as boolean,
  queryParams: {
    menuName: ''
  },
  formData: {
    leafFlag: 1,
    id: '',
    menuName: '',
    routePath: '',
    platform: 'PC'
  } as any,
  selectItem: undefined as any,// 选中的页面项
  rules: {
    id: [{ required: true, message: '请输入ID', trigger: 'blur' }],
    menuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
    routePath: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
    componentPath: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
  },
  currentTime: '',
  parentId: null,
  defaultExpand: [] as any
})
const {
  dialog,
  formData,
  rules,
  currentTime,
  defaultExpand,
  queryParams
} = toRefs(state);

const typeName = computed(() => {
  if (formData.value.type == 1) {
    return '页面'
  } else {
    return '菜单'
  }
});

onMounted(() => {

  handleQuery();
});

/**
 * 点击搜索按钮查询
 * */
async function handleQuery() {
  state.loading = true
  await getMenu({
    queryId: "GetHierarchicalMenuList",
    version: "sdk001",
    params: {
      USERID: localStorage.getItem('userId')
    }
  })
    .then((res: any) => {
      state.pageList = getChildrenNode(res.data.menuList);
      state.defaultExpand = getDefaultExpand();
      // showCurrentTime();
    })
    .catch(() => { });
  state.loading = false
}

function getDefaultExpand() {
  const arr: any[] = [];
  let str = state.queryParams.menuName
  if (str) {
    execGetDefalut(state.pageList, arr, str)
  }
  return arr
}
function execGetDefalut(list: any, arr: any, str: any) {
  list.map((item: any) => {
    if (item.parentId !== 'root' && item.menuName.includes(str)) {
      arr.push(item.menuName);
    }
    if (item.children) {
      execGetDefalut(item.children, arr, str)
    }
  })
}

/**
 * @function 递归获取子节点
 * @param dataList
 * */
function getChildrenNode(dataList: any) {
  const tempArr: any = [];
  dataList.forEach((item: any) => {
    let obj = {
      menuName: item.menuName,
      id: item.id,
      leafFlag: item.leafFlag,
      cacheFlag: item.cacheFlag,
      componentPath: item.componentPath,
      hiddenFlag: item.hiddenFlag,
      platform: item.platform,
      routePath: item.routePath,
      parentId: item.parentId,
    } as any;
    if (item.children && item.children.length > 0) {
      obj.children = getChildrenNode(item.children)
    }
    tempArr.push(obj);
  })
  return tempArr;
}
/**
 * @function
 * 获取时间
 * */
function showCurrentTime() {
  let date = new Date()
  state.currentTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ":" +
    (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
}

/**
 * 新增页面 dialog
 */
function openAddDialog(data: any) {
  state.selectItem = null;
  state.parentId = data.id || null
  dialog.value = {
    title: '新增',
    type: 'add',
    visible: true
  };
}
/**
 * 编辑页面 dialog
 */
function openEditDialog(row: any) {
  state.dialog = {
    title: '编辑',
    type: 'edit',
    visible: true
  };
  state.selectItem = row;
}
/**
 * 新增/修改菜单
 */
function submitForm() {
  formDataRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (state.selectItem) {// 编辑
        let params = {
          dataId: state.selectItem.dataId,
          ...state.formData
        }
        updateMenu(params).then(() => {
          proxy.$ElMessage.success('修改成功');
          cancel();
          handleQuery();
        });
      } else {
        let data = { ...state.formData, parentId: state.parentId }
        addMenu(data).then(() => {
          proxy.$ElMessage.success('新增成功');
          cancel();
          handleQuery();
        });
      }
    }
  });
}


/**
 * 删除菜单
 */
function delItem(row: any) {
  console.log(row)
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      delMenu({
        id: row.id
      }).then(() => {
        proxy.$ElMessage.success('删除成功');
        cancel();
        handleQuery();
      });
    })
    .catch(() => {

    })
}



function dialogOpend() {
  formDataRef.value.resetFields();
  state.formData.id = '';
  if (state.selectItem && state.dialog.type === 'edit') {
    state.formData = {
      id: state.selectItem.id,
      menuName: state.selectItem.menuName,
      routePath: state.selectItem.routePath,
      componentPath: state.selectItem.componentPath,
      parentId: state.selectItem.parentId,
      leafFlag: state.selectItem.leafFlag,
      cacheFlag: state.selectItem.cacheFlag,
      platform: state.selectItem.platform,
      hiddenFlag: state.selectItem.hiddenFlag,
    }
  }
}

/**
 * 取消关闭弹窗
 */
function cancel() {
  state.dialog.visible = false;
}


</script>
<style scoped lang="scss">
@import './index.scss';
</style>
