<template>
  <view class="page-container">
    <scroll-view class="page-body" scroll-y>
      <view class="device-section">
        <!-- 打印设备 -->
        <view class="device-card">
          <view class="device-header">
            <uni-icons custom-prefix="iconfont" type="icon-dayinji"size="20" color="#1890ff"></uni-icons>
            <text class="device-title">打印设备</text>
          </view>
          <view class="device-status">
            <view class="device-dot" :class="printerStatus.dotClass"></view>
            <text :style="{ color: printerStatus.color }">{{ printerStatus.text }}</text>
            <text style="color:#1890ff;margin-left:auto;">蓝牙</text>
          </view>
          <view class="device-info">
            <view class="info-row"><text class="label">连接方式</text><text class="value">蓝牙</text></view>
            <view class="info-row"><text class="label">打印机型号</text><text class="value">{{ printer.deviceName }}</text></view>
            <view class="info-row"><text class="label">标签尺寸</text><text class="value">{{ printer.size }}</text></view>
          </view>
          <view class="device-actions">
            <button class="btn btn-primary" @click="handlePrinter">配置</button>
            <button class="btn btn-primary" @click="testPrinter">测试设备</button>
            <button class="btn btn-outline" @click="debugPrinter">调试打印</button>
          </view>
        </view>

        <!-- 扫码配置 -->
        <view class="device-card">
          <view class="device-header">
            <uni-icons type="scan" size="20" color="#1890ff"></uni-icons>
            <text class="device-title">扫码配置</text>
          </view>
          <view class="device-status">
            <view class="device-dot paired"></view>
            <text style="color:#1890ff;">{{ scanModeText }}</text>
          </view>
          <view class="device-info">
            <view class="info-row">
              <text class="label">当前模式</text>
              <text class="value">{{ scanModeText }}</text>
            </view>
            <view class="info-row">
              <text class="label">说明</text>
              <text class="value" style="font-size:12px;color:#999;">
                {{ scanMode === 'uniapp' ? '使用默认摄像头扫码' : scanMode === 'idata' ? '仅支持 iData 设备内置扫码' : '通用 Android PDA 设备' }}
              </text>
            </view>
          </view>
          <view class="device-actions">
            <button class="btn btn-primary" @click="selectScanMode">切换扫码模式</button>
          </view>
        </view>

        <!-- 称重设备 -->
        <view class="device-card">
          <view class="device-header">
            <uni-icons custom-prefix="iconfont" type="icon-chengzhong"size="20" color="#1890ff"></uni-icons>
            <text class="device-title">称重设备</text>
          </view>
          <view class="device-status">
            <view class="device-dot" :class="scaleStatus.dotClass"></view>
            <text :style="{ color: scaleStatus.color }">{{ scaleStatus.text }}</text>
            <text style="color:#1890ff;margin-left:auto;">蓝牙</text>
          </view>
          <view class="device-info">
            <view class="info-row"><text class="label">连接方式</text><text class="value">蓝牙</text></view>
            <view class="info-row"><text class="label">称重仪器</text><text class="value">{{ scale.model }}</text></view>
            <view class="info-row"><text class="label">小数精度</text><text class="value">{{ scale.precision }}</text></view>
            <view class="info-row"><text class="label">重量单位</text><text class="value">{{ scale.unit }}</text></view>
          </view>
          <view class="device-actions">
            <button class="btn btn-outline" @click="handleScale">配置</button>
            <button class="btn btn-primary" @click="testScale">测试设备</button>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { mapGetters, mapState } from 'vuex';

