<template>
  <view class="page">
    <!-- 顶部搜索和筛选卡片 -->
    <view class="top-card card">
      <!-- 搜索栏 -->
      <view class="search-row">
        <view class="search-input-wrap">
          <text class="search-icon">🔍</text>
          <input v-model="searchName" placeholder="输入资产名搜索" class="search-input"
            @confirm="search" />
          <text v-if="searchName" class="clear-icon" @tap="clearSearch">✕</text>
        </view>
        <button class="btn-search" @tap="search">搜索</button>
      </view>

      <!-- 状态筛选 -->
      <view class="filter-row">
        <view class="filter-tabs">
          <view class="filter-tab" :class="{ active: filterStatus === null }"
            @tap="changeFilter(null)">
            全部
          </view>
          <view class="filter-tab" :class="{ active: filterStatus === 1 }"
            @tap="changeFilter(1)">
            使用中
          </view>
          <view class="filter-tab" :class="{ active: filterStatus === 3 }"
            @tap="changeFilter(3)">
            闲置
          </view>
          <view class="filter-tab" :class="{ active: filterStatus === 4 }"
            @tap="changeFilter(4)">
            维修中
          </view>
          <view class="filter-tab" :class="{ active: filterStatus === 5 }"
            @tap="changeFilter(5)">
            外借
          </view>
        </view>
      </view>
    </view>

    <!-- 资产列表 -->
    <scroll-view class="list-container" scroll-y>
      <view v-if="loading && filteredList.length === 0" class="loading-wrap">
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="filteredList.length === 0" class="empty-wrap">
        <text class="empty-icon">📦</text>
        <text class="empty-text">暂无资产数据</text>
      </view>

      <view v-else class="list">
        <view class="asset-item card" v-for="item in filteredList"
          :key="item.assetId || item.assetid" @tap="gotoDetail(item)">
          <!-- 顶部：资产名称 + 借用按钮/状态标签 -->
          <view class="item-header">
            <view class="asset-name-wrap">
              <text class="asset-name">{{ item.assetName }}</text>
            </view>
            <button v-if="item.status === 3" class="header-borrow-btn"
              @tap.stop="borrow(item)">
              立即借用
            </button>
            <view v-else class="status-badge"
              :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </view>
          </view>

          <!-- 资产信息 -->
          <view class="asset-info">
            <view class="info-row">
              <text class="info-label">采购日期：</text>
              <text class="info-value">{{ item.purchaseDate || '-' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">采购价格：</text>
              <text class="info-value">{{ item.purchasePrice ?
                `¥${item.purchasePrice}` : '-' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">采购数量：</text>
              <text class="info-value">{{ item.purchaseQuantity || '-' }}</text>
            </view>
          </view>

          <!-- 底部操作按钮 -->
          <view class="asset-actions" @tap.stop>
            <button class="action-btn info-btn"
              @tap="gotoShowMaintenanceInfo(item)">
              维修信息
            </button>
            <button class="action-btn detail-btn" @tap="gotoDetail(item)">
              查看详情
            </button>
          </view>
        </view>
      </view>

      <!-- 分页加载提示 -->
      <view class="load-status" v-if="filteredList.length > 0">
        <text v-if="loading">加载中...</text>
        <text v-else-if="noMore">没有更多数据了</text>
      </view>
    </scroll-view>

    <!-- 借用弹窗 -->
    <view class="modal" v-if="showBorrowPopup">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">借用资产</text>
          <text class="modal-close" @tap="cancelBorrow">✕</text>
        </view>

        <scroll-view class="modal-body" scroll-y>
          <view class="form-item">
            <text class="form-label">资产名称</text>
            <view class="form-value">{{ selectedAsset?.assetName }}</view>
          </view>

          <view class="form-item">
            <text class="form-label">借用人手机号 <text
                class="required">*</text></text>
            <input v-model="borrowForm.lenderMobile" placeholder="请输入借用人手机号"
              type="number" class="form-input" maxlength="11"
              @input="searchUserByMobile" />
            <view class="user-suggestions" v-if="userSuggestions.length">
              <view class="suggestion-item" v-for="u in userSuggestions"
                :key="u.userMobile">
                <text class="suggestion-name">{{ u.userName }}</text>
                <text class="suggestion-mobile">{{ u.userMobile }}</text>
              </view>
            </view>
          </view>

          <view class="form-item">
            <text class="form-label">借用日期 <text class="required">*</text></text>
            <picker mode="date" :value="borrowForm.borrowDate"
              @change="onBorrowDateChange">
              <view class="form-picker">
                {{ borrowForm.borrowDate || '请选择借用日期' }}
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="form-label">预计归还日期 <text
                class="required">*</text></text>
            <picker mode="date" :value="borrowForm.returnDate"
              @change="onReturnDateChange">
              <view class="form-picker">
                {{ borrowForm.returnDate || '请选择归还日期' }}
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="form-label">备注</text>
            <textarea v-model="borrowForm.note" placeholder="请输入备注信息"
              class="form-textarea" maxlength="200" />
          </view>
        </scroll-view>

        <view class="modal-footer">
          <button class="footer-btn cancel-btn" @tap="cancelBorrow">取消</button>
          <button class="footer-btn confirm-btn"
            @tap="confirmBorrow">确认借用</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
// @ts-ignore JS模块无类型声明
import { searchFixedAssets, fetchFixedAssets, borrowAssetById, searchUserByMobile as apiSearchUserByMobile } from '@/pages/api/fixedAssets.js'

interface AssetItem { [k: string]: any }

const assetList = ref<AssetItem[]>([])
const page = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const noMore = ref(false)
const searchName = ref('')
const filterStatus = ref<number | null>(null)

const showBorrowPopup = ref(false)
const selectedAsset = ref<AssetItem | null>(null)
const userInfo = uni.getStorageSync('staff') || {}
const currentUserMobile = uni.getStorageSync('userName') || ''

const borrowForm = ref({
  lenderMobile: '',
  borrowDate: '',
  returnDate: '',
  note: ''
})
const userSuggestions = ref<any[]>([])
let searchTimeout: any = null

// 状态筛选后的列表
const filteredList = computed(() => {
  if (filterStatus.value === null) {
    return assetList.value
  }
  return assetList.value.filter(item => {
    const status = item.status === 0 ? 1 : item.status // 0和1都视为使用中
    return status === filterStatus.value
  })
})

function formatDate(d: Date) {
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

// 获取状态文本
function getStatusText(status: number) {
  if (status === 1 || status === 0) return '使用中'
  if (status === 2) return '报废'
  if (status === 3) return '闲置'
  if (status === 4) return '维修中'
  if (status === 5) return '外借'
  return '未知'
}

// 获取状态样式类
function getStatusClass(status: number) {
  if (status === 1 || status === 0) return 'status-using'
  if (status === 2) return 'status-scrapped'
  if (status === 3) return 'status-idle'
  if (status === 4) return 'status-repairing'
  if (status === 5) return 'status-borrowed'
  return 'status-unknown'
}

onLoad(() => {
  getAssetList()
})

onReachBottom(() => {
  if (!loading.value && !noMore.value && !searchName.value) {
    page.value++
    getAssetList()
  }
})

// 切换状态筛选
function changeFilter(status: number | null) {
  filterStatus.value = status
}

// 清除搜索
function clearSearch() {
  searchName.value = ''
  assetList.value = []
  page.value = 1
  noMore.value = false
  filterStatus.value = null
  getAssetList()
}

async function search() {
  loading.value = true
  try {
    if (!searchName.value) {
      assetList.value = []
      page.value = 1
      noMore.value = false
      await getAssetList()
      return
    }
    const data: any = await searchFixedAssets(searchName.value)
    assetList.value = data?.data || []
    noMore.value = true
  } catch (e) {
    console.error('获取数据失败', e)
    uni.showToast({ title: '搜索失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

async function getAssetList() {
  loading.value = true
  try {
    const data: any = await fetchFixedAssets(page.value, pageSize.value)
    const list = data?.data?.list || []
    if (list.length < pageSize.value) noMore.value = true
    assetList.value = assetList.value.concat(list)
  } catch (e) {
    console.error('获取数据失败', e)
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

function gotoDetail(item: AssetItem) {
  const sn = item.assetSn || item.assetSN || item.asset_sn
  if (sn) {
    uni.navigateTo({ url: `/pages/fixed-assets/detail?assetSn=${encodeURIComponent(sn)}` })
  } else {
    uni.navigateTo({
      url: '/pages/fixed-assets/detail',
      success(res) {
        res.eventChannel.emit('sendData', { data: item })
      }
    })
  }
}

function gotoShowMaintenanceInfo(item: AssetItem) {
  const id = item.assetId || item.assetid
  if (id) {
    uni.navigateTo({ url: `/pages/fixed-assets/maintenance-info?assetId=${id}` })
  } else {
    uni.navigateTo({
      url: '/pages/fixed-assets/maintenance-info',
      success(res) {
        res.eventChannel.emit('sendData', { data: item })
      }
    })
  }
}

function borrow(item: AssetItem) {
  selectedAsset.value = item
  showBorrowPopup.value = true
  userSuggestions.value = []

  // 默认填充当前用户手机号
  borrowForm.value = {
    lenderMobile: currentUserMobile,
    borrowDate: formatDate(new Date()),
    returnDate: '',
    note: ''
  }
  searchUserByMobile()
}

function cancelBorrow() {
  showBorrowPopup.value = false
  userSuggestions.value = []
}

function onBorrowDateChange(e: any) {
  borrowForm.value.borrowDate = e.detail.value
}

function onReturnDateChange(e: any) {
  borrowForm.value.returnDate = e.detail.value
}

async function searchUserByMobile() {
  const mobile = borrowForm.value.lenderMobile
  if (searchTimeout) clearTimeout(searchTimeout)
  if (!mobile || mobile.length < 3) {
    userSuggestions.value = []
    return
  }

  searchTimeout = setTimeout(async () => {
    try {
      const resp: any = await apiSearchUserByMobile(mobile)
      userSuggestions.value = resp.data ?? []
    } catch (err) {
      userSuggestions.value = []
    }
  }, 500)
}

function selectUser(user: any) {
}

async function confirmBorrow() {
  // 验证必填项
  if (!borrowForm.value.lenderMobile) {
    uni.showToast({ title: '请输入借用人手机号', icon: 'none' })
    return
  }
  if (!borrowForm.value.borrowDate) {
    uni.showToast({ title: '请选择借用日期', icon: 'none' })
    return
  }
  if (!borrowForm.value.returnDate) {
    uni.showToast({ title: '请选择归还日期', icon: 'none' })
    return
  }

  const s = selectedAsset.value || {}
  const payload = {
    assetId: s.assetId || s.assetid,
    assetName: s.assetName,
    borrowDate: borrowForm.value.borrowDate,
    borrowerMobile: borrowForm.value.lenderMobile,
    lenderMobile: s.headerMobile,
    note: borrowForm.value.note,
    registrantDate: formatDate(new Date()),
    registrantId: s.registrantId || userInfo.id,
    registrantMobile: s.registrantMobile || currentUserMobile,
    returnDate: borrowForm.value.returnDate
  }

  uni.showLoading({ title: '提交中...' })
  try {
    await borrowAssetById(payload)
    uni.hideLoading()
    uni.showToast({
      title: '借用成功',
      icon: 'success'
    })
    showBorrowPopup.value = false

    // 刷新列表
    assetList.value = []
    page.value = 1
    noMore.value = false
    await getAssetList()
  } catch (err) {
    uni.hideLoading()
    uni.showToast({ title: '借用失败', icon: 'none' })
  }
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f5f7fb;
  padding-bottom: 32rpx;
}

.card {
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.06);
}

/* 顶部卡片 */
.top-card {
  margin: 24rpx 24rpx 16rpx;
  padding: 20rpx 24rpx;
}

/* 搜索行 */
.search-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 20rpx;
}

.search-input-wrap {
  flex: 1;
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 40rpx;
  padding: 12rpx 20rpx;
  gap: 8rpx;
}

.search-icon {
  font-size: 28rpx;
  opacity: 0.6;
}

.search-input {
  flex: 1;
  font-size: 26rpx;
  color: #333;
  background: transparent;
}

.clear-icon {
  font-size: 28rpx;
  color: #999;
  padding: 0 8rpx;
}

.btn-search {
  padding: 0rpx 28rpx;
  background: #007aff;
  color: #fff;
  border-radius: 40rpx;
  font-size: 26rpx;
  border: none;
}

/* 筛选行 */
.filter-row {
  padding-top: 16rpx;
  border-top: 2rpx solid #f0f0f0;
}

.filter-tabs {
  display: flex;
  gap: 8rpx;
  overflow-x: auto;
}

.filter-tab {
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  color: #666;
  background: #f8f9fa;
  white-space: nowrap;
  flex-shrink: 0;
  transition: all 0.3s;
}

.filter-tab.active {
  background: #007aff;
  color: #fff;
  font-weight: 500;
}

/* 列表容器 */
.list-container {
  height: calc(100vh - 260rpx);
}

.loading-wrap,
.empty-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.loading-text {
  color: #999;
  font-size: 28rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}

/* 列表 */
.list {
  padding: 0 24rpx;
}

.asset-item {
  margin-bottom: 20rpx;
  padding: 24rpx;
}

/* 资产项头部 */
.item-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 16rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.asset-name-wrap {
  flex: 1;
  margin-right: 16rpx;
}

.asset-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #222;
  line-height: 1.4;
}

/* 顶部借用按钮 */
.header-borrow-btn {
  padding: 0 24rpx;
  height: 56rpx;
  background: #007aff;
  color: #fff;
  border-radius: 28rpx;
  font-size: 24rpx;
  font-weight: 500;
  border: none;
  white-space: nowrap;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
}

/* 状态标签 */
.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-weight: 500;
  white-space: nowrap;
}

.status-using {
  background: #e3f2fd;
  color: #1976d2;
}

.status-scrapped {
  background: #ffebee;
  color: #c62828;
}

.status-idle {
  background: #e8f5e9;
  color: #2e7d32;
}

.status-repairing {
  background: #fff3e0;
  color: #f57c00;
}

.status-borrowed {
  background: #f5f5f5;
  color: #757575;
}

.status-unknown {
  background: #f5f5f5;
  color: #757575;
}

/* 资产信息 */
.asset-info {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  margin-bottom: 16rpx;
}

.info-row {
  display: flex;
  font-size: 24rpx;
}

.info-label {
  color: #999;
  min-width: 140rpx;
  flex-shrink: 0;
}

.info-value {
  color: #333;
  flex: 1;
}

/* 操作按钮 */
.asset-actions {
  display: flex;
  gap: 12rpx;
  justify-content: flex-end;
  padding-top: 16rpx;
  border-top: 2rpx solid #f0f0f0;
}

.action-btn {
  padding: 0rpx 24rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  border: none;
}

.borrow-btn {
  background: #007aff;
  color: #fff;
}

.info-btn {
  background: #fff;
  color: #ff9800;
  border: 2rpx solid #ff9800;
}

.detail-btn {
  background: #fff;
  color: #007aff;
  border: 2rpx solid #007aff;
}

.load-status {
  text-align: center;
  color: #999;
  padding: 24rpx 0;
  font-size: 24rpx;
}

/* 弹窗 */
.modal {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.modal-content {
  width: 86%;
  max-height: 80vh;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 24rpx 28rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 2rpx solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  color: #222;
  font-weight: 600;
}

.modal-close {
  font-size: 48rpx;
  color: #999;
  line-height: 1;
}

.modal-body {
  flex: 1;
  padding: 24rpx 28rpx;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 36rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.required {
  color: #ff4d4f;
  margin-left: 4rpx;
}

.form-value {
  font-size: 28rpx;
  color: #333;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  line-height: 1.6;
}

.form-input {
  height: 80rpx;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
  border: 2rpx solid transparent;
  transition: all 0.3s;
  line-height: 1.5;
}

.form-input:focus,
.form-textarea:focus {
  background: #fff;
  border-color: #007aff;
}

.form-textarea {
  min-height: 160rpx;
}

.form-picker {
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

/* 用户建议列表 */
.user-suggestions {
  margin-top: 16rpx;
  background: #fff;
  border: 2rpx solid #e8e8e8;
  border-radius: 12rpx;
  max-height: 320rpx;
  overflow-y: auto;
}

.suggestion-item {
  padding: 20rpx;
  border-bottom: 2rpx solid #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.suggestion-mobile {
  font-size: 26rpx;
  color: #999;
}

.modal-footer {
  padding: 20rpx 28rpx;
  display: flex;
  gap: 16rpx;
  border-top: 2rpx solid #f0f0f0;
}

.footer-btn {
  flex: 1;
  padding: 0 20rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: #007aff;
  color: #fff;
}
</style>
