<template>
  <view class="container" style="paddingBottom:1rpx;">
    <view class="section">
      <view class="section-title">{{ title }}</view>
      <view class="form-view">
        <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" labelWidth="140rpx"
          :labelStyle="{ color: '#333333', fontSize: '30rpx' }">
          
          <u-form-item label="上级菜单" prop="parentName" @click="showParentPicker = true">
            <view class="input-with-arrow">
              <u--input v-model="parentName" disabled disabledColor="#ffffff" placeholder="请选择上级菜单"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

          <u-form-item label="菜单类型" prop="menuTypeName" @click="showMenuTypePicker = true">
            <view class="input-with-arrow">
              <u--input v-model="menuTypeName" disabled disabledColor="#ffffff" placeholder="请选择菜单类型"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

          <u-form-item label="菜单名称" prop="menuName" required>
            <u--input v-model="form.menuName" placeholder="请输入菜单名称" maxlength="50"
              inputAlign="left" :customStyle="getInputStyle('menuName')"></u--input>
          </u-form-item>

          <u-form-item label="显示排序">
            <u-number-box v-model="form.orderNum" :min="0" :max="999" inputAlign="right"></u-number-box>
          </u-form-item>

          <u-form-item label="路由地址" v-if="form.menuType !== 'F'">
            <u--input v-model="form.path" placeholder="请输入路由地址" maxlength="200"
              inputAlign="left" :customStyle="getInputStyle('path')"></u--input>
          </u-form-item>

          <u-form-item label="组件路径" v-if="form.menuType === 'C'">
            <u--input v-model="form.component" placeholder="请输入组件路径" maxlength="255"
              inputAlign="left" :customStyle="getInputStyle('component')"></u--input>
          </u-form-item>

          <u-form-item label="权限标识" v-if="form.menuType !== 'M'">
            <u--input v-model="form.perms" placeholder="请输入权限标识" maxlength="100"
              inputAlign="left" :customStyle="getInputStyle('perms')"></u--input>
          </u-form-item>

          <u-form-item label="是否外链" v-if="form.menuType !== 'F'" @click="showFramePicker = true">
            <view class="input-with-arrow">
              <u--input v-model="frameName" disabled disabledColor="#ffffff" placeholder="请选择"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

          <u-form-item label="是否缓存" v-if="form.menuType === 'C'" @click="showCachePicker = true">
            <view class="input-with-arrow">
              <u--input v-model="cacheName" disabled disabledColor="#ffffff" placeholder="请选择"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

          <u-form-item label="显示状态" v-if="form.menuType !== 'F'" @click="showVisiblePicker = true">
            <view class="input-with-arrow">
              <u--input v-model="visibleName" disabled disabledColor="#ffffff" placeholder="请选择"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

          <u-form-item label="菜单状态" prop="statusName" @click="showStatusPicker = true">
            <view class="input-with-arrow">
              <u--input v-model="statusName" disabled disabledColor="#ffffff" placeholder="请选择状态"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

        </u--form>
        <view class="form-btn">
          <u-button type="primary" text="提交" @click="submit"></u-button>
        </view>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
    
    <!-- 上级菜单选择器 -->
    <u-picker itemHeight="88" :show="showParentPicker" :columns="parentList" keyName="menuName" 
      @cancel="showParentPicker = false" @confirm="handleParentConfirm"></u-picker>
    
    <!-- 菜单类型选择器 -->
    <u-picker itemHeight="88" :show="showMenuTypePicker" :columns="menuTypeList" keyName="label" 
      @cancel="showMenuTypePicker = false" @confirm="handleMenuTypeConfirm"></u-picker>
    
    <!-- 是否外链选择器 -->
    <u-picker itemHeight="88" :show="showFramePicker" :columns="frameList" keyName="label" 
      @cancel="showFramePicker = false" @confirm="handleFrameConfirm"></u-picker>
    
    <!-- 是否缓存选择器 -->
    <u-picker itemHeight="88" :show="showCachePicker" :columns="cacheList" keyName="label" 
      @cancel="showCachePicker = false" @confirm="handleCacheConfirm"></u-picker>
    
    <!-- 显示状态选择器 -->
    <u-picker itemHeight="88" :show="showVisiblePicker" :columns="visibleList" keyName="dictLabel" 
      @cancel="showVisiblePicker = false" @confirm="handleVisibleConfirm"></u-picker>
    
    <!-- 菜单状态选择器 -->
    <u-picker itemHeight="88" :show="showStatusPicker" :columns="statusList" keyName="dictLabel" 
      @cancel="showStatusPicker = false" @confirm="handleStatusConfirm"></u-picker>
  </view>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue'
