<!--
 * @Author: ysh
 * @Date: 2025-07-08 14:00:47
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-08-12 09:32:32
-->
<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>
            <uni-easyinput v-model="queryParams.brand" placeholder="品牌筛选" @confirm="handleQuery" @blur="handleQuery"
              :inputBorder="false" :styles="{
                backgroundColor: '#fff',
                borderRadius: '8px',
                border: '1px solid #e0e0e0'
              }" />
          </view>
        </view>
        <view class="filter-row">
          <view class="filter-item">
            <text class="filter-label">出厂编号</text>
            <uni-easyinput v-model="queryParams.code" placeholder="编号筛选" @confirm="handleQuery" @blur="handleQuery"
              :inputBorder="false" :styles="{
                backgroundColor: '#fff',
                borderRadius: '8px',
                border: '1px solid #e0e0e0'
              }" />
          </view>
          <view class="filter-item">
            <text class="filter-label">规格型号</text>
            <uni-easyinput v-model="queryParams.series" placeholder="型号筛选" @confirm="handleQuery" @blur="handleQuery"
              :inputBorder="false" :styles="{
                backgroundColor: '#fff',
                borderRadius: '8px',
                border: '1px solid #e0e0e0'
              }" />
          </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>

    <!-- 设备列表 -->
    <mescroll-uni ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption"
      :up="upOption" :fixed="false" :top="10" style="padding: 30rpx;">
      <view>
        <view v-for="(item, index) in deviceList" :key="index" class="device-card" @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-show="checkPermi(['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-show="checkPermi(['oa:device:remove'])">
              <uni-icons type="trash" size="14" color="#FF3B30"></uni-icons>
              <text>删除</text>
            </button>
          </view>
        </view>
      </view>
    </mescroll-uni>

    <!-- 悬浮按钮 -->
    <view class="fab-button" @click="handleAdd" v-if="checkPermi(['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>
            <uni-easyinput v-model="form.brand" placeholder="请输入设备品牌" />
          </view>
          <view class="form-item">
            <text class="label">设备名称 *</text>
            <uni-easyinput 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>
            <uni-easyinput 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>
            <uni-easyinput v-model="form.place" placeholder="请输入存放地点" />
          </view>
          <view class="form-item">
            <text class="label">购买价格（元）</text>
            <uni-easyinput v-model="form.cost" type="number" placeholder="请输入购买价格" />
          </view>
          <view class="form-item">
            <text class="label">预计使用年限（年）</text>
            <uni-easyinput v-model="form.expectLife" type="number" placeholder="请输入使用年限" />
          </view>
          <view class="form-item">
            <text class="label">出厂编号</text>
            <uni-easyinput v-model="form.code" type="textarea" placeholder="请输入出厂编号" :autoHeight="true" />
          </view>
          <view class="form-item">
            <text class="label">单日成本（元）</text>
            <uni-easyinput 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>
            <uni-easyinput v-model="form.deviceNumber" placeholder="请输入设备编号" />
          </view>
          <view class="form-item">
            <text class="label">备注</text>
            <uni-easyinput v-model="form.remark" type="textarea" placeholder="请输入备注信息" :autoHeight="true" />
          </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";
import { checkPermi, checkRole } from "@/utils/permission";
import MescrollMixin from '@/uni_modules/mescroll/components/mescroll-uni/mescroll-mixins.js'

export default {
  name: "InstrumentsList",
  mixins: [MescrollMixin],
  data() {
    return {
      // mescroll相关
      mescroll: null, // mescroll实例
      downOption: {
        auto: true,
        textOutOffset: '下拉刷新',
        textLoading: '加载中...'
      },
      upOption: {
        auto: false,
        page: { num: 1, size: 20 },
        noMoreSize: 5,
        empty: { tip: '暂无设备数据' },
        textNoMore: '~ 没有更多数据了 ~'
      },

      // 筛选相关
      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.getDeptOptions();
  },

  methods: {
    checkPermi,
    checkRole,

    // 加载数据
    async loadData() {
      try {
        const response = await listDevice(this.queryParams);
        return { data: response.rows || [], total: response.total || 0 };
      } catch (error) {
        console.error('获取设备列表失败:', error);
        return { data: [], error: true };
      }
    },

    mescrollInit(mescroll) {
      this.mescroll = mescroll;
    },

    // mescroll下拉刷新回调
    async downCallback() {
      this.deviceList = []; // 清空列表
      this.queryParams.pageNum = 1;
      const res = await this.loadData();
      if (res.error) {
        this.mescroll.endErr();
      } else {
        this.deviceList = res.data;
        this.mescroll.endSuccess(res.data.length, res.total);
      }
      uni.stopPullDownRefresh();
    },

    // mescroll上拉加载回调
    async upCallback(page) {
      this.queryParams.pageNum = page.num;
      const res = await this.loadData();
      if (res.error) {
        this.mescroll.endErr();
      } else {
        this.deviceList = this.deviceList.concat(res.data);
        this.mescroll.endSuccess(res.data.length, res.total);
      }
    },

    // 获取设备列表（保留原有方法，用于其他操作后刷新）
    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;
      } 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.downCallback();
    },

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

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

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

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

    handleViewLogs() {
      this.closeDetailPopup();
    },

    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.downCallback(); // 使用mescroll刷新
            } 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.downCallback(); // 使用mescroll刷新
      } 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: 13px;
    color: #666;
    margin-bottom: 8px;
    display: block;
    font-weight: 500;
  }

  // uni-easyinput 样式
  :deep(.uni-easyinput) {
    height: 40px !important;
    border-radius: 8px !important;

    .uni-easyinput__content {
      height: 100% !important;
      border-radius: 8px !important;
      border: 1px solid #e0e0e0 !important;
      background: #fff !important;
      transition: all 0.3s ease;

      &:focus-within {
        border-color: #6366f1 !important;
        box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1) !important;
      }
    }

    .uni-easyinput__content-input {
      padding: 0 12px !important;
      font-size: 14px !important;
      color: #333 !important;

      &::placeholder {
        color: #a0a0a0 !important;
        font-size: 13px !important;
      }
    }
  }
}

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

.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;
  background: linear-gradient(90deg, #e0e7ff 0%, #f8fafc 100%);
}

.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: 5px;
    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;
    }
  }
}

.fab-button {
  position: fixed;
  right: 20px;
  bottom: 30px;
  width: 56px;
  height: 56px;
  background: #6366f1;
  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;
  }

  // uni-easyinput 样式
  :deep(.uni-easyinput) {
    .uni-easyinput__content {
      height: 45px !important;
      border: 1px solid #ddd !important;
      border-radius: 8px !important;
      background: #f8f8f8 !important;
      transition: all 0.3s ease;

      &:focus-within {
        border-color: #667eea !important;
        background: #fff !important;
        box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1) !important;
      }
    }

    .uni-easyinput__content-input {
      padding: 0 12px !important;
      font-size: 14px !important;
      color: #333 !important;

      &::placeholder {
        color: #999 !important;
      }
    }

    // textarea 样式
    &.uni-easyinput--textarea {
      .uni-easyinput__content {
        height: auto !important;
        min-height: 80px !important;
      }

      .uni-easyinput__content-textarea {
        padding: 12px !important;
        font-size: 14px !important;
        color: #333 !important;
        min-height: 60px !important;

        &::placeholder {
          color: #999 !important;
        }
      }
    }
  }

  .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: 10px;
  border-top: 1px solid #f0f0f0;

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

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

    &.primary {
      background: #6366f1;
      color: #fff;
    }
  }
}
</style>