<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" size="small" label-width="90px">
      <el-form-item label="货单单号"><el-input v-model="queryParams.sheetNo" clearable style="width:200px" /></el-form-item>
      <el-form-item label="货单日期"><el-date-picker v-model="queryParams.sheetDate" type="date" value-format="yyyy-MM-dd" style="width:200px" /></el-form-item>
      <el-form-item label="生产类型"><el-input v-model="queryParams.productionType" clearable style="width:200px" /></el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="handleQuery">搜索</el-button>
        <el-button size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"><el-button type="primary" plain size="mini" @click="handleAdd" v-hasPermi="['erp:stock:issue:add']">新增领料</el-button></el-col>
      <el-col :span="1.5"><el-button type="danger" plain size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['erp:stock:issue:remove']">删除</el-button></el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="货单日期" prop="sheetDate" width="110" align="center" />
      <el-table-column label="货单单号" prop="sheetNo" min-width="130" align="center" />
      <el-table-column label="生产类型" prop="productionType" min-width="100" align="center" />
      <el-table-column label="生产车间" prop="productionWorkshop" min-width="120" align="center" />
      <el-table-column label="小计合计" prop="totalSubtotal" min-width="120" align="center" />
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleView(scope.row)" v-hasPermi="['erp:stock:issue:query']">查看</el-button>
          <el-button type="text" size="mini" @click="handleDelete(scope.row)" v-hasPermi="['erp:stock:issue:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <el-dialog :title="title" :visible.sync="open" width="1500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="12">
          <el-col :span="6"><el-form-item label="货单日期" prop="sheetDate"><el-date-picker v-model="form.sheetDate" type="date" value-format="yyyy-MM-dd" style="width:100%" :disabled="readonly"/></el-form-item></el-col>
          <el-col :span="6"><el-form-item label="货单单号"><el-input v-model="form.sheetNo" readonly /></el-form-item></el-col>
          <el-col :span="6"><el-form-item label="生产类型"><el-input v-model="form.productionType" :disabled="readonly"/></el-form-item></el-col>
          <el-col :span="6"><el-form-item label="生产车间"><el-input v-model="form.productionWorkshop" :disabled="readonly"/></el-form-item></el-col>
        </el-row>
        <el-form-item label="货单备注"><el-input v-model="form.remark" type="textarea" :rows="2" :disabled="readonly" /></el-form-item>
        <div class="mb8" v-if="!readonly"><el-button type="primary" plain size="mini" @click="addGoodsRow">新增明细</el-button></div>
        <el-table :data="form.goodsList" border>
          <el-table-column type="index" width="50" />
          <el-table-column label="库存行" min-width="230">
            <template slot-scope="scope">
              <el-select v-model="scope.row.sourceInventoryId" filterable style="width:100%" :disabled="readonly" @change="onSourceChange(scope.row)">
                <el-option v-for="it in inventoryOptions" :key="it.inventoryId" :label="`${it.warehouseNo} | ${it.goodsNum} | 批次:${it.batchNo}`" :value="it.inventoryId"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物料编号" prop="goodsNum" min-width="90"/><el-table-column label="物料名称" prop="goodsName" min-width="100"/>
          <el-table-column label="物料规格" prop="goodsSpec" min-width="90"/><el-table-column label="入库批次" prop="batchNo" min-width="90"/>
          <el-table-column label="仓库(出库)" min-width="120"><template slot-scope="s">{{ s.row.outWarehouseNo }} / {{ s.row.outWarehouseName }}</template></el-table-column>
          <el-table-column label="基本单位" prop="baseUnit" width="85"/>
          <el-table-column label="基本数量" width="180"><template slot-scope="s"><el-input-number v-model="s.row.baseQty" :precision="4" :min="0" :disabled="readonly" style="width:100%" @change="calcSubtotal(s.row)"/></template></el-table-column>
          <el-table-column label="辅助单位" prop="assistantUnit" width="85"/>
          <el-table-column label="辅助数量" width="180"><template slot-scope="s"><el-input-number v-model="s.row.assistantQty" :precision="4" :min="0" :disabled="readonly" style="width:100%"/></template></el-table-column>
          <el-table-column label="加工费" width="180"><template slot-scope="s"><el-input-number v-model="s.row.processingFee" :precision="4" :min="0" :disabled="readonly" style="width:100%" @change="calcSubtotal(s.row)"/></template></el-table-column>
          <el-table-column label="小计" width="180" align="right"><template slot-scope="s">{{ lineSubtotal(s.row) }}</template></el-table-column>
          <el-table-column label="物料备注" min-width="120"><template slot-scope="s"><el-input v-model="s.row.remark" :disabled="readonly"/></template></el-table-column>
          <el-table-column label="操作" width="70" v-if="!readonly"><template slot-scope="s">

            <el-button type="text" size="mini" @click="removeGoodsRow(s.$index)">删除</el-button></template></el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!readonly" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addStockIssue, delStockIssue, getStockIssue, listStockIssue, listStockIssueInventoryOptions } from "@/api/erp/stock";
