<template>
  <view class="page-container">
    <view class="page-body">
      <!-- 出库表单 -->
      <view class="form-section">
        <view class="form-group">
          <view class="form-item">
            <text class="form-label">数字识别码</text>
            <view class="input-row">
              <input class="form-input" v-model="formData.digital_id" placeholder="输入或扫码" />
              <view class="input-extra" style="margin-left: 8px;">
                <button class="btn btn-sm btn-outline" @click="scanCode">扫码</button>
              </view>
            </view>
          </view>

          <view class="form-item">
            <text class="form-label">去向</text>
            <picker class="form-value" :range="directionOptions" range-key="label" :value="directionIndex" @change="onDirectionChange">
              <text>{{ formData.direction_name || '请选择去向' }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </picker>
          </view>

          <!-- <view class="form-item">
            <text class="form-label">贮存设施</text>
            <picker class="form-value" :range="storageFacilityOptions" range-key="label" :value="storageFacilityIndex" @change="onStorageFacilityChange">
              <text>{{ formData.storage_facility_name || '请选择贮存设施' }}</text>
            </picker>
          </view> -->

          <view class="form-item">
            <text class="form-label">出库时间</text>
            <picker class="form-value" mode="date" :value="formData.time" @change="e => formData.time = e.detail.value">
              <view>{{ formData.time || '选择日期' }}</view>
            </picker>
          </view>

        </view>
      </view>

      <!-- 自动扫码出库开关 -->
      <view class="auto-outbound-section">
        <view class="form-item switch-row">
          <text class="form-label">自动扫码出库</text>
          <switch :checked="autoOutboundSwitch" @change="onAutoOutboundSwitchChange" color="#007AFF" />
        </view>
      </view>

      <!-- 按钮 -->
      <view class="btn-area" v-if="!autoOutboundSwitch">
        <button class="btn btn-primary btn-block" :disabled="!canSubmit" @click="handleSubmit(false)">确认出库</button>
      </view>

      <!-- 扫码出库记录 -->
      <scan-records 
        :records="scanRecords"
        title="扫码记录"
        empty-text="暂无出库记录"
        @clear="clearScanRecords"
      />

      <!-- 出库历史 -->
      <inout-history
        :records="outRecords"
        title="出库历史"
        empty-text="暂无出库历史"
      />
    </view>
  </view>
</template>

<script>
import { api } from '@/api'
import { getDate, getTime, getDateTime} from '@/utils/common.js'
// #ifdef APP-PLUS
import scan from '@/utils/scan.js'
// #endif
import ScanRecords from '@/components/common/scan-records.vue'
import InoutHistory from '@/components/common/inout-history.vue'
import { mapState } from 'vuex'

export default {
  components: {
    ScanRecords,
    InoutHistory
  },
  data() {
    return {
      autoOutboundSwitch: true,
      scanRecords: [],
      isAutoSubmitting: false,
      formData: {
        digital_id: '',
        destination: '',
        direction_name: '',
        time: ''
      },
      directionOptions: [
        { value: 'wwlycz', label: '委外利用处置' },
        { value: 'lycz', label: '利用处置' },
        { value: 'zxlycz', label: '自行利用处置' }
      ],
      directionIndex: 0,
      outRecords: [],
      default: {},
      dict: {}
    }
  },
  computed: {
    ...mapState('scan', ['scanMode']),
    canSubmit() {
      return this.formData.digital_id && this.formData.destination && this.formData.time
    }
  },
  onLoad() {
    // #ifdef APP-PLUS
    // 仅APP端初始化原生扫码模块
    this.initScanner()
    // #endif
    this.formData.time = getDateTime()
  },
  mounted() {
    this.initData()
  },
  onUnload() {
    // #ifdef APP-PLUS
    // 仅APP端销毁原生扫码模块
    this.cleanupScanner()
    // #endif
  },
  methods: {
    /** 初始化数据 */
    async initData() {
      // 初始化去向默认选中第一项
      const firstDirection = this.directionOptions[0]
      this.formData.destination = firstDirection.value
      this.formData.direction_name = firstDirection.label
      this.directionIndex = 0

      await this.getOutRecords()
      await this.getOperators()
      await this.getDefault()
    },
    /** 获取出库历史记录 */
    async getOutRecords() {
      this.outRecords = await api.hwOutlist({ zdbm: 'ckjbr'}).then(res => {
        return res.data.list
      })
    },
    // 获取默认配置
    async getDefault() {
      this.default = await api.defaultParams().then(res => {
        console.log(res)
        return res.data
      })
      console.log('default', this.default)
      // this.dict = await api.hwDict().then(res => {
      //   return res.data
      // })
    },
    // 获取经办人
    async getOperators() {
      // 1.产生，2.贮存，3.运送，4.出库
      const res = await api.handler({ type: 4 })
      console.log('handler', res)
      if (res.code == 1000) {
        this.operators = res.data.map(res => {
          return {
            id: res.handler_code,
            name: res.handler_name,
            code: res.handler_code
          }
        })
      }
    },

    // #ifdef APP-PLUS
    // ==================== APP原生扫码模块 ====================
    /**
     * 初始化扫码
     * 根据 store 中的 scanMode 设置 idata/android 模式，并注册扫码回调
     */
    initScanner() {
      try {
        scan.setMode(this.scanMode)
        scan.init()
        scan.register((codeStr) => {
          this.onBarcodeScanned(codeStr)
        })
      } catch (e) {
        console.error('[出库] 扫码初始化失败:', e)
      }
    },
    /** 页面卸载时注销扫码回调，防止内存泄漏 */
    cleanupScanner() {
      scan.unregister()
    },
    /** APP端扫码按钮：点一次开始扫描，再点一次停止扫描 */
    scanCode() {
      if (scan.isScanning()) {
        scan.stopScan()
      } else {
        scan.startScan()
      }
    },
    // #endif

    // #ifdef MP
    // ==================== 小程序兼容扫码模块 ====================
    /** 小程序端扫码按钮：调用uni跨平台扫码API */
    scanCode() {
      uni.scanCode({
        success: (res) => {
          this.onBarcodeScanned(res.result)
        },
        fail: (err) => {
          console.error('[出库] 小程序扫码失败:', err)
          if (err.errMsg && err.errMsg.indexOf('cancel') === -1) {
            uni.showToast({ title: '扫码失败', icon: 'none' })
          }
        }
      })
    },
    // #endif

    /** 扫码结果回调（APP/小程序通用）：填充数字识别码 -> 自动提交（如果开启） */
    onBarcodeScanned(barcode) {
      this.formData.digital_id = barcode
      uni.showToast({ title: '扫码成功 ' + barcode, icon: 'none' })
      if (this.autoOutboundSwitch && !this.isAutoSubmitting) {
        setTimeout(() => {
          if (this.canSubmit) {
            this.handleSubmit(true)
          }
        }, 300)
      }
    },

    // ==================== 表单选择器 ====================
    onDirectionChange(e) {
      this.directionIndex = e.detail.value
      const selected = this.directionOptions[this.directionIndex]
      this.formData.destination = selected.value
      this.formData.direction_name = selected.label
    },
    onAutoOutboundSwitchChange(e) {
      this.autoOutboundSwitch = e.detail.value
    },
    async handleSubmit(isAuto = false) {
      if (this.isAutoSubmitting) return
      if (isAuto) {
        this.isAutoSubmitting = true
      }
      try {
        const submitData = {
          // 扫码值(危废标签二维码或数字识别码)
          code: this.formData.digital_id,
          // 出库时间 yyyy-MM-dd HH:mm:ss
          time: this.formData.time,
          // 去向
          destination: this.formData.destination,
          // 贮存设施编码(可选)
          // storage_facility: this.formData.storage_facility
        }
        const res = await api.deviceHwOut(submitData)
        uni.showToast({ title: '出库成功', icon: 'success' })
        if (isAuto) {
          this.addScanRecord(this.formData.digital_id, 'success', '出库成功')
        }
        this.getOutRecords()   // 刷新出库历史
        this.resetForm()
      } catch (error) {
        // console.error('出库失败:', error)
        uni.showToast({ title: error.message, icon: 'none' })
        if (isAuto) {
          this.addScanRecord(this.formData.digital_id, 'error', '出库失败')
        }
      } finally {
        if (isAuto) {
          this.isAutoSubmitting = false
        }
      }
    },
    resetForm() {
      this.formData = {
        digital_id: '',
        destination: '',
        direction_name: '',
        time: getDateTime()
      }
      this.directionIndex = 0
    },
    addScanRecord(digitalId, status, message) {
      const time = getTime()
      this.scanRecords.unshift({ digitalId, status, message, time })
      if (this.scanRecords.length > 10) {
        this.scanRecords.pop()
      }
    },
    clearScanRecords() {
      this.scanRecords = []
    }
  }
}
</script>

<style lang="scss" scoped>
// 输入行（带按钮）
.input-row {
  display: flex;
  align-items: center;
  flex: 1;
}

.input-extra {
  display: flex;
  align-items: center;
}

// 单位文本
.unit-text {
  font-size: 14px;
  color: #666;
  margin-left: 8px;
}

// 错误文本
.error {
  color: #f00;
}

// 提示文本
.hint-text {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.btn-sm {
  padding: 0 12px;
  font-size: 13px;
  height: 32px;
  line-height: 32px;
}

// 自动扫码出库开关
.auto-outbound-section {
  padding: 0 16px;
}

.switch-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
}
</style>
