<template>
  <div class="pda-container">
    <!-- 头部栏 -->
    <div class="header-bar">
      <div class="header-left" @click="$router.back()">
        <i class="el-icon-arrow-left"></i>
        <span>属性变动</span>
      </div>
      <div class="header-right" @click="$router.push({ path: '/' })">
        首页
      </div>
    </div>

    <!-- 搜索框 -->
    <div class="search-container">
      <el-input clearable
        v-model="scanCode"
        placeholder="请扫描标签条码"
        prefix-icon="el-icon-search"
        @keyup.enter.native="handleScan"
        ref="scanInput"
      />
    </div>

    <!-- 标签信息卡片 -->
    <div class="label-info-card" >
      <div class="info-row">
        <span class="info-label">标签条码</span>
        <span class="info-value">{{ stockInfo.labelCode || '' }}</span>
      </div>

      <div class="info-row">
        <span class="info-label">标签数量</span>
        <span class="info-value">{{ stockInfo.labelQuantity || '' }}</span>
      </div>

      <div class="info-row">
        <span class="info-label">所在仓库</span>
        <span class="info-value">{{ stockInfo.warehouseName || '' }}</span>
      </div>

      <div class="info-row">
        <span class="info-label">所在库位</span>
        <div class="input-wrapper">
          <el-input
            v-model="newLocationId"
            placeholder="请扫描/输入库位"
            class="location-input"
            @keyup.enter.native="focusNextInput"
          />
        </div>
      </div>

      <div class="info-row">
        <span class="info-label">标签状态</span>
        <span class="info-value" :class="stockInfo.status === '冻结' ? 'status-frozen' : 'status-normal'">{{ stockInfo.status || '' }}</span>
      </div>

      <div class="info-row">
        <span class="info-label">生产日期</span>
        <div class="input-wrapper">
          <el-date-picker
            v-model="newProductionDate"
            type="date"
            placeholder="选择生产日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            class="date-input"
          />
        </div>
      </div>

      <div class="info-row">
        <span class="info-label">有效期截止</span>
        <div class="input-wrapper">
          <el-date-picker
            v-model="newExpiryDate"
            type="date"
            placeholder="选择有效期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            class="date-input"
          />
        </div>
      </div>

      <div class="info-row">
        <span class="info-label">关联单号1</span>
        <span class="info-value">{{ stockInfo.orderref1 || '-' }}</span>
      </div>

      <div class="info-row">
        <span class="info-label">关联单号2</span>
        <span class="info-value">{{ stockInfo.orderref2 || '-' }}</span>
      </div>

      <div class="info-row">
        <span class="info-label">批次号</span>
        <span class="info-value">{{ stockInfo.batchNo  || ''}}</span>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="bottom-actions" v-if="stockInfo.labelCode">
      <button class="action-btn primary" @click="confirmChange">
        确定
      </button>
      <button class="action-btn secondary" @click="cancelChange">
        取消
      </button>
    </div>
  </div>
</template>

<script>
import { getStockInfoByLabelCode, savePropertyChange } from "@/api/property-change/property-change.js";
import { getCurrentWarehouse } from '@/utils'
import moment from 'moment';

