<template>
  <div class="stockin-container">
    <el-dialog 
      :title="title" 
      :visible.sync="visible" 
      width="80%" 
      :before-close="handleClose"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 入库单基本信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单号" prop="stockIoCode">
              <el-input v-model="form.stockIoCode" placeholder="系统自动生成" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库类型" prop="ioType">
              <el-select v-model="form.ioType" placeholder="请选择入库类型" :disabled="true">
                <el-option label="入库" value="in" />
                <el-option label="出库" value="out" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务类型" prop="bizType">
              <el-select v-model="form.bizType" placeholder="请选择业务类型" :disabled="true">
                <el-option label="采购入库" value="purchase" />
                <el-option label="销售退货" value="return" />
                <el-option label="调拨入库" value="transfer" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择单据状态" :disabled="true">
                <el-option label="草稿" :value="0" />
                <el-option label="已提交" :value="1" />
                <el-option label="已审核" :value="2" />
                <el-option label="已完成" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <!-- 入库明细表格 -->
        <el-form-item label="入库明细">
          <KLPTable 
            :data="form.details" 
            border 
            style="width: 100%"
          >
            <el-table-column label="原材料" align="center" prop="rawMaterialName" />
            <el-table-column label="SKU" align="center">
              <template slot-scope="scope">
                <BomInfoMini item-type="raw_material" :item-id="scope.row.rawMaterialId" />
              </template>
            </el-table-column>
            <el-table-column label="计划数量" align="center" prop="planQuantity" />
            <el-table-column label="入库数量" align="center" prop="quantity">
              <template slot-scope="scope">
                <el-input 
                  v-model.number="scope.row.quantity" 
                  size="mini"
                  @change="handleQuantityChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="仓库" align="center" prop="warehouseId">
              <template slot-scope="scope">
                <warehouse-select
                  v-model="scope.row.warehouseId"
                  placeholder="请选择仓库"
                  size="mini"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column label="批次号" align="center" prop="batchNo">
              <template slot-scope="scope">
                <el-input 
                  v-model="scope.row.batchNo" 
                  size="mini"
                  placeholder="请输入批次号"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark">
              <template slot-scope="scope">
                <el-input 
                  v-model="scope.row.remark" 
                  size="mini"
                  placeholder="请输入备注"
                />
              </template>
            </el-table-column>
          </KLPTable>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addStockIoWithDetail } from "@/api/wms/stockIo";
import { updatePurchasePlanDetail } from "@/api/wms/purchasePlanDetail";
import { getRawMaterial } from "@/api/wms/rawMaterial";
import { EPurchaseDetailStatus } from "@/utils/enums";
import WarehouseSelect from "@/components/KLPService/WarehouseSelect";
import BomInfoMini from '@/components/KLPService/Renderer/BomInfoMini.vue';

export default {
  name: "StockInDialog",
  components: {
    WarehouseSelect,
    BomInfoMini
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    selectedItems: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      title: "创建入库单",
      submitLoading: false,
      form: {
        stockIoCode: "",
        ioType: "in",
        bizType: "purchase",
        status: 0,
        remark: "",
        details: []
      },
      rules: {
        remark: [
          { max: 500, message: "备注长度不能超过500个字符", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.initForm();
      }
    },
    // selectedItems: {
    //   handler(newVal) {
    //     if (newVal && newVal.length > 0 && this.visible) {
    //       this.initDetails();
    //     }
    //   },
    //   immediate: false
    // }
  },
  methods: {
    /** 初始化表单 */
    initForm() {
      this.form = {
        stockIoCode: `IN-${new Date().getTime()}`,
        ioType: "in",
        bizType: "purchase",
        status: 0,
        remark: `采购计划入库单 - ${new Date().toLocaleDateString()}`,
        details: []
      };
      // 如果已经有选中的明细，则初始化明细
      if (this.selectedItems && this.selectedItems.length > 0) {
        this.initDetails();
      }
    },
    /** 初始化明细数据 */
    async initDetails() {
      if (this.selectedItems && this.selectedItems.length > 0) {
        this.form.details = [];
        
        // 逐个获取原材料信息
        for (const item of this.selectedItems) {
          try {
            const rawMaterialInfo = await getRawMaterial(item.rawMaterialId);
            this.form.details.push({
              detailId: item.detailId,
              rawMaterialId: item.rawMaterialId,
              rawMaterialName: rawMaterialInfo.data.rawMaterialName || `原材料${item.rawMaterialId}`,
              planQuantity: item.quantity,
              quantity: item.quantity, // 默认入库数量等于计划数量
              unit: item.unit,
              warehouseId: null, // 默认仓库ID
              batchNo: `BATCH-${new Date().getTime()}-${item.rawMaterialId}`,
              remark: "",
              itemType: "raw_material"
            });
          } catch (error) {
            console.error(`获取原材料信息失败: ${item.rawMaterialId}`, error);
            // 如果获取失败，使用默认名称
            this.form.details.push({
              detailId: item.detailId,
              rawMaterialId: item.rawMaterialId,
              rawMaterialName: `原材料${item.rawMaterialId}`,
              planQuantity: item.quantity,
              quantity: item.quantity,
              unit: item.unit,
              warehouseId: null,
              batchNo: `BATCH-${new Date().getTime()}-${item.rawMaterialId}`,
              remark: "",
              itemType: "raw_material"
            });
          }
        }
      }
    },

    /** 处理数量变化 */
    handleQuantityChange(row) {
      // 验证入库数量不能超过计划数量
      if (row.quantity > row.planQuantity) {
        this.$message.warning(`入库数量不能超过计划数量 ${row.planQuantity}`);
        row.quantity = row.planQuantity;
      }
      if (row.quantity < 0) {
        this.$message.warning("入库数量不能为负数");
        row.quantity = 0;
      }
    },
    /** 关闭对话框 */
    handleClose() {
      this.$confirm("确认关闭？未保存的数据将丢失", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$emit("update:visible", false);
      }).catch(() => {});
    },
    /** 提交表单 */
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 验证是否有明细
          if (this.form.details.length === 0) {
            this.$message.warning("没有可入库的明细");
            return;
          }

          // 验证必填字段
          const invalidDetails = this.form.details.filter(detail => 
            !detail.warehouseId || !detail.batchNo || detail.quantity <= 0
          );
          
          if (invalidDetails.length > 0) {
            this.$message.warning("请完善明细的仓库、批次号和入库数量信息");
            return;
          }

          this.submitLoading = true;

          // 构建入库单数据
          const stockInData = {
            ...this.form,
            details: this.form.details.map(detail => ({
              warehouseId: detail.warehouseId,
              itemType: detail.itemType,
              itemId: detail.rawMaterialId,
              quantity: detail.quantity,
              unit: detail.unit,
              batchNo: detail.batchNo,
              remark: detail.remark
            }))
          };

          // 调用创建入库单API
          addStockIoWithDetail(stockInData).then(response => {
            // 创建入库单成功后，更新采购明细状态
            const updatePromises = this.form.details.map(detail => 
              updatePurchasePlanDetail({ 
                detailId: detail.detailId, 
                status: EPurchaseDetailStatus.FINISH 
              })
            );

            Promise.all(updatePromises).then(() => {
              this.$modal.msgSuccess("入库单创建成功，相关明细状态已更新为采购完成");
              this.$emit("success");
              this.$emit("update:visible", false);
            }).catch(error => {
              console.error(error);
              this.$modal.msgError("状态更新失败");
            });
          }).catch(error => {
            console.error(error);
            this.$modal.msgError("入库单创建失败");
          }).finally(() => {
            this.submitLoading = false;
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.stockin-container {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}
</style> 