export default {
  name: "StockIssue",
  data() {
    return {
      loading:false, showSearch:true, total:0, list:[], ids:[], multiple:true, open:false, title:"", readonly:false,
      inventoryOptions:[],
      queryParams:{ pageNum:1, pageSize:10, sheetNo:undefined, sheetDate:undefined, productionType:undefined },
      form:{}, rules:{ sheetDate:[{ required:true, message:"货单日期不能为空", trigger:"change" }] }
    };
  },
  created(){ this.getList(); this.loadOptions(); },
  methods:{
    getList(){ this.loading=true; listStockIssue(this.queryParams).then(res=>{ this.list=res.rows||[]; this.total=res.total||0; this.loading=false; }); },
    loadOptions(){ listStockIssueInventoryOptions().then(r=>this.inventoryOptions=r.data||[]); },
    reset(){ const u=this.$store.state.user||{}; this.form={ id:undefined, sheetDate:this.parseTime(new Date(), "{y}-{m}-{d}"), sheetNo:"", productionType:"", productionWorkshop:"", issueUser:(u.nickName||u.name||""), remark:"", goodsList:[this.emptyRow()] }; this.resetForm("form"); },
    emptyRow(){ return { sourceInventoryId:undefined, goodsNum:"", goodsName:"", goodsSpec:"", batchNo:"", outWarehouseNo:"", outWarehouseName:"", baseUnit:"", baseQty:1, assistantUnit:"", assistantQty:1, processingFee:0, subtotal:0, remark:"" }; },
    onSourceChange(row){ const h=this.inventoryOptions.find(o=>o.inventoryId===row.sourceInventoryId); if(!h)return; row.goodsNum=h.goodsNum||""; row.goodsName=h.goodsName||""; row.goodsSpec=h.goodsSpec||""; row.batchNo=h.batchNo||""; row.outWarehouseNo=h.warehouseNo||""; row.outWarehouseName=h.warehouseName||""; row.baseUnit=h.baseUnit||""; row.assistantUnit=h.assistantUnit||""; this.calcSubtotal(row); },
    calcSubtotal(row){ row.subtotal = Number(row.baseQty||0) * Number(row.processingFee||0); this.$forceUpdate(); },
    lineSubtotal(row){ return Number(row.subtotal||0).toFixed(4); },
    handleQuery(){ this.queryParams.pageNum=1; this.getList(); },
    resetQuery(){ this.resetForm("queryForm"); this.handleQuery(); },
    handleSelectionChange(s){ this.ids=s.map(i=>i.id); this.multiple=!s.length; },
    handleAdd(){ this.readonly=false; this.reset(); this.open=true; this.title="新增仓库领料"; },
    handleView(row){ this.readonly=true; getStockIssue(row.id).then(r=>{ this.form=Object.assign({goodsList:[]}, r.data||{}); this.open=true; this.title="查看仓库领料"; }); },
    addGoodsRow(){ this.form.goodsList.push(this.emptyRow()); },
    removeGoodsRow(i){ this.form.goodsList.splice(i,1); if(!this.form.goodsList.length)this.form.goodsList.push(this.emptyRow()); },
    validateRows(){ const g=this.form.goodsList||[]; if(!g.length){ this.$modal.msgError("至少一条明细"); return false; } for(let i=0;i<g.length;i++){ const r=g[i]; if(!r.sourceInventoryId){ this.$modal.msgError(`第${i+1}行未选库存行`); return false; } if(Number(r.baseQty||0)<=0 && Number(r.assistantQty||0)<=0){ this.$modal.msgError(`第${i+1}行数量必须大于0`); return false; } } return true; },
    submitForm(){ this.$refs.form.validate(v=>{ if(!v||!this.validateRows())return; const payload={ sheetDate:this.form.sheetDate, productionType:this.form.productionType, productionWorkshop:this.form.productionWorkshop, issueUser:this.form.issueUser, remark:this.form.remark, goodsList:(this.form.goodsList||[]).map(r=>({ sourceInventoryId:r.sourceInventoryId, baseQty:Number(r.baseQty||0), assistantQty:Number(r.assistantQty||0), processingFee:Number(r.processingFee||0), remark:r.remark })) }; addStockIssue(payload).then(()=>{ this.$modal.msgSuccess("提交成功"); this.open=false; this.getList(); this.loadOptions(); }); }); },
    handleDelete(row){ const ids=row.id||this.ids.join(","); this.$modal.confirm("确认删除选中的领料单吗？").then(()=>delStockIssue(ids)).then(()=>{ this.$modal.msgSuccess("删除成功"); this.getList(); }).catch(()=>{}); },
    cancel(){ this.open=false; this.reset(); }
  }
};
</script>
