/**
 * 页面通用混入
 * 提供页面级别的通用功能和生命周期管理
 */

import { ref, reactive, onMounted, onUnmounted, onShow, onHide } from 'vue'
import { useUserStore } from '@/common/store/modules/user.js'
import { createLogger } from '@/common/utils/logger.js'
import { permission } from '@/common/utils/permission.js'

const logger = createLogger('PageMixin')

/**
 * 页面基础混入
 */
export const pageBaseMixin = {
  setup() {
    const userStore = useUserStore()
    const loading = ref(false)
    const refreshing = ref(false)
    const pageData = reactive({})
    
    // 页面加载状态管理
    const setLoading = (state) => {
      loading.value = state
      if (state) {
        uni.showLoading({ title: '加载中...' })
      } else {
        uni.hideLoading()
      }
    }
    
    // 页面刷新状态管理
    const setRefreshing = (state) => {
      refreshing.value = state
    }
    
    // 显示成功提示
    const showSuccess = (message, duration = 2000) => {
      uni.showToast({
        title: message,
        icon: 'success',
        duration
      })
    }
    
    // 显示错误提示
    const showError = (message, duration = 2000) => {
      uni.showToast({
        title: message,
        icon: 'none',
        duration
      })
    }
    
    // 显示确认对话框
    const showConfirm = (options) => {
      return new Promise((resolve) => {
        uni.showModal({
          title: options.title || '提示',
          content: options.content || '',
          confirmText: options.confirmText || '确定',
          cancelText: options.cancelText || '取消',
          success: (res) => {
            resolve(res.confirm)
          },
          fail: () => {
            resolve(false)
          }
        })
      })
    }
    
    // 页面跳转
    const navigateTo = (url, params = {}) => {
      const query = Object.keys(params).length > 0 
        ? '?' + Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&')
        : ''
      
      uni.navigateTo({
        url: url + query,
        fail: (error) => {
          logger.error('Navigation failed', { url, params }, error)
          showError('页面跳转失败')
        }
      })
    }
    
    // 页面返回
    const navigateBack = (delta = 1) => {
      uni.navigateBack({
        delta,
        fail: () => {
          uni.switchTab({ url: '/pages/index/index' })
        }
      })
    }
    
    // 页面重定向
    const redirectTo = (url, params = {}) => {
      const query = Object.keys(params).length > 0 
        ? '?' + Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&')
        : ''
      
      uni.redirectTo({
        url: url + query,
        fail: (error) => {
          logger.error('Redirect failed', { url, params }, error)
          showError('页面跳转失败')
        }
      })
    }
    
    // 切换到标签页
    const switchTab = (url) => {
      uni.switchTab({
        url,
        fail: (error) => {
          logger.error('Switch tab failed', { url }, error)
          showError('页面切换失败')
        }
      })
    }
    
    // 分享页面
    const sharePage = (options = {}) => {
      return {
        title: options.title || '畜牧管理系统',
        path: options.path || '/pages/index/index',
        imageUrl: options.imageUrl || ''
      }
    }
    
    return {
      userStore,
      loading,
      refreshing,
      pageData,
      setLoading,
      setRefreshing,
      showSuccess,
      showError,
      showConfirm,
      navigateTo,
      navigateBack,
      redirectTo,
      switchTab,
      sharePage
    }
  }
}

/**
 * 列表页面混入
 */
