<template>
  <uni-popup ref="devicePopup" type="bottom" @maskClick="close">
    <view class="modal-container">
      <!-- 搜索表单 -->
      <view class="search-box">
        <view class="search-type">
          <uni-data-select v-model="searchType" :localdata="searchTypeOptions" @change="handleSearchTypeChange">
          </uni-data-select>
        </view>
        <view class="search-item">
          <uni-easyinput v-show="searchType === 'code'" v-model="queryParams.code" placeholder="出厂编号"
            @blur="handleSearch" clearable>
          </uni-easyinput>
          <uni-data-select v-show="searchType === 'name'" v-model="queryParams.name" :localdata="nameList"
            @change="handleSearch" clearable>
          </uni-data-select>
          <uni-easyinput v-show="searchType === 'brand'" v-model="queryParams.brand" placeholder="设备品牌"
            @blur="handleSearch" clearable>
          </uni-easyinput>
        </view>
      </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 {
      searchType: 'code',
      searchTypeOptions: [
        { value: 'code', text: '出厂编号' },
        { value: 'name', text: '设备名称' },
        { value: 'brand', text: '设备品牌' }
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: '1',
        type: '仪器设备',
        code: '',
        name: '',
        brand: ''
      },
      statusOptions: [
        { value: '0', text: '被领用' },
        { value: '1', text: '可领用' },
        { value: '2', text: '维修中' },
        { value: '3', text: '已停用' },
        { value: '4', text: '已报废' }
      ],
      list: [],
      selectedList: [],
      hasMore: true,
      loading: false,
      scrollTop: 0,
      nameList: []
    }
  },

  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);
    this.getNameList();
  },

  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];
        }

        // 保持已选择的设备状态
        const selectedDeviceIds = this.selectedList.map(item => item.deviceId);
        this.list.forEach(item => {
          if (selectedDeviceIds.includes(item.deviceId)) {
            const selectedItem = this.selectedList.find(s => s.deviceId === item.deviceId);
            if (selectedItem) {
              Object.assign(item, selectedItem);
            }
          }
        });

        this.hasMore = res.total > this.queryParams.pageNum * this.queryParams.pageSize;
        this.queryParams.pageNum++;
      } finally {
        this.loading = false;
      }
    },
    getNameList() {
      listDeviceName().then(res => {
        this.nameList = res.data.filter(function (item) {
          return item !== null;
        }).map(function (item) {
          return { value: item.name, text: item.name };
        });
      })
    },
    // 搜索类型改变处理
    handleSearchTypeChange() {
      // 清空其他搜索字段
      this.queryParams.code = '';
      this.queryParams.name = '';
      this.queryParams.brand = '';
      this.handleSearch();
    },
    // 搜索处理
    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() {
      if (!this.hasMore || this.loading) return;
      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-direction: row;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 32rpx;

  .search-type {
    width: 30%;

    ::v-deep .uni-data-select {
      width: 100%;
    }
  }

  .search-item {
    width: 70%;
    position: relative;
    height: 72rpx;
    /* 设置固定高度，与输入框高度一致 */

    ::v-deep .uni-easyinput__content,
    ::v-deep .uni-data-select {
      height: 72rpx;
      line-height: 72rpx;
    }
  }

  ::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>