<template>
  <el-dialog
    title="新增手动入库"
    :visible.sync="visible"
    width="900px"
    append-to-body
    destroy-on-close
  >
    <div class="outbound-table">
      <el-table :data="tableData" size="small" border>
        <el-table-column label="物料编码" width="280">
          <template slot-scope="scope">
            <el-autocomplete
              :value="queryGoods"
              v-model="scope.row.goodsId"
              :fetch-suggestions="searchMaterials"
              :trigger-on-focus="false"
              placeholder="请输入物料编码或名称"
              clearable
               @select="handleMaterialSelect(scope.$index,$event)"
            >
              <template slot-scope="{ item }">
                <div class="material-item">
                  <div class="material-code">{{ item.goodsId }}</div>
                  <div class="material-desc">{{ item.goodsDesc }}</div>
                  <div class="material-divider"></div>
                </div>
              </template>
            </el-autocomplete>
          </template>
        </el-table-column>
         <el-table-column label="物料条码" prop="goodsCode">
          <template slot-scope="scope">
            <el-input v-model="scope.row.goodsCode"   placeholder="物料条码" />
          </template>
        </el-table-column>
        <el-table-column label="物料描述" prop="goodsDesc">
          <template slot-scope="scope">
            <el-input v-model="scope.row.goodsDesc"  readonly placeholder="物料描述" />
          </template>
        </el-table-column>
        <el-table-column label="入库数量" width="150">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.goodsNum"
              :min="1"
              controls-position="right"
              placeholder="请输入数量"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="removeRow(scope.$index)"
              :disabled="tableData.length === 1"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <el-button type="primary" icon="el-icon-plus" @click="addRow">新增行</el-button>
      </div>
    </div>

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

<script>
import { queryListByGoodsId } from "@/api/system/goods";

export default {
  name: 'OutboundDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      queryGoods: "",
      tableData: [
        {
          stockId: Date.now(),
          goodsId: '',
          goodsDesc: '',
          goodsNum: 1,  // 统一使用 goodsNum
        }
      ]
    }
  },
  methods: {
    // 搜索物料
    async searchMaterials(query, callback) {
      if (query.length < 2) {
        callback([]);
        return;
      }

        const queryParams = {
          goodsId: query
        };
        let mockData = [];
        await queryListByGoodsId(queryParams).then(response => {
           if(response.code === 200){
            response.data.forEach(item => {
              mockData.push({
                value: item.goodsId,
                goodsId: item.goodsId,
                goodsDesc: item.goodsDesc,
                goodsCode: item.goodsCode,
              });
            });
            mockData = response.data;
           }
        });
        callback(mockData);

    },

    // 选择物料
    // handleMaterialSelect(index,item) {
    //   consoe.log("=======================");
    //   console.log("index", index);
    //   console.log("item",item );
    //   this.$set(this.tableData[index], 'goodsId', item.goodsId);
    //   this.$set(this.tableData[index], 'goodsDesc', item.goodsDesc);
    //   this.$set(this.tableData[index], 'goodsName', item.goodsName);
    // },

    // 新增行
    addRow() {
      this.tableData.push({
        stockId: Date.now(),
        goodsId: '',
        goodsDesc: '',
        goodsCode: '',
        goodsNum: 1
      });
    },

    // 删除行
    removeRow(index) {
      if (this.tableData.length > 1) {
        this.tableData.splice(index, 1);
      }
    },

    // 取消
    handleCancel() {
      this.$emit('update:visible', false);
      this.resetForm();
    },
  // 选择物料后，更新 goodsName 和 goodsDesc
  handleMaterialSelect(index,item){
    console.log("handleMaterialSelect",index);
      const selectedItem = this.tableData[index];
      console.log("selectedItem",selectedItem);
      // 模拟API返回的数据
      // const selectedMaterial = {
      //   goodsId: selectedItem.goodsId,
      //   goodsName: '物料名称示例', // 需要从接口获取实际物料名称
      //   goodsDesc: '物料描述示例' // 需要从接口获取实际物料描述
      // };

      this.$set(this.tableData, index, {
        ...selectedItem,
        goodsId: item.goodsId,  // 更新物料编码
        goodsDesc: item.goodsDesc,  // 更新物料描述
        goodsCode: item.goodsCode,  // 更新物料条码
      });
    },
    // 提交
    handleSubmit() {
      // 验证数据
      const invalidRow = this.tableData.find(item =>
        !item.goodsId ||
        !item.goodsDesc ||
        item.goodsNum < 1
      );

      if (invalidRow) {
        this.$message.warning('请填写完整的出库信息');
        return;
      }

      // 提交数据
      this.$emit('submit', this.tableData);
      this.handleCancel();
    },

    // 重置表单
    resetForm() {
      this.tableData = [
        {
          stockId: Date.now(),
          goodsId: '',
          goodsDesc: '',
          goodsCode: '',
          goodsNum: 1
        }
      ];
    }
  }
};
</script>

<style lang="scss" scoped>
.outbound-table {
  .material-item {
    .material-code {
      font-weight: bold;
    }
    .material-desc {
      font-size: 12px;
      color: #666;
    }
  }

  .table-footer {
    margin-top: 15px;
    display: flex;
    justify-content: flex-start;
  }
}

.el-autocomplete {
  width: 100%;
}

.el-input-number {
  width: 100%;
}
.material-divider {
  border-top: 1px dashed #ccc;
  margin: 8px 0;
}
</style>