import { getMenu, addMenu, updateMenu, treeselect } from '@/api/system/menu'
import { getDicts } from "@/api/system/dict/data"
import { onLoad } from "@dcloudio/uni-app"

const { proxy } = getCurrentInstance()
const title = ref('添加菜单')
const parentList = ref([])
const menuTypeList = ref([[
  { label: '目录', value: 'M' },
  { label: '菜单', value: 'C' },
  { label: '按钮', value: 'F' }
]])
const frameList = ref([[
  { label: '是', value: '0' },
  { label: '否', value: '1' }
]])
const cacheList = ref([[
  { label: '缓存', value: '0' },
  { label: '不缓存', value: '1' }
]])
const visibleList = ref([])
const statusList = ref([])

const showParentPicker = ref(false)
const showMenuTypePicker = ref(false)
const showFramePicker = ref(false)
const showCachePicker = ref(false)
const showVisiblePicker = ref(false)
const showStatusPicker = ref(false)

const parentName = ref('顶级菜单')
const menuTypeName = ref('目录')
const frameName = ref('否')
const cacheName = ref('缓存')
const visibleName = ref('')
const statusName = ref('')

const form = reactive({
  menuId: undefined,
  parentId: 0,
  menuName: undefined,
  menuType: 'M',
  orderNum: 0,
  path: undefined,
  component: undefined,
  perms: undefined,
  isFrame: '1',
  isCache: '0',
  visible: '0',
  status: '0'
})

// 表单验证错误字段
const errorFields = ref([])

// 输入框基础样式
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '60rpx',
  lineHeight: '60rpx',
  width: '100%',
  boxSizing: 'border-box'
}

// 输入框错误样式
const inputErrorStyle = {
  background: '#fef0f0',
  border: '2rpx solid #f56c6c',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '60rpx',
  lineHeight: '60rpx',
  width: '100%',
  boxSizing: 'border-box'
}

// 根据字段名获取输入框样式
const getInputStyle = (field) => {
  return errorFields.value.includes(field) ? inputErrorStyle : inputBaseStyle
}

const rules = {
  menuName: [
    { required: true, message: '菜单名称不能为空', trigger: ['blur', 'change'] }
  ]
}

onLoad((option) => {
  // 获取字典
  getDicts('sys_show_hide').then(res => {
    visibleList.value = [res.data]
  })
  getDicts('sys_normal_disable').then(res => {
    statusList.value = [res.data]
  })
  
  // 获取菜单树
  getMenuTree()

  if (option.id) {
    title.value = '修改菜单'
    getDetail(option.id)
  } else if (option.parentId) {
    form.parentId = parseInt(option.parentId)
  } else {
    setTimeout(() => {
      updateAllNames()
    }, 100)
  }
})

// 获取菜单树
function getMenuTree() {
  treeselect().then(res => {
    const tree = res.data || []
    const flatList = flattenMenuTree(tree)
    parentList.value = [[{ menuId: 0, menuName: '顶级菜单' }, ...flatList]]
  })
}

// 扁平化菜单树
function flattenMenuTree(tree, result = [], level = 0) {
  tree.forEach(item => {
    let prefix = ''
    if (level === 1) {
      prefix = '　└─ '
    } else if (level > 1) {
      prefix = '　'.repeat(level) + '└─ '
    }
    result.push({
      menuId: item.id,
      menuName: prefix + item.label,
      originalName: item.label,
      level: level
    })
    if (item.children && item.children.length > 0) {
      flattenMenuTree(item.children, result, level + 1)
    }
  })
  return result
}

// 获取详情
function getDetail(id) {
  getMenu(id).then(res => {
    Object.assign(form, res.data)
    updateAllNames()
  })
}

// 更新所有显示名称
function updateAllNames() {
  updateParentName()
  updateMenuTypeName()
  updateFrameName()
  updateCacheName()
  updateVisibleName()
  updateStatusName()
}

// 更新上级菜单名称
function updateParentName() {
  if (form.parentId === 0) {
    parentName.value = '顶级菜单'
  } else {
    const flatList = parentList.value[0] || []
    const parent = flatList.find(item => item.menuId === form.parentId)
    parentName.value = parent ? parent.originalName || parent.menuName : '顶级菜单'
  }
}

// 更新菜单类型名称
function updateMenuTypeName() {
  const types = { 'M': '目录', 'C': '菜单', 'F': '按钮' }
  menuTypeName.value = types[form.menuType] || '目录'
}

