/**
 * 卡片展开收起指令
 * 完全独立的自定义指令，内置控制按钮和状态管理
 */

import { nextTick } from 'vue'

// 存储所有卡片的状态
const cardStates = new Map()

/**
 * 获取卡片内容元素
 * @param {HTMLElement} cardEl - a-card 元素
 * @returns {HTMLElement|null} 卡片内容元素
 */
function getCardBody (cardEl) {
  return cardEl.querySelector('.el-card__body')
}

/**
 * 设置卡片高度
 * @param {HTMLElement} cardEl - a-card 元素
 * @param {boolean} isExpanded - 是否展开
 * @param {number} collapsedHeight - 收起时的高度
 */
function setCardHeight (cardEl, isExpanded, collapsedHeight = 60) {
  const cardBody = getCardBody(cardEl)
  if (!cardBody) return

  // 获取原始 padding 值（如果还没有保存的话）
  if (!cardEl._originalPadding) {
    const computedStyle = window.getComputedStyle(cardBody)
    cardEl._originalPadding = computedStyle.padding
  }

  if (isExpanded) {
    cardBody.style.height = 'auto'
    cardBody.style.overflow = 'visible'
    cardBody.style.padding = cardEl._originalPadding // 恢复原始 padding
  } else {
    cardBody.style.height = `${collapsedHeight}px`
    cardBody.style.overflow = 'hidden'
    // 当收起高度为0时，同时设置padding为0
    if (collapsedHeight === 0) {
      cardBody.style.padding = '0'
    } else {
      cardBody.style.padding = cardEl._originalPadding // 保持原始 padding
    }
  }
}

/**
 * 创建控制按钮
 * @param {HTMLElement} cardEl - a-card 元素
 * @param {Object} options - 配置选项
 */
function createControlButton (cardEl, options) {
  const { expandText = '展开', collapseText = '收起' } = options

  // 创建按钮容器
  const buttonContainer = document.createElement('div')
  buttonContainer.className = 'card-expand-control'
  buttonContainer.style.cssText = `
    position: absolute;
    top: 14px;
    right: 15px;
    z-index: 10;
    cursor: pointer;
    color: #1677ff;
    font-size: 14px;
    user-select: none;
    transition: color 0.3s;
  `

  // 创建按钮文本
  const buttonText = document.createElement('span')
  buttonText.textContent = expandText
  buttonContainer.appendChild(buttonText)

  // 添加悬停效果
  buttonContainer.addEventListener('mouseenter', () => {
    buttonContainer.style.color = '#4096ff'
  })

  buttonContainer.addEventListener('mouseleave', () => {
    buttonContainer.style.color = '#1677ff'
  })

  // 点击事件
  buttonContainer.addEventListener('click', (e) => {
    e.preventDefault()
    e.stopPropagation()
    toggleCard(cardEl._cardExpandId)
  })

  // 将按钮添加到卡片
  cardEl.style.position = 'relative'
  cardEl.appendChild(buttonContainer)

  // 存储按钮引用
  cardEl._controlButton = buttonContainer
  cardEl._buttonText = buttonText
  cardEl._expandText = expandText
  cardEl._collapseText = collapseText
}

/**
 * 更新按钮文本
 * @param {HTMLElement} cardEl - a-card 元素
 * @param {boolean} isExpanded - 是否展开
 */
function updateButtonText (cardEl, isExpanded) {
  if (cardEl._buttonText) {
    cardEl._buttonText.textContent = isExpanded ? cardEl._collapseText : cardEl._expandText
  }
}

/**
 * 初始化卡片
 * @param {HTMLElement} cardEl - a-card 元素
 * @param {Object} options - 配置选项
 */
function initCard (cardEl, options = {}) {
  const {
    isExpanded = false,
    expandText = '展开',
    collapseText = '收起',
    collapsedHeight = 0
  } = options

  const cardId = cardEl.getAttribute('data-card-id') || `card-${Date.now()}-${Math.random()}`
  cardEl.setAttribute('data-card-id', cardId)

  // 存储卡片状态
  cardStates.set(cardId, {
    isExpanded: isExpanded,
    element: cardEl,
    options,
    collapsedHeight
  })

  // 设置初始状态
  setCardHeight(cardEl, isExpanded, collapsedHeight)

  // 创建控制按钮
  createControlButton(cardEl, { expandText, collapseText })

  // 更新按钮文本
  updateButtonText(cardEl, isExpanded)

  return cardId
}

/**
 * 切换卡片状态
 * @param {string} cardId - 卡片ID
 */
function toggleCard (cardId) {
  const state = cardStates.get(cardId)
  if (!state) return

  state.isExpanded = !state.isExpanded
  setCardHeight(state.element, state.isExpanded, state.collapsedHeight)
  updateButtonText(state.element, state.isExpanded)

  return state.isExpanded
}

/**
 * 设置卡片状态
 * @param {string} cardId - 卡片ID
 * @param {boolean} isExpanded - 是否展开
 */
function setCardState (cardId, isExpanded) {
  const state = cardStates.get(cardId)
  if (!state) return

  state.isExpanded = isExpanded
  setCardHeight(state.element, isExpanded, state.collapsedHeight)
  updateButtonText(state.element, isExpanded)
}

/**
 * 获取卡片状态
 * @param {string} cardId - 卡片ID
 * @returns {boolean} 是否展开
 */
function getCardState (cardId) {
  const state = cardStates.get(cardId)
  return state ? state.isExpanded : false
}

/**
 * 卡片展开收起指令
 * @param {HTMLElement} el - a-card 元素
 * @param {Object} binding - 绑定对象
 * @param {Object} value - 配置选项
 * @param {boolean} value.isExpanded - 是否展开
 * @param {string} value.expandText - 展开文本
 * @param {string} value.collapseText - 收起文本
 * @param {number} value.collapsedHeight - 收起时的高度
 * @returns {void}
 * @example
 * <a-card v-card-expand="{ isExpanded: true, expandText: '展开', collapseText: '收起', collapsedHeight: 0 }">
 *   <div>卡片内容</div>
 * </a-card>
 */
export const vCardExpand = {
  mounted (el, binding) {
    const { value = {} } = binding

    nextTick(() => {
      const cardId = initCard(el, value)
      el._cardExpandId = cardId
    })
  },

  updated (el, binding) {
    const { value = {} } = binding
    const { isExpanded } = value

    // 通过 isExpanded 控制状态
    if (typeof isExpanded === 'boolean' && el._cardExpandId) {
      setCardState(el._cardExpandId, isExpanded)
    }
  },

  unmounted (el) {
    // 清理资源
    if (el._cardExpandId) {
      cardStates.delete(el._cardExpandId)
    }
  }
}

// 导出工具函数供外部使用
export {
  toggleCard,
  setCardState,
  getCardState
}