export default {
  computed: {
    ...mapState('print', ['printerConfig']),
    ...mapState('scale', ['scaleConfig']),
    ...mapState('scan', ['scanMode']),

    // 打印机状态计算（只有未配置和已配对两种）
    printerStatus() {
      const config = this.printerConfig
      if (config.deviceId) {
        return { text: '已配对', color: '#1890ff', dotClass: 'paired' }
      }
      return { text: '未配置', color: '#999', dotClass: 'offline' }
    },

    // 打印机信息
    printer() {
      const config = this.printerConfig
      return {
        deviceName: config.deviceName || '-',
        size: config.paperWidth && config.paperHeight
          ? `${config.paperWidth}×${config.paperHeight}mm`
          : '-'
      }
    },

    // 称重设备状态计算
    scaleStatus() {
      const config = this.scaleConfig
      if (config.deviceId) {
        return { text: '已配对', color: '#1890ff', dotClass: 'paired' }
      }
      return { text: '未配置', color: '#999', dotClass: 'offline' }
    },

    // 称重设备信息
    scale() {
      const config = this.scaleConfig
      return {
        model: config.model || '-',
        precision: config.precision ? `${config.precision}位` : '-',
        unit: config.unit || '-'
      }
    },

    // 扫码模式文字
    scanModeText() {
      const map = { 
        uniapp: '安卓设备', 
        idata: 'IDATA PDA设备', 
        android: '带扫码PDA设备' 
      }
      return map[this.scanMode] || '安卓设备'
    }
  },
  onLoad() {
    this.$store.dispatch('scan/initScanMode')
    this.$store.dispatch('scale/initScaleConfig')  // 初始化称重配置
  },
  methods: {
    handlePrinter() {
      uni.navigateTo({
        url: '/pages/settings/devices/printer'
      })
    },
    handleScale() {
      uni.navigateTo({
        url: '/pages/settings/devices/scale'
      })
    },
    testPrinter() {
      uni.navigateTo({
        url: '/pages/settings/devices/configPrinter'
      })
    },
    testScale() {
      uni.navigateTo({
        url: '/pages/settings/devices/scaleTest'
      })
    },
    debugPrinter() {
      uni.navigateTo({
        // url: '/pages/testpages/blerinte'
        url: '/pages/settings/devices/printTest'
      })
    },

    // === 扫码模式切换 ===
    async selectScanMode() {
      try {
        // 使用对象数组，key:value 形式定义选项
        const modeOptions = [
          { key: 'uniapp', label: '安卓设备' },
          { key: 'idata', label: 'IDATA PDA设备' },
          { key: 'android', label: '带扫码PDA设备' }
        ]
        
        const res = await uni.showActionSheet({
          itemList: modeOptions.map(m => m.label) // 提取标签显示
        })
        
        // 兼容不同平台的返回值格式
        // 注意：某些情况下返回值可能是数组 [null, {errMsg, tapIndex}]
        let tapIndex = null
        if (Array.isArray(res)) {
          // 数组格式：[null, {errMsg: "showActionSheet:ok", tapIndex: 0}]
          const data = res[1] || res[0]
          tapIndex = data ? (data.tapIndex !== undefined ? data.tapIndex : data.index) : null
        } else if (res && typeof res === 'object') {
          // 对象格式：{errMsg: "showActionSheet:ok", tapIndex: 0}
          tapIndex = res.tapIndex !== undefined ? res.tapIndex : res.index
        }
        
        if (tapIndex === undefined || tapIndex === null) {
          console.error('[Device] 无法获取用户选择:', res)
          return
        }
        
        const mode = modeOptions[tapIndex].key // 直接获取对应的 key
        if (!mode) {
          console.error('[Device] 无效的模式索引:', tapIndex)
          return
        }
        
        console.log('[Device] 切换扫码模式为:', mode)
        this.$store.dispatch('scan/setScanMode', mode)
        uni.showToast({ title: '已切换为' + this.scanModeText, icon: 'none' })
      } catch (err) {
        // 用户取消选择，不处理
        console.log('[Device] 用户取消扫码模式选择')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.device-section {
  padding: $spacing-md;
}

.device-card {
  background: #ffffff;
  border-radius: $border-radius-md;
  padding: $spacing-md;
  margin-bottom: $spacing-base;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.device-header {
  display: flex;
  align-items: center;
  gap: $spacing-sm;
  margin-bottom: $spacing-base;
}

.device-title {
  font-size: $font-size-md;
  color: $text-primary;
  font-weight: 600;
}

.device-status {
  display: flex;
  align-items: center;
  gap: $spacing-sm;
  margin-bottom: $spacing-base;
}

.device-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;

  &.online {
    background: #52c41a;
  }

  &.paired {
    background: #1890ff;
  }

  &.offline {
    background: #999;
  }
}

.device-info {
  border-top: 1px solid $border-light;
  padding-top: $spacing-sm;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacing-sm 0;
  border-bottom: 1px solid $border-light;
  font-size: $font-size-sm;

  &:last-child {
    border-bottom: none;
  }

  .label {
    color: $text-secondary;
  }

  .value {
    color: $text-primary;
  }
}

.device-actions {
  display: flex;
  gap: $spacing-sm;
  margin-top: $spacing-base;
}
</style>
