<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.bizDate" type="date" value-format="yyyy-MM-dd" 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:guide: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:guide: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="bizDate" width="110" align="center"/>
      <el-table-column label="单据编号" prop="sheetNo" min-width="130" align="center"/>
      <el-table-column label="操作" width="140" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleView(scope.row)" v-hasPermi="['erp:stock:guide:query']">查看</el-button>
          <el-button type="text" size="mini" @click="handleDelete(scope.row)" v-hasPermi="['erp:stock:guide: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="1380px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="12">
          <el-col :span="6"><el-form-item label="业务日期" prop="bizDate"><el-date-picker v-model="form.bizDate" 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-row>
        <div class="mb8" v-if="!readonly"><el-button type="primary" plain size="mini" @click="addRow">新增明细</el-button></div>
        <el-table :data="form.goodsList" border>
          <el-table-column label="序号" width="70" align="center">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="生产车间" min-width="120"><template slot-scope="scope"><el-input v-model="scope.row.productionWorkshop" :disabled="readonly"/></template></el-table-column>
          <el-table-column label="物料" min-width="220">
            <template slot-scope="scope">
              <el-select v-model="scope.row.goodsNum" filterable style="width:100%" :disabled="readonly" @change="onMaterialChange(scope.row)">
                <el-option v-for="m in materialOptions" :key="m.inventoryId" :label="`${m.goodsNum} - ${m.goodsName}`" :value="m.goodsNum"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物料编号" prop="goodsNum" min-width="100"/>
          <el-table-column label="物料名称" prop="goodsName" min-width="110"/>
          <el-table-column label="物料规格" prop="goodsSpec" min-width="100"/>
          <el-table-column label="指导价" min-width="120"><template slot-scope="scope"><el-input-number v-model="scope.row.guidePrice" :precision="4" :min="0" :disabled="readonly" style="width:100%"/></template></el-table-column>
          <el-table-column label="物料备注" min-width="130"><template slot-scope="scope"><el-input v-model="scope.row.remark" :disabled="readonly"/></template></el-table-column>
          <el-table-column label="操作" width="70" v-if="!readonly"><template slot-scope="scope"><el-button type="text" size="mini" @click="removeRow(scope.$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 { addAccountingGuide, delAccountingGuide, getAccountingGuide, listAccountingGuide, listAccountingGuideMaterialOptions } from "@/api/erp/stock";
export default {
  name: "AccountingGuide",
  data() {
    return {
      loading:false, showSearch:true, total:0, list:[], ids:[], multiple:true, open:false, title:"", readonly:false, materialOptions:[],
      queryParams:{ pageNum:1, pageSize:10, sheetNo:undefined, bizDate:undefined },
      form:{},
      rules:{ bizDate:[{ required:true, message:"业务日期不能为空", trigger:"change" }] }
    };
  },
  created(){ this.getList(); this.loadOptions(); },
  methods:{
    getList(){ this.loading=true; listAccountingGuide(this.queryParams).then(res=>{ this.list=res.rows||[]; this.total=res.total||0; this.loading=false; }); },
    loadOptions(){ listAccountingGuideMaterialOptions().then(r=>{ const list=r.data||[]; const map={}; (list||[]).forEach(it=>{ if(it&&it.goodsNum&&!map[it.goodsNum]) map[it.goodsNum]=it; }); this.materialOptions=Object.values(map); }); },
    emptyRow(){ return { productionWorkshop:"", goodsNum:"", goodsName:"", goodsSpec:"", guidePrice:0, remark:"" }; },
    reset(){ this.form={ id:undefined, bizDate:this.parseTime(new Date(), "{y}-{m}-{d}"), sheetNo:"", goodsList:[this.emptyRow()] }; this.resetForm("form"); },
    onMaterialChange(row){ const hit=(this.materialOptions||[]).find(x=>x.goodsNum===row.goodsNum); if(!hit)return; row.goodsName=hit.goodsName||""; row.goodsSpec=hit.goodsSpec||""; },
    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; getAccountingGuide(row.id).then(r=>{ this.form=Object.assign({goodsList:[]}, r.data||{}); this.open=true; this.title="查看核算指导价"; }); },
    addRow(){ this.form.goodsList.push(this.emptyRow()); },
    removeRow(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++){ if(!g[i].goodsNum){ this.$modal.msgError(`第${i+1}行未选择物料`); return false; } if(!g[i].productionWorkshop){ this.$modal.msgError(`第${i+1}行生产车间不能为空`); return false; } } return true; },
    submitForm(){ this.$refs.form.validate(v=>{ if(!v||!this.validateRows())return; const payload={ bizDate:this.form.bizDate, goodsList:(this.form.goodsList||[]).map(r=>({ productionWorkshop:r.productionWorkshop, goodsNum:r.goodsNum, goodsName:r.goodsName, goodsSpec:r.goodsSpec, guidePrice:Number(r.guidePrice||0), remark:r.remark })) }; addAccountingGuide(payload).then(()=>{ this.$modal.msgSuccess("提交成功"); this.open=false; this.getList(); }); }); },
    handleDelete(row){ const ids=row.id||this.ids.join(","); this.$modal.confirm("确认删除选中的记录吗？").then(()=>delAccountingGuide(ids)).then(()=>{ this.$modal.msgSuccess("删除成功"); this.getList(); }).catch(()=>{}); },
    cancel(){ this.open=false; this.reset(); }
  }
};
</script>