export const listPageMixin = {
  setup() {
    const list = ref([])
    const total = ref(0)
    const page = ref(1)
    const pageSize = ref(20)
    const hasMore = ref(true)
    const searchKeyword = ref('')
    const filters = reactive({})
    const sortBy = ref('')
    const sortOrder = ref('desc')
    
    // 重置列表
    const resetList = () => {
      list.value = []
      total.value = 0
      page.value = 1
      hasMore.value = true
    }
    
    // 加载更多
    const loadMore = async (loadFunction) => {
      if (!hasMore.value) return
      
      try {
        const params = {
          page: page.value,
          pageSize: pageSize.value,
          keyword: searchKeyword.value,
          sortBy: sortBy.value,
          sortOrder: sortOrder.value,
          ...filters
        }
        
        const response = await loadFunction(params)
        const newList = response.data.list || []
        
        if (page.value === 1) {
          list.value = newList
        } else {
          list.value.push(...newList)
        }
        
        total.value = response.data.total || 0
        hasMore.value = newList.length === pageSize.value
        page.value++
        
        return response
      } catch (error) {
        logger.error('Load more failed', { page: page.value }, error)
        throw error
      }
    }
    
    // 刷新列表
    const refreshList = async (loadFunction) => {
      resetList()
      return await loadMore(loadFunction)
    }
    
    // 搜索
    const search = async (keyword, loadFunction) => {
      searchKeyword.value = keyword
      return await refreshList(loadFunction)
    }
    
    // 筛选
    const filter = async (filterData, loadFunction) => {
      Object.assign(filters, filterData)
      return await refreshList(loadFunction)
    }
    
    // 排序
    const sort = async (field, order, loadFunction) => {
      sortBy.value = field
      sortOrder.value = order
      return await refreshList(loadFunction)
    }
    
    return {
      list,
      total,
      page,
      pageSize,
      hasMore,
      searchKeyword,
      filters,
      sortBy,
      sortOrder,
      resetList,
      loadMore,
      refreshList,
      search,
      filter,
      sort
    }
  }
}

/**
 * 表单页面混入
 */
