<template>
  <view class="inventory-bg">
    <view class="inventory-card">
      <view class="readonly-group">
        <view class="readonly-item">
          <text class="readonly-label">物资名称</text>
          <text class="readonly-value">{{ materialName }}</text>
        </view>
        <view class="readonly-item">
          <text class="readonly-label">物质代码</text>
          <text class="readonly-value">{{ materialCode }}</text>
        </view>
        <view class="readonly-item">
          <text class="readonly-label">规格型号</text>
          <text class="readonly-value">{{ materialSpec }}</text>
        </view>
        <view class="readonly-item">
          <text class="readonly-label">库存数量</text>
          <text class="readonly-value">{{ stockQty }}{{ unit ? ' ' + unit : '' }}</text>
        </view>
      </view>
      <view class="form-group" v-if="!isViewMode">
        <text class="form-label">盘点数量</text>
        <input class="form-input" type="number" v-model="countQty" placeholder="请输入盘点数量" />
      </view>
      <view class="form-group" v-if="!isViewMode">
        <text class="form-label">盘点备注</text>
        <textarea class="form-textarea" v-model="remark" placeholder="请输入备注信息" />
      </view>
      <view class="form-group" v-if="!isViewMode">
        <text class="form-label">照片上传</text>
        <view class="photo-upload">
          <view v-for="(photo, index) in photos" :key="index" class="photo-preview">
            <image :src="photo" mode="aspectFill" class="photo-img" />
            <view class="photo-del" @click="deletePhoto(index)">
              <text class="delete-icon">×</text>
            </view>
          </view>
          <button v-if="photos.length < 3" class="photo-btn" @click="choosePhoto">
            <text class="iconfont icon-camera"></text>
            <text class="btn-text">上传照片</text>
          </button>
        </view>
      </view>
      <button class="submit-btn" v-if="!isViewMode" @click="submit">提交盘点</button>
    </view>
  </view>
</template>

<script>
import { getMaterialInfo, saveInventoryCheck, uploadFile } from '@/api.js'
export default {
  data() {
    return {
      isViewMode: false,
      stockQty: '',
      countQty: '',
      remark: '',
      photo: '',
      photos: [],
      materialName: '',
      materialSpec: '',
      unit: '',
      materialCode: '',
      material_infos_plan_id: '',
      materialId: ''
    }
  },
  onLoad(options) {
    this.isViewMode = options.view === '1';
    this.date = this.getToday();
    this.materialId = options.code;
    console.log("materialId:", this.materialId);
    if (this.materialId) {
      getMaterialInfo(this.materialId).then(response => {
        console.log("response:", response);
        if (response.data) {
          this.materialName = response.data.zichanmingcheng || '-'
          this.materialSpec = response.data.guigexinghao || '-'
          this.unit = response.data.jiliangdanwei || '-'
          this.materialCode = response.data.wuzibianma || '-'
          this.material_infos_plan_id = response.data.material_infos_plan_id || ''
          this.stockQty = response.data.inventorys_total || '0'
        } else {
          uni.showToast({ title: '未获取到物资信息', icon: 'none' })
        }
      }).catch(() => {
        uni.showToast({ title: '获取物资信息失败', icon: 'none' })
      })
    }
  },
  methods: {
    getToday() {
      const now = new Date();
      const y = now.getFullYear();
      const m = String(now.getMonth() + 1).padStart(2, '0');
      const d = String(now.getDate()).padStart(2, '0');
      return `${y}-${m}-${d}`;
    },
    choosePhoto() {
      if (this.photos.length >= 3) {
        uni.showToast({ title: '最多上传3张照片', icon: 'none' });
        return;
      }
      uni.chooseImage({
        count: 3 - this.photos.length,
        success: (res) => {
          this.photos = [...this.photos, ...res.tempFilePaths];
        }
      });
    },
    deletePhoto(index) {
      this.photos.splice(index, 1);
    },
    async submit() {
      if (!this.countQty) {
        uni.showToast({ title: '请输入盘点数量', icon: 'none' });
        return;
      }
      
      if (!/^(0|[1-9][0-9]*)$/.test(this.countQty)) {
        uni.showToast({ title: '盘点数量必须为0或正整数', icon: 'none' });
        return;
      }
      uni.showLoading({ title: '提交中...' });
      // 1. 上传所有照片，收集 file_id
      let file_ids = [];
      for (let i = 0; i < this.photos.length; i++) {
        try {
          const res = await uploadFile(this.photos[i]);
          if (res && res.id) {
            file_ids.push(res.id);
          }
        } catch (e) {
          uni.hideLoading();
          uni.showToast({ title: '图片上传失败', icon: 'none' });
          return;
        }
      }
      // 2. 组装盘点数据
      const data = {
        status: '1',
        material_info_id: this.materialId, // 或实际物资id字段
        check_num: this.countQty,
        remark: this.remark,
        file_ids
        // 其他参数如 material_infos_plan_id、status、check_date 可按需补充
      };
      console.log("data:", data);
      // 3. 提交盘点
      saveInventoryCheck(data).then(res => {
        console.log("res:", res);
        uni.hideLoading();
        if (res && (!res.data || res.data.errcode === undefined)) {
          uni.showToast({ title: '盘点提交成功', icon: 'success' });
          setTimeout(() => {
            uni.reLaunch({ url: '/pages/index/index' });
          }, 1200);
        } else {
          uni.showToast({ title: res.data.errmsg || '提交失败', icon: 'none' });
        }
      }).catch(() => {
        uni.hideLoading();
        uni.showToast({ title: '提交失败', icon: 'none' });
      });
    }
  }
}
</script>

<style>
.inventory-bg {
  min-height: 100vh;
  background: #f5f6f7;
  padding: 24rpx;
}

.inventory-card {
  background: #fff;
  border-radius: 24rpx;
  padding: 32rpx 24rpx;
  margin-bottom: 24rpx;
}

.readonly-group {
  margin-bottom: 32rpx;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
}

.readonly-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.readonly-item:last-child {
  margin-bottom: 0;
}

.readonly-label {
  color: #666;
  font-size: 28rpx;
}

.readonly-value {
  color: #333;
  font-size: 28rpx;
  font-weight: 500;
}

.form-group {
  margin-bottom: 32rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.form-input {
  height: 88rpx;
  background: #f8f9fa;
  border: none;
  border-radius: 16rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333;
}

.form-textarea {
  min-height: 160rpx;
  background: #f8f9fa;
  border: none;
  border-radius: 16rpx;
  padding: 20rpx 24rpx;
  font-size: 28rpx;
  color: #333;
}

.photo-upload {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.photo-preview {
  position: relative;
  width: 160rpx;
  height: 160rpx;
}

.photo-btn {
  width: 160rpx;
  height: 160rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.photo-btn .iconfont {
  font-size: 48rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.btn-text {
  font-size: 24rpx;
  color: #666;
}

.photo-preview {
  position: relative;
}

.photo-img {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
}

.photo-del {
  position: absolute;
  top: -16rpx;
  right: -16rpx;
  width: 40rpx;
  height: 40rpx;
  background: rgba(0,0,0,0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon {
  color: #ff4d4f;
  font-size: 32rpx;
  font-weight: bold;
  line-height: 1;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: #409eff;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 44rpx;
  margin-top: 48rpx;
}

.submit-btn:active {
  opacity: 0.9;
}
</style>