export default {
  data() {
    return {
      scanCode: '',
      stockInfo: {},
      newLocationId: '',
      newProductionDate: '',
      newExpiryDate: ''
    };
  },
  methods: {
    // 处理扫描
    handleScan() {
      if (!this.scanCode.trim()) {
        return;
      }

      this.getStockInfo(this.scanCode.trim());
      this.scanCode = '';
    },

    // 获取库存信息
    getStockInfo(labelCode) {
      const params = {
        labelCode: labelCode,
        site: localStorage.getItem('site'),
        warehouseId: getCurrentWarehouse()
      };

      getStockInfoByLabelCode(params).then(({ data }) => {
        if (data && data.code === 0) {
          this.stockInfo = data.data;

          // 初始化输入值为当前值
          this.newLocationId = this.stockInfo.locationId || '';
          this.newProductionDate = this.stockInfo.productionDate ? moment(this.stockInfo.productionDate).format('YYYY-MM-DD') : '';
          this.newExpiryDate = this.stockInfo.expiryDate ? moment(this.stockInfo.expiryDate).format('YYYY-MM-DD') : '';

          this.$message.success('获取标签信息成功');
        } else {
          this.$message.error(data.msg || '未找到该标签的库存信息');
          this.stockInfo = {};
        }
      }).catch(error => {
        console.error('获取库存信息失败:', error);
        this.$message.error('获取库存信息失败');
        this.stockInfo = {};
      });
    },

    // 聚焦到下一个输入框
    focusNextInput() {
      // 可以根据需要实现聚焦逻辑
    },

    // 确认变动
    confirmChange() {
      if (!this.stockInfo.labelCode) {
        this.$message.warning('请先扫描标签条码');
        return;
      }

      // 检查是否有变动
      const oldLocationId = this.stockInfo.locationId || '';
      const oldProductionDate = this.stockInfo.productionDate ? moment(this.stockInfo.productionDate).format('YYYY-MM-DD') : '';
      const oldExpiryDate = this.stockInfo.expiryDate ? moment(this.stockInfo.expiryDate).format('YYYY-MM-DD') : '';

      const hasLocationChange = this.newLocationId !== oldLocationId;
      const hasProductionDateChange = this.newProductionDate !== oldProductionDate;
      const hasExpiryDateChange = this.newExpiryDate !== oldExpiryDate;

      if (!hasLocationChange && !hasProductionDateChange && !hasExpiryDateChange) {
        this.$message.warning('没有检测到属性变动，请修改后再提交');
        return;
      }

      // 构建保存参数
      const params = {
        site: localStorage.getItem('site'),
        buNo: this.stockInfo.buNo,
        warehouseId: getCurrentWarehouse(),
        labelCode: this.stockInfo.labelCode,
        partNo: this.stockInfo.partNo,
        batchNo: this.stockInfo.batchNo,
        quantity: this.stockInfo.qtyOnHand,
        oldLocationId: oldLocationId,
        newLocationId: this.newLocationId,
        oldProductionDate: oldProductionDate,
        newProductionDate: this.newProductionDate,
        oldExpiryDate: oldExpiryDate,
        newExpiryDate: this.newExpiryDate
      };

      // 确认对话框
      let changeMsg = '确认进行以下属性变动？\n';
      if (hasLocationChange) {
        changeMsg += `库位: ${oldLocationId} → ${this.newLocationId}\n`;
      }
      if (hasProductionDateChange) {
        changeMsg += `生产日期: ${oldProductionDate} → ${this.newProductionDate}\n`;
      }
      if (hasExpiryDateChange) {
        changeMsg += `有效期: ${oldExpiryDate} → ${this.newExpiryDate}\n`;
      }

      this.$confirm(changeMsg, '确认变动', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.saveChange(params);
      }).catch(() => {
        // 用户取消
      });
    },

    // 保存变动
    saveChange(params) {
      savePropertyChange(params).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success('操作成功');
          this.resetForm();
        } else {
          this.$message.error(data.msg || '保存失败');
        }
      }).catch(error => {
        console.error('保存属性变动失败:', error);
        this.$message.error('保存失败');
      });
    },

    // 取消变动
    cancelChange() {
      if (this.stockInfo.labelCode) {
        this.$confirm('确定要取消当前操作吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '继续操作',
          type: 'warning'
        }).then(() => {
          this.resetForm();
        }).catch(() => {
          // 用户选择继续操作
        });
      } else {
        this.$router.back();
      }
    },

    // 重置表单
    resetForm() {
      this.stockInfo = {};
      this.newLocationId = '';
      this.newProductionDate = '';
      this.newExpiryDate = '';

      // 聚焦扫描框
      this.$nextTick(() => {
        if (this.$refs.scanInput) {
          this.$refs.scanInput.focus();
        }
      });
    }
  },

  mounted() {
    // 聚焦扫描框
    this.$nextTick(() => {
      if (this.$refs.scanInput) {
        this.$refs.scanInput.focus();
      }
    });
  }
};
</script>

<style scoped>
.pda-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

/* 头部栏 */
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: #17B3A3;
  color: white;
  height: 40px;
  min-height: 40px;
}

.header-left {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
}

.header-left i {
  margin-right: 8px;
  font-size: 18px;
}

.header-right {
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
}

/* 搜索容器 */
.search-container {
  padding: 12px 16px;
  background: white;
}

.search-container .el-input {
  width: 100%;
}

/* 标签信息卡片 */
.label-info-card {
  background: white;
  margin: 8px 16px;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex: 1;
  overflow-y: auto;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 2px;
  min-height: 40px;
}

.info-label {
  width: 80px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  font-size: 14px;
  color: #666;
  margin-left: 12px;
}

.status-frozen {
  color: #ff4949;
  font-weight: 500;
}

.status-normal {
  color: #17B3A3;
  font-weight: 500;
}

.input-wrapper {
  flex: 1;
  margin-left: 12px;
}

.location-input {
  width: 100%;
}

.location-input ::v-deep .el-input__inner {
  border: 1px solid #17B3A3;
  border-radius: 4px;
  font-size: 14px;
  padding: 8px 12px;
}

.date-input {
  width: 100%;
}

.date-input ::v-deep .el-input__inner {
  border: 1px solid #17B3A3;
  border-radius: 4px;
  font-size: 14px;
  padding: 8px 12px;
}

/* 底部操作按钮 */
.bottom-actions {
  display: flex;
  padding: 16px;
  gap: 12px;
  background: white;
  margin-top: auto;
}

.action-btn {
  flex: 1;
  padding: 12px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
}

.action-btn.primary {
  background: #17B3A3;
  color: white;
}

.action-btn.primary:hover {
  background: #0d8f7f;
}

.action-btn.secondary {
  background: white;
  color: #17B3A3;
  border: 1px solid #17B3A3;
}

.action-btn.secondary:hover {
  background: #17B3A3;
  color: white;
}

.action-btn:active {
  transform: scale(0.98);
}

/* 响应式设计 */
@media (max-width: 360px) {
  .header-bar {
    padding: 8px 12px;
  }

  .search-container {
    padding: 8px 12px;
  }

  .label-info-card {
    margin: 6px 12px;
    padding: 12px;
  }

  .info-label {
    width: 70px;
    font-size: 13px;
  }

  .info-value {
    font-size: 13px;
  }

  .bottom-actions {
    padding: 12px;
  }
}
</style>