// 更新是否外链名称
function updateFrameName() {
  frameName.value = form.isFrame === '0' ? '是' : '否'
}

// 更新是否缓存名称
function updateCacheName() {
  cacheName.value = form.isCache === '0' ? '缓存' : '不缓存'
}

// 更新显示状态名称
function updateVisibleName() {
  const list = visibleList.value[0] || []
  const item = list.find(v => v.dictValue === form.visible)
  visibleName.value = item ? item.dictLabel : ''
}

// 更新菜单状态名称
function updateStatusName() {
  const list = statusList.value[0] || []
  const item = list.find(v => v.dictValue === form.status)
  statusName.value = item ? item.dictLabel : ''
}

// 上级菜单确认
function handleParentConfirm(e) {
  const item = e.value[0]
  form.parentId = item.menuId
  parentName.value = item.originalName || item.menuName
  showParentPicker.value = false
}

// 菜单类型确认
function handleMenuTypeConfirm(e) {
  const item = e.value[0]
  form.menuType = item.value
  menuTypeName.value = item.label
  showMenuTypePicker.value = false
}

// 是否外链确认
function handleFrameConfirm(e) {
  const item = e.value[0]
  form.isFrame = item.value
  frameName.value = item.label
  showFramePicker.value = false
}

// 是否缓存确认
function handleCacheConfirm(e) {
  const item = e.value[0]
  form.isCache = item.value
  cacheName.value = item.label
  showCachePicker.value = false
}

// 显示状态确认
function handleVisibleConfirm(e) {
  const item = e.value[0]
  form.visible = item.dictValue
  visibleName.value = item.dictLabel
  showVisiblePicker.value = false
}

// 菜单状态确认
function handleStatusConfirm(e) {
  const item = e.value[0]
  form.status = item.dictValue
  statusName.value = item.dictLabel
  showStatusPicker.value = false
}

// 提交
function submit() {
  errorFields.value = [] // 清空错误字段
  proxy.$refs.uForm.validate().then(() => {
    if (form.menuId) {
      updateMenu(form).then(() => {
        proxy.$modal.msgSuccess('修改成功')
        setTimeout(() => {
          uni.navigateTo({ url: `/pages_mine/pages/system/menu/list` })
        }, 1500)
      })
    } else {
      addMenu(form).then(() => {
        proxy.$modal.msgSuccess('新增成功')
        setTimeout(() => {
          uni.navigateTo({ url: `/pages_mine/pages/system/menu/list` })
        }, 1500)
      })
    }
  }).catch((errors) => {
    // 记录验证失败的字段
    if (errors && Array.isArray(errors)) {
      errorFields.value = errors.map(err => err.field || err.prop)
    }
    proxy.$modal.msgError('请填写完整信息')
  })
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
}

.section {
  margin: 24rpx;
  padding: 0;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .section-title {
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;
    line-height: 1.2;
    font-size: 28rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      width: 6rpx;
      height: 28rpx;
      background: #ffffff;
      border-radius: 3rpx;
      margin-right: 12rpx;
    }
  }

  .form-view {
    padding: 24rpx;

    .form-btn {
      padding-top: 16rpx;
    }
    
    .input-with-arrow {
      position: relative;
      width: 100%;
      
      .arrow-icon {
        position: absolute;
        right: 20rpx;
        top: 50%;
        transform: translateY(-50%);
        color: #c0c4cc;
        font-size: 20rpx;
        pointer-events: none;
        z-index: 10;
      }
    }
  }
}

.select-input-wrapper {
  position: relative;
  
  .select-arrow {
    position: absolute;
    right: 24rpx;
    top: 50%;
    transform: translateY(-50%);
    color: #c0c4cc;
    font-size: 28rpx;
    pointer-events: none;
  }
}
</style>

<style lang="scss">
.form-btn .u-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border: none !important;
  border-radius: 24rpx !important;
  height: 80rpx !important;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4) !important;
}

.form-btn .u-button__text {
  font-size: 30rpx !important;
  font-weight: 500 !important;
  letter-spacing: 2rpx !important;
}

/* 统一输入框高度和行高 */
.u--input,
.u-input__content__field-wrapper {
  height: 60rpx !important;
  line-height: 60rpx !important;
  min-height: 60rpx !important;
  box-sizing: border-box !important;
}

.u-form-item__body {
  flex: 1 !important;
}

.u-form-item__body .u--input {
  width: 100% !important;
  box-sizing: border-box !important;
}

.u-input__content__field-wrapper__field {
  line-height: 60rpx !important;
  height: 60rpx !important;
}
</style>
