<template>
  <div>
    <div class="pda-container">
      <div class="status-bar">
        <div class="goBack" @click="handleBack"><i class="el-icon-arrow-left"></i>上一页</div>
        <div class="goBack">{{ functionTitle }}</div>
        <div class="network" style="color: #fff" @click="$router.push({ path: '/' })">🏠首页</div>
      </div>
      <div style="overflow-y: auto">
        <!-- 功能选择 -->
<!--        <div class="function-selector" v-if="processFlag === 1">-->
<!--          <div class="function-card" @click="selectFunction('direct')">-->
<!--            <div class="function-icon">📦</div>-->
<!--            <div class="function-title">直接发料</div>-->
<!--            <div class="function-desc">扫描调墨标签或输入条码桶号发料</div>-->
<!--          </div>-->
<!--        </div>-->

        <!-- 直接发料 -->
        <div class="direct-issue">
          <!-- 工单输入 -->
          <div class="input-section">
            <div class="input-group">
              <label>桶号</label>
              <div class="input-with-scan">
                <input v-model="directIssueForm.bucketNo" placeholder="请扫描调墨标签或输入条码桶号"
                  @keyup.enter="bucketNoEnter1" ref="scannerInput"/>
                <button @click="bucketNoEnter1" class="scan-btn">确认</button>
              </div>
            </div>
            <div class="input-group" v-if="mixInkOrderList.length">
              <label>设备编码</label>
              <div class="input-with-scan">
                <input v-model="directIssueForm.deviceNo" placeholder="请扫描机台条码或输入机台编码" ref="scannerInput2"/>
                <button @click="sendHandle" class="scan-btn">发送</button>
              </div>
            </div>
            <div class="materials-section" v-if="mixInkOrderList.length">
              <div class="material-list">
                <div v-for="(mixInkOrder, index) in mixInkOrderList" :key="index" class="material-item">
                  <div class="material-info">
                    <div class="part-no">{{ mixInkOrder.orderNo }}</div>
                    <div class="part-desc">{{ mixInkOrder.inkPartNo+' '+mixInkOrder.inkPartDesc }}</div>
                    <div class="qty-info">
                      需求重量: {{ mixInkOrder.needWeight+'g  ' }} |
                      实际重量: {{ mixInkOrder.actualWeight+'g' }}
                    </div>
                    <div class="qty-info">
                      是否可回收: {{ mixInkOrder.recyclableFlag === 'Y' ? '是' : '否' }} |
                      是否预调墨: {{ mixInkOrder.preFlag === 'Y' ? '是' : '否' }}
                    </div>
                  </div>
                  <div class="material-status">
                    <span  class="status-pending">待发送</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载提示 -->
      <div class="loading" v-if="loading">
        <div class="loading-spinner"></div>
        <div class="loading-text">{{ loadingText }}</div>
      </div>

      <!-- 消息提示 -->
      <div class="message" v-if="message" :class="messageType">{{ message }}</div>
    </div>
  </div>
</template>

<script>
import {getOrderInfoByBucketNoForPda, sendInkHandle} from '../../../api/production/production-issue'

