<template>
    <div class="menus-container">
      <el-tree :data="menus" node-key="identifier" :expand-on-click-node="true">
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ data.title }}</span>
            <span>
              <el-button type="primary" text :disabled="node.level === 4" :icon="Plus"
                :title="node.level === 4 ? '菜单最多添加三级' : '增加'" v-if="checkPermission(['menuManage:add'])"
                @click.stop="handleAddMenu(data)" />
              <el-button type="danger" text :icon="Minus" :title="$t('delete')" v-if="checkPermission(['menuManage:del'])"
                @click.stop="handleDeleteMenu(node, data)" />
              <el-button type="primary" text :icon="Edit" :title="$t('edit')" v-if="checkPermission(['menuManage:edit'])"
                @click.stop="handleEditMenu(data)" />
            </span>
          </span>
        </template>
      </el-tree>
      <el-button v-if="menus" text style="margin-top: 10px; margin-left: 20px"
        @click="handleAddMenu('')">{{$t('add_top_menu')}}</el-button>
      <el-dialog :title="menuForm.menu_name ? $t('edit_menu') : $t('add_menu')" v-model="dialogMenuVisible" width="500px" class="!rounded-lg"
        :close-on-click-modal="false" :close-on-press-escape="false" @close="closeMenuForm">
        <el-form :model="menuForm" :rules="menuRules" ref="menuFormRef" label-width="100px">
          <el-form-item :label="$t('menu_title')" prop="title">
            <el-input v-model="menuForm.title"></el-input>
          </el-form-item>
          <el-form-item :label="$t('menu_identifier')" prop="identifier">
            <el-input v-model="menuForm.identifier"></el-input>
          </el-form-item>
          <el-form-item :label="$t('menu_auth_regular')" prop="auth_regular">
            <el-input v-model="menuForm.auth_regular" type="textarea"></el-input>
          </el-form-item>
          <el-form-item :label="$t('menu_icon')" prop="icon" v-if="iconShow!=='0'">
            <el-upload class="site-logo" :action="MixinUploadApi" :show-file-list="false"
              :on-success="(res) => { menuForm.icon = res.url }" :multiple="false">
              <img v-if="menuForm.icon" :src="menuForm.icon" class="site-logo-img">
              <el-icon v-else><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item :label="$t('menu_show_home')" prop="show_home" v-if="iconShow !== '0' && checkPermission(['UserMenu:get'])">
            <el-switch v-model="menuForm.show_home" :active-value="1" :inactive-value="2" @change="switchVal"></el-switch>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeMenuForm">{{$t('cancel')}}</el-button>
            <el-button type="primary" @click="submitMenuForm('menuFormRef')">{{$t('submit')}}</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Minus, Edit } from '@element-plus/icons-vue'
  import * as API_Menus from '@/api/menus'
  import { useI18n } from 'vue-i18n';
const { t } = useI18n();

  const MixinUploadApi=ref(import.meta.env.VITE_API_URL + '/uploaders')
  const menus = ref<any[]>([]);
  const menuForm = ref<any>({
    parent_id: 0,
    menu_name:""
  })
  const menuRules = reactive({
    title: [
      { required: true, message:t('place')+t('menu_title')+'!', trigger: 'blur' }
    ],
    identifier: [
      { required: true, message:t('place')+t('menu_identifier')+'!', trigger: 'blur' }
    ],
    auth_regular: [
      { required: true, message:t('place')+t('menu_auth_regular')+'!', trigger: 'blur' }
    ],
  })
  
  const dialogMenuVisible = ref(false)
  const currentMenu = ref('')
  const iconShow = ref('')
  const itemMenu = ref<any>({})
  const menuFormRef = ref()
  
  const closeMenuForm = () => {
    dialogMenuVisible.value = false
    itemMenu.value = {}
  }
  
  const switchVal = (val) => {
    if (menuForm.value.menu_name === "编辑菜单") {
      if (val === 1) {
        // API_Menus.editHomeMenu({menu_id:''})
      } else if (val === 2) {
        // API_Menus.deleteHomeMenu({})
      }
    }
  }
  
  const handleAddMenu = (menu) => {
    if (menu === "") {
      iconShow.value = '0'
    }
    Object.assign(menuForm, {
      parent_id: menu ? menu.id : 0
    })
    currentMenu.value = menu || {}
    dialogMenuVisible.value = true
  }
  
  const handleDeleteMenu = (node, menu) => {
    ElMessageBox.confirm(t('menu_delet_info'),t('prompt'), { type: 'warning' })
      .then(() => {
        API_Menus.deleteMenu(menu.id).then(() => {
          const parent = node.parent
          const children = parent.data.children || parent.data
          const index = children.findIndex(d => d.id === menu.id)
          children.splice(index, 1)
        })
      })
      .catch(() => { })
  }
  
  const handleEditMenu = (menu) => {
    Object.assign(menuForm, JSON.parse(JSON.stringify(menu)))
    itemMenu.value = menuForm
    iconShow.value = menu.parent_id
    currentMenu.value = menu
    menuForm.value.menu_name = '编辑菜单'
    dialogMenuVisible.value = true
  }
  
  const submitMenuForm = (formName) => {
    menuFormRef.value.validate((valid) => {
      if (valid) {
        const { id } = menuForm.value
        if (id) {
          API_Menus.editMenu(id, menuForm.value).then(response => {
            dialogMenuVisible.value = false
            ElMessage.success(t('sub_success'))
            GET_Memus()
          })
        } else {
          API_Menus.addMenu(menuForm.value).then((response:any) => {
            const data:any = currentMenu.value
            if (menuForm.value.parent_id === 0) {
              menus.value.push(response)
            } else {
              if (!data.children) data.children = []
              data.children.push(response)
            }
            dialogMenuVisible.value = false
            ElMessage.success(t('sub_success'))
          })
        }
      } else {
        ElMessage.error(t('form_erroe'))
        return false
      }
    })
  }
  
  const GET_Memus = () => {
    API_Menus.getMenusChildren().then(response => {
      menus.value = response
    })
  }
  
  const checkPermission = (permissions) => {
    // 实现权限检查逻辑
    return true
  }
  
  onMounted(() => {
    GET_Memus()
  })
  </script>
  
  <style scoped>
  .menus-container {
    padding: 10px;
    background-color: #fff;
  }
  
  .menus-container :deep(.el-tree) {
    width: 500px;
  }
  
  .menus-container :deep(.el-icon-minus) {
    color: #F56C6C;
  }
  
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  
  .site-logo-img {
    width: 50px;
    height: 50px;
  }
  </style>