<template>
  <uni-popup ref="devicePopup" type="bottom" @maskClick="close">
    <view class="modal-container">
      <!-- 搜索表单 -->
      <view class="search-box">
        <uni-data-select v-model="queryParams.status" :localdata="statusOptions" style="width: 200rpx;"
          :clearable="false" @change="handleSearch">
        </uni-data-select>

        <uni-easyinput v-model="queryParams.code" placeholder="出厂编号" @confirm="handleSearch" clearable>
        </uni-easyinput>

        <uni-easyinput v-model="queryParams.name" placeholder="设备名称" @confirm="handleSearch" clearable>
        </uni-easyinput>
      </view>

      <!-- 设备列表 -->
      <scroll-view scroll-y class="list-container" @scrolltolower="loadMore" :scroll-top="scrollTop">
        <view v-for="(item, index) in list" :key="index" class="list-item" :class="{ selected: isSelected(item) }"
          @click="handleSelect(item)">
          <view class="item-content">
            <view class="item-header">
              <uni-tag :text="statusText(item.status)" :type="statusType(item.status)" size="small">
              </uni-tag>
              <text class="device-code">{{ item.code }}</text>
            </view>
            <view class="item-body">
              <text class="device-name">{{ item.name }}</text>
              <text class="device-info">{{ item.brand }} {{ item.series }}</text>
              <text class="device-place">📍 {{ item.place }}</text>
            </view>
          </view>

          <uni-icons v-if="isSelected(item)" type="checkmarkempty" color="#007AFF" size="18" />
        </view>

        <!-- 加载状态 -->
        <view class="loading-status">
          <uni-load-more :status="loading ? 'loading' : (hasMore ? 'more' : 'noMore')" :contentText="{
            contentdown: '上拉加载更多',
            contentrefresh: '正在加载',
            contentnomore: '没有更多设备'
          }">
          </uni-load-more>
        </view>
      </scroll-view>

      <!-- 底部操作栏 -->
      <view class="footer-actions">
        <button class="action-btn cancel" @click="close">取消</button>
        <button class="action-btn confirm" @click="confirm" :disabled="!selectedList.length">确定选择</button>
      </view>
    </view>
  </uni-popup>
</template>

<script>
import { listDevice, listDeviceName } from "@/api/oa/device/device";
import { debounce } from 'lodash-es';

export default {
  props: {
    visible: Boolean,
    selected: {
      type: [Array, Object],
      default: () => ([])
    },
    multiple: {
      type: Boolean,
      default: true
    }
  },

  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: '1',
        type: '仪器设备',
        code: '',
        name: ''
      },
      statusOptions: [
        { value: '0', text: '被领用' },
        { value: '1', text: '可领用' },
        { value: '2', text: '维修中' },
        { value: '3', text: '已停用' },
        { value: '4', text: '已报废' }
      ],
      list: [],
      selectedList: [],
      hasMore: true,
      loading: false,
      scrollTop: 0
    }
  },

  watch: {
    visible(val) {
      val ? this.$refs.devicePopup.open() : this.$refs.devicePopup.close();
      if (val) this.initData();
    },
    selected: {
      immediate: true,
      handler(val) {
        this.selectedList = Array.isArray(val) ? [...val] : [val];
      }
    },
    'queryParams.status': {
      handler() {
        this.handleSearch();
      }
    }
  },

  created() {
    this.debouncedSearch = debounce(this.loadData, 300);
  },

  methods: {
    // 初始化数据
    initData() {
      this.queryParams.pageNum = 1;
      this.hasMore = true;
      this.list = [];
      this.loadData();
    },

    // 加载设备数据
    async loadData() {
      if (this.loading) return;

      this.loading = true;
      try {
        const res = await listDevice(this.queryParams);
        
        // 如果是第一页，直接替换列表
        if (this.queryParams.pageNum === 1) {
          this.list = res.rows;
        } else {
          // 如果不是第一页，追加到列表
          this.list = [...this.list, ...res.rows];
        }

        this.hasMore = res.total > this.queryParams.pageNum * this.queryParams.pageSize;
        this.queryParams.pageNum++;
      } finally {
        this.loading = false;
      }
    },

    // 搜索处理
    handleSearch() {
      // 重置分页参数
      this.queryParams.pageNum = 1;
      this.hasMore = true;
      this.list = [];
      this.loadData();
    },

    // 选择设备
    handleSelect(item) {
      if (this.multiple) {
        const index = this.selectedList.findIndex(d => d.deviceId === item.deviceId);
        index === -1
          ? this.selectedList.push(item)
          : this.selectedList.splice(index, 1);
      } else {
        this.selectedList = [item];
      }
    },

    // 确认选择
    confirm() {
      const result = this.multiple ? this.selectedList : this.selectedList[0];
      this.$emit('update:selected', result);
      this.$emit('confirm', result);
      this.close();
    },

    // 状态显示逻辑
    statusText(status) {
      const map = { '0': '被领用', '1': '可领用', '2': '维修中', '3': '已停用', '4': '已报废' };
      return map[status] || '未知状态';
    },

    statusType(status) {
      const typeMap = { '0': 'warning', '1': 'success', '2': 'info', '3': 'error', '4': 'default' };
      return typeMap[status] || 'default';
    },

    isSelected(item) {
      return this.selectedList.some(d => d.deviceId === item.deviceId);
    },

    // 加载更多
    loadMore() {
      this.loadData();
    },

    close() {
      this.$emit('update:visible', false);
    }
  }
}
</script>

<style lang="scss" scoped>
.modal-container {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 32rpx;
  max-height: 80vh;
}

.search-box {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 32rpx;

  ::v-deep .uni-easyinput__content {
    border-radius: 16rpx;
  }
}

.list-container {
  max-height: 60vh;
  margin-bottom: 32rpx;

  .list-item {
    display: flex;
    align-items: center;
    padding: 24rpx;
    border-bottom: 1rpx solid #eee;

    &.selected {
      background-color: #f5f7fa;
    }

    .item-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 8rpx;

      .item-header {
        display: flex;
        align-items: center;
        gap: 16rpx;

        .device-code {
          color: #666;
          font-size: 24rpx;
        }
      }

      .item-body {
        display: flex;
        flex-direction: column;
        gap: 4rpx;

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

        .device-info {
          color: #666;
          font-size: 24rpx;
        }

        .device-place {
          color: #999;
          font-size: 24rpx;
        }
      }
    }
  }
}

.footer-actions {
  display: flex;
  gap: 32rpx;

  .action-btn {
    flex: 1;
    border-radius: 12rpx;
    font-size: 28rpx;

    &.confirm {
      background: #007AFF;
      color: #fff;

      &:disabled {
        background: #ccc;
      }
    }

    &.cancel {
      background: #f5f5f5;
      color: #666;
    }
  }
}

.loading-status {
  padding: 32rpx 0;
  text-align: center;
}
</style>