export default {
  name: 'ProductionIssuePDA',
  data() {
    return {
      processFlag: 1, // 1=功能选择, 2=主表单, 3=物料列表, 4=扫描标签
      selectedFunction: null,
      loading: false,
      loadingText: '',
      message: '',
      messageType: 'info',

      // 直接发料
      directIssueForm: {
        site: this.$store.state.user.site,
        bucketNo: '',
        deviceNo: '',
        orderNo: '',
        demandNo: '',
        inkPartNo: '',
        inkPartDesc: '',
        needWeight: 0,
        recyclableFlag: false,
        preFlag: false,
        actualWeight: 0,
        createBy: this.$store.state.user.name,
        updateBy: this.$store.state.user.name,
      },
      mixInkOrderList: [],
      currentPallet: {},
      scannedUnit: '',

      // 通用
      scannedLabel: '',
      labelInfo: null,
      showScanLabel: false,
      scanLabelContext: {},
      scanLabelData: {},
      scanTableInput: '',
      scanTableData: [],
    }
  },
  computed: {
    functionTitle() {
      if (!this.selectedFunction) return '生产发料'
      if (this.selectedFunction === 'direct') return '直接发料'
      if (this.selectedFunction === 'picking') return '拣选装托盘'
      if (this.selectedFunction === 'request') return '申请单发料'
      return '生产发料'
    },
  },
  created () {
    // 聚焦
    this.$nextTick(() => {
      this.$refs.scannerInput.focus();
    });
  },
  methods: {
    handleBack() {
      if (this.processFlag === 3) {
        this.processFlag = 2
        this.showScanLabel = false
      } else if (this.processFlag === 2) {
        this.processFlag = 1
        this.selectedFunction = null
      } else if (this.processFlag === 1) {
        this.$router.push('/')
      }
    },

    bucketNoEnter1 () {
      if (this.directIssueForm.bucketNo) {
        let tempData = {
          site: localStorage.getItem('site'),
          bucketNo: this.directIssueForm.bucketNo
        }
        this.loading = true
        this.loadingText = '加载调墨工单...'
        getOrderInfoByBucketNoForPda(tempData).then(({ data }) => {
          if (data.code === 0) {
            this.mixInkOrderList[0] = data.row;
            // 等待1S
            setTimeout(() => {
              // 聚焦
              this.$nextTick(() => {
                this.$refs.scannerInput2.focus();
              });
            }, 500);
          } else {
            this.mixInkOrderList = []
            this.showMessage('获取工单单信息失败：' + data.msg, 'warning')
          }
          this.loading = false
        });
      } else {
        this.showMessage('请先输入或扫描桶号！', 'error');
      }
    },

    sendHandle(){
      if (this.directIssueForm.deviceNo){
        let tempData = {
          site: localStorage.getItem('site'),
          demandNo: this.mixInkOrderList[0].demandNo,
          deviceNo: this.directIssueForm.deviceNo,
          updateBy: localStorage.getItem('userName'),
          recyclableFlag: this.mixInkOrderList[0].recyclableFlag,
          taskId: this.mixInkOrderList[0].taskId,
          inventoryStockEntity : {
            partNo: this.mixInkOrderList[0].inkPartNo,
            partDesc: this.mixInkOrderList[0].inkPartDesc,
            bucketNo: this.directIssueForm.bucketNo,
            weight: this.mixInkOrderList[0].actualWeight,
            expirationDate: this.mixInkOrderList[0].expirationDate,
            entryDate: this.dayjs().format('YYYY-MM-DD'),
            usageWeight: 0.0,
            sampleFlag: this.mixInkOrderList[0].sampleFlag ? this.mixInkOrderList[0].sampleFlag : 'N',
            locationNo: '线边库库位',
            preFlag: this.mixInkOrderList[0].preFlag,
          }
        }
        this.loading = true
        this.loadingText = '发送中...'
        sendInkHandle(tempData).then(({data}) => {
          if (data.code === 0) {
            this.showMessage('发送成功', 'success');
            this.mixInkOrderList = []
            this.directIssueForm.bucketNo = ''
          } else {
            this.showMessage('发送失败：' + data.msg, 'warning');
          }
          this.loading = false
        });
      }else {
        this.showMessage('请先输入或扫描设备！', 'error');
      }
    },

    showMessage(text, type = 'info') {
      this.message = text
      this.messageType = type
      setTimeout(() => {
        this.message = ''
      }, 3000)
    },
  },
}
</script>

<style scoped>
.production-issue-pda {
  padding: 10px;
  font-family: Arial, sans-serif;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 功能选择 */
.function-selector {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 20px 0;
}

.function-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
}

.function-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.function-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.function-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.function-desc {
  font-size: 14px;
  color: #666;
}

/* 输入区域 */
.input-section,
.materials-section,
.scan-section,
.pallet-info,
.print-section {
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

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

.section-header h3,
.section-header h4 {
  margin: 0;
  color: #333;
}

.reset-btn {
  background: #17b3a3;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.input-group {
  margin-bottom: 15px;
}

.input-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #333;
}

.input-with-scan {
  display: flex;
  gap: 10px;
}

.input-with-scan input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.scan-btn,
.confirm-btn,
.print-btn {
  background: #17b3a3;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  white-space: nowrap;
}

.scan-btn:hover,
.confirm-btn:hover,
.print-btn:hover {
  background: #13998c;
}

.confirm-btn:disabled,
.print-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

/* 物料列表 */
.material-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.material-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.material-item:hover {
  border-color: #007bff;
  background-color: #f8f9fa;
}

.material-item.selected {
  border-color: #007bff;
  background-color: #e3f2fd;
}

.material-info {
  flex: 1;
}

.part-no {
  font-weight: bold;
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.part-desc {
  color: #666;
  font-size: 14px;
  margin-bottom: 4px;
}

.work-order {
  color: #007bff;
  font-size: 12px;
  margin-bottom: 4px;
}

.qty-info {
  font-size: 12px;
  color: #666;
}

.material-status {
  text-align: right;
}

.status-pending {
  background: #ffc107;
  color: #212529;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.status-complete {
  background: #28a745;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
}

/* 标签信息 */
.label-info,
.info-card {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 15px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.info-row:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.info-row .label {
  font-weight: bold;
  color: #666;
}

.info-row .value {
  color: #333;
}

/* 数量输入 */
.qty-input {
  margin-top: 15px;
}

.qty-input input[type='number'] {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

/* 托盘相关 */
.scan-bind-section {
  margin: 20px 0;
}

.bound-units {
  margin-top: 20px;
}

.unit-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 200px;
  overflow-y: auto;
}

.unit-item {
  background: #e9ecef;
  padding: 10px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 14px;
}

/* 加载和消息 */
.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  z-index: 1000;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 10px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 14px;
}

.message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 12px 20px;
  border-radius: 6px;
  font-weight: bold;
  z-index: 1001;
  max-width: 90%;
  text-align: center;
}

.message.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.message.warning {
  background: #fff3cd;
  color: #856404;
  border: 1px solid #ffeaa7;
}

.message.info {
  background: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .production-issue-pda {
    padding: 5px;
  }

  .function-card {
    padding: 15px;
  }

  .function-icon {
    font-size: 36px;
  }

  .input-with-scan {
    flex-direction: column;
  }

  .material-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .material-status {
    align-self: flex-end;
  }
}
.confirm-btn {
  width: 100%;
}
</style>