export const formPageMixin = {
  setup() {
    const formData = reactive({})
    const errors = ref({})
    const submitting = ref(false)
    const isDirty = ref(false)
    
    // 设置表单数据
    const setFormData = (data) => {
      Object.assign(formData, data)
      isDirty.value = false
    }
    
    // 更新表单字段
    const updateField = (field, value) => {
      formData[field] = value
      isDirty.value = true
      
      // 清除该字段的错误
      if (errors.value[field]) {
        delete errors.value[field]
        errors.value = { ...errors.value }
      }
    }
    
    // 设置错误信息
    const setErrors = (errorData) => {
      errors.value = errorData
    }
    
    // 清除错误信息
    const clearErrors = () => {
      errors.value = {}
    }
    
    // 验证表单
    const validateForm = (rules) => {
      const newErrors = {}
      
      Object.keys(rules).forEach(field => {
        const fieldRules = rules[field]
        const value = formData[field]
        
        for (const rule of fieldRules) {
          if (rule.required && (!value || value === '')) {
            newErrors[field] = rule.message || `${field}不能为空`
            break
          }
          
          if (rule.pattern && value && !rule.pattern.test(value)) {
            newErrors[field] = rule.message || `${field}格式不正确`
            break
          }
          
          if (rule.minLength && value && value.length < rule.minLength) {
            newErrors[field] = rule.message || `${field}长度不能少于${rule.minLength}个字符`
            break
          }
          
          if (rule.maxLength && value && value.length > rule.maxLength) {
            newErrors[field] = rule.message || `${field}长度不能超过${rule.maxLength}个字符`
            break
          }
          
          if (rule.validator && typeof rule.validator === 'function') {
            const result = rule.validator(value, formData)
            if (result !== true) {
              newErrors[field] = result || rule.message || `${field}验证失败`
              break
            }
          }
        }
      })
      
      setErrors(newErrors)
      return Object.keys(newErrors).length === 0
    }
    
    // 提交表单
    const submitForm = async (submitFunction, rules = null) => {
      if (submitting.value) return
      
      if (rules && !validateForm(rules)) {
        uni.showToast({
          title: '请填写正确信息',
          icon: 'none'
        })
        return
      }
      
      try {
        submitting.value = true
        const result = await submitFunction(formData)
        isDirty.value = false
        return result
      } catch (error) {
        logger.error('Form submit failed', { formData }, error)
        throw error
      } finally {
        submitting.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      Object.keys(formData).forEach(key => {
        delete formData[key]
      })
      clearErrors()
      isDirty.value = false
    }
    
    return {
      formData,
      errors,
      submitting,
      isDirty,
      setFormData,
      updateField,
      setErrors,
      clearErrors,
      validateForm,
      submitForm,
      resetForm
    }
  }
}

/**
 * 权限检查混入
 */
export const permissionMixin = {
  setup() {
    // 检查权限
    const hasPermission = (permissions, operator = 'and') => {
      return permission.check(permissions, operator)
    }
    
    // 检查角色
    const hasRole = (roles, operator = 'or') => {
      return permission.checkRole(roles, operator)
    }
    
    // 是否为管理员
    const isAdmin = () => {
      return permission.checkRole(['super_admin', 'admin'], 'or')
    }
    
    // 权限守卫
    const requirePermission = (permissions, operator = 'and') => {
      if (!hasPermission(permissions, operator)) {
        uni.showToast({
          title: '权限不足',
          icon: 'none'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
        return false
      }
      return true
    }
    
    return {
      hasPermission,
      hasRole,
      isAdmin,
      requirePermission
    }
  }
}

/**
 * 页面生命周期混入
 */
export const lifecycleMixin = {
  setup() {
    const pageStartTime = Date.now()
    
    onMounted(() => {
      const loadTime = Date.now() - pageStartTime
      logger.performance('Page Mount', loadTime)
    })
    
    onShow(() => {
      logger.pageView(getCurrentPages().pop()?.route || 'Unknown')
    })
    
    onHide(() => {
      logger.debug('Page hidden')
    })
    
    onUnmounted(() => {
      logger.debug('Page unmounted')
    })
    
    return {}
  }
}

/**
 * 下拉刷新混入
 */
export const pullRefreshMixin = {
  setup() {
    const refreshing = ref(false)
    
    // 开始下拉刷新
    const onPullDownRefresh = async (refreshFunction) => {
      if (refreshing.value) return
      
      try {
        refreshing.value = true
        await refreshFunction()
      } catch (error) {
        logger.error('Pull refresh failed', null, error)
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        })
      } finally {
        refreshing.value = false
        uni.stopPullDownRefresh()
      }
    }
    
    return {
      refreshing,
      onPullDownRefresh
    }
  }
}

/**
 * 触底加载混入
 */
export const reachBottomMixin = {
  setup() {
    const loading = ref(false)
    
    // 触底加载更多
    const onReachBottom = async (loadMoreFunction) => {
      if (loading.value) return
      
      try {
        loading.value = true
        await loadMoreFunction()
      } catch (error) {
        logger.error('Reach bottom load failed', null, error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        loading.value = false
      }
    }
    
    return {
      loading,
      onReachBottom
    }
  }
}

/**
 * 分享功能混入
 */
export const shareMixin = {
  setup() {
    // 分享给朋友
    const onShareAppMessage = (options = {}) => {
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      
      return {
        title: options.title || '畜牧管理系统',
        path: options.path || `/${currentPage.route}`,
        imageUrl: options.imageUrl || ''
      }
    }
    
    // 分享到朋友圈
    const onShareTimeline = (options = {}) => {
      return {
        title: options.title || '畜牧管理系统',
        imageUrl: options.imageUrl || ''
      }
    }
    
    return {
      onShareAppMessage,
      onShareTimeline
    }
  }
}

/**
 * 组合所有混入
 */
export const commonMixin = {
  mixins: [
    pageBaseMixin,
    permissionMixin,
    lifecycleMixin,
    shareMixin
  ]
}

// 导出所有混入
export default {
  pageBaseMixin,
  listPageMixin,
  formPageMixin,
  permissionMixin,
  lifecycleMixin,
  pullRefreshMixin,
  reachBottomMixin,
  shareMixin,
  commonMixin
}