<!--
 * @Author: ysh
 * @Date: 2025-07-08 14:00:47
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-07-08 15:50:20
-->
<template>
  <view class="device-container">
    <!-- 顶部搜索栏 -->
    <view class="search-section">
      <view class="search-bar">
        <view class="search-input-wrapper">
          <uni-icons type="search" size="16" color="#999"></uni-icons>
          <input class="search-input" v-model="queryParams.name" placeholder="搜索设备名称" @confirm="handleQuery"
            @input="handleSearchInput" />
          <uni-icons v-if="queryParams.name" type="clear" size="16" color="#999" @click="clearSearch"></uni-icons>
        </view>
      </view>

      <!-- 筛选条件 -->
      <view class="filter-section" v-if="showFilter">
        <view class="filter-row">
          <view class="filter-item">
            <text class="filter-label">设备状态</text>
            <uni-data-select v-model="queryParams.status" :localdata="statusOptions" placeholder="全部状态"
              @change="handleQuery" />
          </view>
          <view class="filter-item">
            <text class="filter-label">设备品牌</text>
            <input v-model="queryParams.brand" placeholder="品牌筛选" @confirm="handleQuery" />
          </view>
        </view>
        <view class="filter-row">
          <view class="filter-item">
            <text class="filter-label">出厂编号</text>
            <input v-model="queryParams.code" placeholder="编号筛选" @confirm="handleQuery" />
          </view>
          <view class="filter-item">
            <text class="filter-label">规格型号</text>
            <input v-model="queryParams.series" placeholder="型号筛选" @confirm="handleQuery" />
          </view>
        </view>
      </view>

      <!-- 筛选按钮 -->
      <view class="filter-toggle" @click="toggleFilter">
        <text>筛选</text>
        <uni-icons :type="showFilter ? 'up' : 'down'" size="14" color="#666"></uni-icons>
      </view>
    </view>

    <!-- 设备列表 -->
    <scroll-view :scroll-top="scrollTop" scroll-y="true" class="device-list" @scrolltoupper="upper"
      @scrolltolower="lower" @scroll="scroll" :refresher-enabled="true" :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh" :lower-threshold="50" :upper-threshold="50">
      <view class="content-wrapper">
        <template v-if="deviceList.length > 0">
          <view class="device-card" v-for="(item, index) in deviceList" :key="index" @click="handleViewDetail(item)">
            <view class="device-header">
              <view class="device-info">
                <text class="device-name">{{ item.name }}</text>
                <text class="device-brand">{{ item.brand }}</text>
              </view>
              <view class="device-status">
                <uni-tag :text="statusTypeText(item.status)" :type="statusTypeStyle(item.status)" size="small" />
              </view>
            </view>

            <view class="device-content">
              <view class="info-row">
                <text class="info-label">设备编号：</text>
                <text class="info-value">{{ item.deviceNumber || '暂无' }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">规格型号：</text>
                <text class="info-value">{{ item.series || '暂无' }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">出厂编号：</text>
                <text class="info-value">{{ item.code || '暂无' }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">购置时间：</text>
                <text class="info-value">{{ formatDate(item.acquisitionTime) }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">购买价格：</text>
                <text class="info-value price">¥{{ item.cost || '0' }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">单日成本：</text>
                <text class="info-value cost">¥{{ item.dayCost || '0' }}</text>
              </view>
            </view>

            <view class="device-actions">
              <button class="action-btn view" @click.stop="handleViewDetail(item)">
                <uni-icons type="eye" size="14" color="#007AFF"></uni-icons>
                <text>查看</text>
              </button>
              <button class="action-btn edit" @click.stop="handleUpdate(item)" v-if="hasPermission('oa:device:edit')">
                <uni-icons type="compose" size="14" color="#FF9500"></uni-icons>
                <text>编辑</text>
              </button>
              <button class="action-btn delete" @click.stop="handleDelete(item)"
                v-if="hasPermission('oa:device:remove')">
                <uni-icons type="trash" size="14" color="#FF3B30"></uni-icons>
                <text>删除</text>
              </button>
            </view>
          </view>

          <!-- 加载更多 -->
          <view class="loading-more" v-if="hasMore">
            <text class="loading-text">加载中...</text>
          </view>
          <view class="no-more" v-else>
            <text class="no-more-text">没有更多数据了</text>
          </view>
        </template>

        <!-- 空状态 -->
        <view v-else class="empty-state">
          <image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
          <text class="empty-text">暂无设备数据</text>
          <text class="empty-subtext">点击下方按钮添加设备</text>
        </view>
      </view>
    </scroll-view>

    <!-- 悬浮按钮 -->
    <view class="fab-button" @click="handleAdd" v-if="hasPermission('oa:device:add')">
      <uni-icons type="plusempty" size="24" color="#fff"></uni-icons>
    </view>

    <!-- 设备详情弹窗 -->
    <uni-popup ref="detailPopup" type="center">
      <view class="detail-popup">
        <view class="popup-header">
          <text class="title">设备详情</text>
          <uni-icons type="close" size="20" @click="closeDetailPopup"></uni-icons>
        </view>
        <view class="popup-body">
          <view class="detail-item">
            <text class="detail-label">设备名称</text>
            <text class="detail-value">{{ currentDevice.name }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">设备品牌</text>
            <text class="detail-value">{{ currentDevice.brand }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">设备编号</text>
            <text class="detail-value">{{ currentDevice.deviceNumber }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">规格型号</text>
            <text class="detail-value">{{ currentDevice.series }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">出厂编号</text>
            <text class="detail-value">{{ currentDevice.code }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">设备状态</text>
            <text class="detail-value">
              <uni-tag :text="statusTypeText(currentDevice.status)" :type="statusTypeStyle(currentDevice.status)"
                size="small" />
            </text>
          </view>
          <view class="detail-item">
            <text class="detail-label">购置时间</text>
            <text class="detail-value">{{ formatDate(currentDevice.acquisitionTime) }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">购买价格</text>
            <text class="detail-value price">¥{{ currentDevice.cost }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">预计使用年限</text>
            <text class="detail-value">{{ currentDevice.expectLife }}年</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">单日成本</text>
            <text class="detail-value cost">¥{{ currentDevice.dayCost }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">存放地点</text>
            <text class="detail-value">{{ currentDevice.place || '暂无' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">备注</text>
            <text class="detail-value">{{ currentDevice.remark || '暂无' }}</text>
          </view>
        </view>
        <view class="popup-footer">
          <button class="popup-btn cancel" @click="closeDetailPopup">关闭</button>
          <button class="popup-btn primary" @click="handleViewLogs">查看记录</button>
        </view>
      </view>
    </uni-popup>

    <!-- 新增/编辑设备弹窗 -->
    <uni-popup ref="formPopup" type="center">
      <view class="form-popup">
        <view class="popup-header">
          <text class="title">{{ isEdit ? '编辑设备' : '新增设备' }}</text>
          <uni-icons type="close" size="20" @click="closeFormPopup"></uni-icons>
        </view>
        <scroll-view scroll-y="true" class="popup-body">
          <view class="form-item">
            <text class="label">设备品牌 *</text>
            <input v-model="form.brand" placeholder="请输入设备品牌" />
          </view>
          <view class="form-item">
            <text class="label">设备名称 *</text>
            <input v-model="form.name" placeholder="请输入设备名称" />
          </view>
          <view class="form-item">
            <text class="label">设备类别</text>
            <uni-data-select v-model="form.type" :localdata="typeOptions" placeholder="请选择设备类别" />
          </view>
          <view class="form-item">
            <text class="label">规格型号</text>
            <input v-model="form.series" placeholder="请输入规格型号" />
          </view>
          <view class="form-item">
            <text class="label">购置时间</text>
            <view class="date-picker" @click="openDatePicker">
              <text v-if="form.acquisitionTime">{{ form.acquisitionTime }}</text>
              <text v-else class="placeholder">请选择购置时间</text>
            </view>
          </view>
          <view class="form-item">
            <text class="label">存放地点</text>
            <input v-model="form.place" placeholder="请输入存放地点" />
          </view>
          <view class="form-item">
            <text class="label">购买价格（元）</text>
            <input v-model="form.cost" type="number" placeholder="请输入购买价格" />
          </view>
          <view class="form-item">
            <text class="label">预计使用年限（年）</text>
            <input v-model="form.expectLife" type="number" placeholder="请输入使用年限" />
          </view>
          <view class="form-item">
            <text class="label">出厂编号</text>
            <textarea v-model="form.code" placeholder="请输入出厂编号" />
          </view>
          <view class="form-item">
            <text class="label">单日成本（元）</text>
            <input v-model="form.dayCost" type="number" placeholder="请输入单日成本" />
          </view>
          <view class="form-item">
            <text class="label">管理部门</text>
            <uni-data-select v-model="form.manageDept" :localdata="deptOptions" placeholder="请选择管理部门" />
          </view>
          <view class="form-item">
            <text class="label">设备状态</text>
            <uni-data-select v-model="form.status" :localdata="statusOptions" placeholder="请选择设备状态" />
          </view>
          <view class="form-item">
            <text class="label">设备编号</text>
            <input v-model="form.deviceNumber" placeholder="请输入设备编号" />
          </view>
          <view class="form-item">
            <text class="label">备注</text>
            <textarea v-model="form.remark" placeholder="请输入备注信息" />
          </view>
        </scroll-view>
        <view class="popup-footer">
          <button class="popup-btn cancel" @click="closeFormPopup">取消</button>
          <button class="popup-btn primary" @click="submitForm">确定</button>
        </view>
      </view>
    </uni-popup>

    <!-- 日期选择器 -->
    <uv-calendar ref="calendar" mode="single" @confirm="confirmDate"></uv-calendar>
  </view>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from "@/api/oa/device/device";

export default {
  name: "InstrumentsList",
  data() {
    return {
      // 滚动相关
      scrollTop: 0,
      isRefreshing: false,
      hasMore: true,

      // 筛选相关
      showFilter: false,

      // 列表数据
      deviceList: [],
      total: 0,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        name: '',
        status: '',
        brand: '',
        code: '',
        series: ''
      },

      // 表单数据
      form: {},
      isEdit: false,

      // 当前查看的设备
      currentDevice: {},

      // 选项数据
      statusOptions: [
        { value: '0', text: '被领用' },
        { value: '1', text: '可领用' },
        { value: '2', text: '维修中' },
        { value: '3', text: '已停用' },
        { value: '4', text: '已报废' }
      ],
      typeOptions: [
        { value: '仪器设备', text: '仪器设备' },
        { value: '办公设备', text: '办公设备' }
      ],
      deptOptions: []
    };
  },

  onLoad() {
    this.getList();
    this.getDeptOptions();
  },

  methods: {
    // 获取设备列表
    async getList() {
      try {
        const response = await listDevice(this.queryParams);
        if (this.queryParams.pageNum === 1) {
          this.deviceList = response.rows || [];
        } else {
          this.deviceList = [...this.deviceList, ...(response.rows || [])];
        }
        this.total = response.total || 0;
        this.hasMore = this.deviceList.length < this.total;
      } catch (error) {
        console.error('获取设备列表失败:', error);
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      }
    },

    // 获取部门选项
    async getDeptOptions() {
      try {
        // 这里需要根据实际的部门API进行调整
        const deptList = this.$store.state.user.deptList || [];
        this.deptOptions = deptList.map(dept => ({
          value: dept.deptId,
          text: dept.deptName
        }));
      } catch (error) {
        console.error('获取部门列表失败:', error);
      }
    },

    // 搜索相关方法
    handleSearchInput() {
      // 可以在这里添加防抖搜索
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    clearSearch() {
      this.queryParams.name = '';
      this.handleQuery();
    },

    toggleFilter() {
      this.showFilter = !this.showFilter;
    },

    // 滚动相关方法
    upper() {
      // 下拉刷新
    },

    lower() {
      if (this.hasMore) {
        this.queryParams.pageNum++;
        this.getList();
      }
    },

    scroll(e) {
      this.scrollTop = e.detail.scrollTop;
    },

    async onRefresh() {
      this.isRefreshing = true;
      this.queryParams.pageNum = 1;
      await this.getList();
      this.isRefreshing = false;
    },

    // 设备操作方法
    handleViewDetail(item) {
      this.currentDevice = item;
      this.$refs.detailPopup.open();
    },

    closeDetailPopup() {
      this.$refs.detailPopup.close();
    },

    handleViewLogs() {
      this.closeDetailPopup();
      uni.navigateTo({
        url: `/pages/oa/device/deviceLog?deviceId=${this.currentDevice.deviceId}`
      });
    },

    handleAdd() {
      this.isEdit = false;
      this.resetForm();
      this.$refs.formPopup.open();
    },

    async handleUpdate(item) {
      this.isEdit = true;
      try {
        const response = await getDevice(item.deviceId);
        this.form = response.data || {};
        this.$refs.formPopup.open();
      } catch (error) {
        console.error('获取设备详情失败:', error);
        uni.showToast({
          title: '获取设备详情失败',
          icon: 'none'
        });
      }
    },

    closeFormPopup() {
      this.$refs.formPopup.close();
    },

    async handleDelete(item) {
      uni.showModal({
        title: '确认删除',
        content: `是否确认删除设备"${item.name}"？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await delDevice(item.deviceId);
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
              this.getList();
            } catch (error) {
              console.error('删除设备失败:', error);
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },

    // 表单相关方法
    resetForm() {
      this.form = {
        deviceId: null,
        brand: '',
        name: '',
        type: '仪器设备',
        series: '',
        acquisitionTime: '',
        place: '',
        cost: '',
        expectLife: '',
        code: '',
        dayCost: '',
        manageDept: '',
        status: '1',
        deviceNumber: '',
        remark: ''
      };
    },

    openDatePicker() {
      this.$refs.calendar.open();
    },

    confirmDate(e) {
      this.form.acquisitionTime = e.result;
    },

    async submitForm() {
      // 表单验证
      if (!this.form.name) {
        uni.showToast({
          title: '请输入设备名称',
          icon: 'none'
        });
        return;
      }

      try {
        if (this.isEdit) {
          await updateDevice(this.form);
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          });
        } else {
          await addDevice(this.form);
          uni.showToast({
            title: '新增成功',
            icon: 'success'
          });
        }

        this.closeFormPopup();
        this.getList();
      } catch (error) {
        console.error('保存设备失败:', error);
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    },

    // 工具方法
    formatDate(date) {
      if (!date) return '暂无';
      return new Date(date).toLocaleDateString();
    },

    statusTypeText(status) {
      const statusMap = {
        '0': '被领用',
        '1': '可领用',
        '2': '维修中',
        '3': '已停用',
        '4': '已报废'
      };
      return statusMap[status] || '未知';
    },

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

    hasPermission(permission) {
      // 这里需要根据实际的权限系统进行调整
      return true;
    }
  }
};
</script>

<style lang="scss" scoped>
.device-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.search-section {
  background: #fff;
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
}

.search-bar {
  margin-bottom: 10px;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background: #f8f8f8;
  border-radius: 20px;
  padding: 8px 15px;

  .search-input {
    flex: 1;
    margin-left: 8px;
    font-size: 14px;
  }
}

.filter-section {
  background: #f8f8f8;
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 10px;
}

.filter-row {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;

  &:last-child {
    margin-bottom: 0;
  }
}

.filter-item {
  flex: 1;

  .filter-label {
    font-size: 12px;
    color: #666;
    margin-bottom: 5px;
    display: block;
  }

  input {
    width: 100%;
    padding: 6px 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 12px;
  }
}

.filter-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  font-size: 14px;
  color: #666;
  padding: 8px;
}

.device-list {
  flex: 1;
}

.content-wrapper {
  padding: 15px;
}

.device-card {
  background: #fff;
  border-radius: 12px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.device-info {
  flex: 1;

  .device-name {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    display: block;
    margin-bottom: 4px;
  }

  .device-brand {
    font-size: 12px;
    color: #666;
  }
}

.device-content {
  padding: 15px;
}

.info-row {
  display: flex;
  margin-bottom: 8px;

  &:last-child {
    margin-bottom: 0;
  }

  .info-label {
    width: 80px;
    font-size: 13px;
    color: #666;
    flex-shrink: 0;
  }

  .info-value {
    flex: 1;
    font-size: 13px;
    color: #333;

    &.price,
    &.cost {
      color: #ff6b35;
      font-weight: 600;
    }
  }
}

.device-actions {
  display: flex;
  border-top: 1px solid #f0f0f0;

  .action-btn {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    padding: 12px;
    background: none;
    border: none;
    font-size: 13px;

    &.view {
      color: #007AFF;
    }

    &.edit {
      color: #FF9500;
      border-left: 1px solid #f0f0f0;
    }

    &.delete {
      color: #FF3B30;
      border-left: 1px solid #f0f0f0;
    }
  }
}

.loading-more,
.no-more {
  text-align: center;
  padding: 20px;

  .loading-text,
  .no-more-text {
    font-size: 14px;
    color: #999;
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;

  .empty-image {
    width: 120px;
    height: 120px;
    margin-bottom: 20px;
  }

  .empty-text {
    font-size: 16px;
    color: #666;
    display: block;
    margin-bottom: 8px;
  }

  .empty-subtext {
    font-size: 14px;
    color: #999;
  }
}

.fab-button {
  position: fixed;
  right: 20px;
  bottom: 30px;
  width: 56px;
  height: 56px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  z-index: 999;
}

// 弹窗样式
.detail-popup,
.form-popup {
  background: #fff;
  border-radius: 12px;
  width: 90vw;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;

  .title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }
}

.popup-body {
  flex: 1;
  padding: 20px;
  max-height: 60vh;
}

.detail-item {
  display: flex;
  margin-bottom: 15px;

  .detail-label {
    width: 80px;
    font-size: 14px;
    color: #666;
    flex-shrink: 0;
  }

  .detail-value {
    flex: 1;
    font-size: 14px;
    color: #333;

    &.price,
    &.cost {
      color: #ff6b35;
      font-weight: 600;
    }
  }
}

.form-item {
  margin-bottom: 20px;

  .label {
    font-size: 14px;
    color: #333;
    margin-bottom: 8px;
    display: block;
  }

  input,
  textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 14px;
    background: #f8f8f8;

    &:focus {
      border-color: #667eea;
      background: #fff;
    }
  }

  textarea {
    min-height: 80px;
    resize: none;
  }

  .date-picker {
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 8px;
    background: #f8f8f8;
    font-size: 14px;

    .placeholder {
      color: #999;
    }
  }
}

.popup-footer {
  display: flex;
  gap: 15px;
  padding: 20px;
  border-top: 1px solid #f0f0f0;

  .popup-btn {
    flex: 1;
    padding: 12px;
    border-radius: 8px;
    font-size: 16px;
    border: none;

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

    &.primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #fff;
    }
  }
}
</style>