<template>
  <div class="bmcargo-edit">
    <BmcargoList ref="bmcargoList" :readonly="readonly" :selectedRow="tempRow" :voyage-id="voyageInfo.id"
      @rowClick="bmcargoClick">
    </BmcargoList>
    <div class="edit-content">
      <div class="edit-header">
        <div class="header-title">{{ title }}</div>
        <div class="header-btns" v-if="!readonly">
          <!-- <el-button >取消</el-button> -->
          <el-button type="primary" style="width: 120px;" v-loading="loading" @click="submitForm"
            :disabled="!voyageInfo.id && !form.voyageId">保存</el-button>
        </div>
      </div>
      <div class="edit-scroll">
        <el-form ref="form" v-if="!updating" :model="form" :rules="rules" :show-message="false" v-enterboard>
          <el-descriptions class="desc-table" :column="3" border v-enterboard>
            <el-descriptions-item>
              <template slot="label">货主名称<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.custName }}</div>
              <el-form-item v-else prop="custId" class="margin-none">
                <el-select v-model="form.custId" filterable placeholder="请输入货主名称" style="width: 100%" clearable
                  @change="setCustDetail">
                  <el-option v-for="item in custList" :key="item.id" :label="item.custName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">货物名称<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.cargoName }}</div>
              <el-form-item v-else prop="cargoId" class="margin-none">
                <el-select v-model="form.cargoId" filterable placeholder="请输入货物名称" style="width: 100%" clearable
                  @change="setCargoDetail">
                  <el-option v-for="item in cargoList" :key="item.id" :label="item.cargoName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">计量单位<rq /></template>
              <div v-if="notAdd">
                <dict-tag :options="dict.type.sys_measurement_unit" :value="form.unit"></dict-tag>
              </div>
              <el-form-item v-else prop="unit" class="margin-none">
                <el-select filterable v-model="form.unit" placeholder="请输入计量单位" clearable style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_measurement_unit" :key="dict.value" :label="dict.label"
                             :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label"><span style="min-width: 120px !important;">第一计量单位<rq /></span></template>
              <div v-if="notAdd">
                <dict-tag :options="dict.type.sys_measurement_unit" :value="form.firstUnit"></dict-tag>
              </div>
              <el-form-item v-else prop="firstUnit" class="margin-none">
                <el-select filterable v-model="form.firstUnit" placeholder="请输入第一计量单位" clearable style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_measurement_unit" :key="dict.value" :label="dict.label"
                             :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">HS编号</template>
              <div class="nomal-text">{{ form.hsCode }}</div>
            </el-descriptions-item>

            <el-descriptions-item>
              <template slot="label">原产国<rq /></template>
              <div v-if="notAdd">
                <dict-tag :options="dict.type.sys_origin_country" :value="form.originCountry"></dict-tag>
              </div>
              <el-form-item v-else prop="originCountry" class="margin-none">
                <el-select filterable v-model="form.originCountry" placeholder="请选择原产国" style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_origin_country" :key="dict.value" :label="dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-descriptions-item>


            <el-descriptions-item>
              <template slot="label">商品料号<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.itemNumber }}</div>
              <el-form-item v-else prop="itemNumber" class="margin-none">
                <el-input v-model="form.itemNumber" placeholder="请输入商品料号" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">规格类型品质</template>
              <div v-if="notAdd" class="nomal-text">{{ form.cargoSpec }}</div>
              <el-form-item v-else prop="cargoSpec" class="margin-none">
                <el-input v-model="form.cargoSpec" placeholder="请输入规格类型品质" style="width: 100%" /></el-form-item>
            </el-descriptions-item>

            <el-descriptions-item>
              <template slot="label">货物自然序号<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.cargoNumber }}</div>
              <el-form-item v-else prop="cargoNumber" class="margin-none">
                <el-input v-model="form.cargoNumber" placeholder="请输入货物自然序号" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">唛头</template>
              <div v-if="notAdd" class="nomal-text">{{ form.mark }}</div>
              <el-form-item v-else prop="mark" class="margin-none">
                <el-input v-model="form.mark" placeholder="请输入唛头" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">包装类型</template>
              <div v-if="notAdd">
                <dict-tag :options="dict.type.sys_package_type" :value="form.packType"></dict-tag>
              </div>
              <el-form-item v-else prop="packType" class="margin-none">
                <el-select filterable v-model="form.packType" placeholder="请选择包装类型" style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_package_type" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">电子账册项号<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.bookNumber }}</div>
              <el-form-item v-else prop="bookNumber" class="margin-none">
                <el-input v-model="form.bookNumber" placeholder="请输入电子账册项号" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">报关单号<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.customsNo }}</div>
              <el-form-item v-else prop="customsNo" class="margin-none">
                <el-input v-model="form.customsNo" placeholder="请输入报关单号" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">核注清单号<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.listNumber }}</div>
              <el-form-item v-else prop="listNumber" class="margin-none">
                <el-input v-model="form.listNumber" placeholder="请输入核注清单号" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">提运单号<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.billNo }}</div>
              <el-form-item v-else prop="billNo" class="margin-none">
                <el-input v-model="form.billNo" placeholder="请输入提运单号" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">业务性质</template>
              <div>
                <dict-tag :options="dict.type.sys_business_nature" :value="form.opType"></dict-tag>
              </div>
              <!-- <el-form-item v-else prop="opType" class="margin-none">
                <el-select filterable v-model="form.opType" placeholder="请选择业务性质" style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_business_nature" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item> -->
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">船港货机械</template>
              <div v-if="notAdd">
                <dict-tag :options="dict.type.sys_shipport_cargo_machinery" :value="form.cargoMachine"></dict-tag>
              </div>
              <el-form-item v-else prop="cargoMachine" class="margin-none">
                <el-select filterable v-model="form.cargoMachine" placeholder="请输入船港货机械" clearable style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_shipport_cargo_machinery" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">舱口类型</template>
              <div v-if="notAdd">
                <dict-tag :options="dict.type.sys_hatch_type" :value="form.hatchTpe"></dict-tag>
              </div>
              <el-form-item v-else prop="hatchTpe" class="margin-none">
                <el-select filterable v-model="form.hatchTpe" placeholder="请输入舱口类型" clearable style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_hatch_type" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-descriptions-item>

            <el-descriptions-item>
              <template slot="label">贸易性质<rq /></template>
              <div v-if="notAdd">
                <dict-tag :options="dict.type.sys_trade_nature" :value="form.tradType"></dict-tag>
              </div>
              <el-form-item v-else prop="tradType" class="margin-none">
                <el-select filterable v-model="form.tradType" placeholder="请选择贸易性质" style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_trade_nature" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-descriptions-item>


            <el-descriptions-item>
              <template slot="label">单件重量</template>
              <div v-if="notAdd" class="nomal-text">{{ form.pieceWeight }}</div>
              <el-form-item v-else prop="pieceWeight" class="margin-none">
                <el-input-number v-model="form.pieceWeight" placeholder="请输入单件重量" :min="0" :precision="2" controls-position="right"
                  style="width: 100%" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">货物单价<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.unitPrice }}</div>
              <el-form-item v-else prop="unitPrice" class="margin-none">
                <el-input-number v-model="form.unitPrice" :min="0" placeholder="请输入货物单价" style="width: 100%" controls-position="right"
                                 :precision="2" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">货物价值</template>
              <div v-if="notAdd" class="nomal-text">{{ form.cargoValue }}</div>
              <el-form-item v-else prop="cargoValue" class="margin-none">
                <el-input-number v-model="form.cargoValue" :min="0" placeholder="请输入货物价值" style="width: 100%"
                  :precision="2" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">币种<rq /></template>
              <div v-if="notAdd">
                <dict-tag :options="dict.type.sys_curr_type" :value="form.currType"></dict-tag>
              </div>
              <el-form-item v-else prop="currType" class="margin-none">
                <el-select filterable v-model="form.currType" placeholder="请选择币种" style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_curr_type" :key="dict.value" :label="dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">有效期至<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.expiryDate }}</div>
              <el-form-item v-else prop="expiryDate" class="margin-none">
                <el-date-picker clearable v-model="form.expiryDate" type="datetime" value-format="yyyy-MM-dd"
                  style="width: 100%" placeholder="请选择有效期至" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">计划件数</template>
              <div v-if="notAdd" class="nomal-text">{{ form.cargoNum }}</div>
              <el-form-item v-else prop="cargoNum" class="margin-none">
                <el-input-number v-model="form.cargoNum" placeholder="请输入货物件数" :min="0" :precision="2" controls-position="right"
                  style="width: 100%" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">计划重量<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.cargoWt }}</div>
              <el-form-item v-else prop="cargoWt" class="margin-none">
                <el-input-number v-model="form.cargoWt" placeholder="请输入货物重量" :min="0" :precision="2" controls-position="right"
                  style="width: 100%" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">计划体积(m³)<rq /></template>
              <div v-if="notAdd" class="nomal-text">{{ form.cargoVol }}</div>
              <el-form-item v-else prop="cargoVol" class="margin-none">
                <el-input-number v-model="form.cargoVol" placeholder="请输入货物体积" :min="0" :precision="2" controls-position="right"
                  style="width: 100%" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">实际交接件数</template>
              <div v-if="readonly" class="nomal-text">{{ form.actNum }}</div>
              <el-form-item v-else prop="actNum" class="margin-none">
                <el-input-number v-model="form.actNum" placeholder="请输入实际交接件数" :min="0" style="width: 100%" controls-position="right"
                  @change="changeStockNum" :precision="2" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">实际交接重量<rq /></template>
              <div v-if="readonly" class="nomal-text">{{ form.actWt }}</div>
              <el-form-item v-else prop="actWt" class="margin-none">
                <el-input-number v-model="form.actWt" placeholder="请输入实际交接重量" :min="0" style="width: 100%" controls-position="right"
                  @change="changeStockWt" :precision="2" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">实际交接体积(m³)</template>
              <div v-if="readonly" class="nomal-text">{{ form.actVol }}</div>
              <el-form-item v-else prop="actVol" class="margin-none">
                <el-input-number v-model="form.actVol" placeholder="请输入实际交接体积" :min="0" style="width: 100%" controls-position="right"
                  @change="changeStockVol" :precision="2" />
              </el-form-item>
            </el-descriptions-item>
            <!--            <el-descriptions-item>-->
            <!--              <template slot="label">出(入)库单据编号</template>-->
            <!--              <div v-if="readonly" class="nomal-text">{{ form.billNumber }}</div>-->
            <!--              <el-form-item v-else prop="billNumber" class="margin-none">-->
            <!--                <el-input v-model="form.billNumber" placeholder="请输入单据编号" style="width: 100%"/>-->
            <!--              </el-form-item>-->
            <!--            </el-descriptions-item>-->

            <el-descriptions-item>
              <template slot="label">直提件数</template>
              <div v-if="readonly" class="nomal-text">{{ form.ztNum }}</div>
              <el-form-item v-else prop="ztNum" class="margin-none">
                <el-input-number v-model="form.ztNum" placeholder="请输入直提件数" style="width: 100%" @change="changeStockNum" controls-position="right"
                  :precision="2" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">直提重量</template>
              <div v-if="readonly" class="nomal-text">{{ form.ztWt }}</div>
              <el-form-item v-else prop="ztWt" class="margin-none">
                <el-input-number v-model="form.ztWt" placeholder="请输入直提重量" :min="0" style="width: 100%" controls-position="right"
                  @change="changeStockWt" :precision="2" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">直提体积(m³)</template>
              <div v-if="readonly" class="nomal-text">{{ form.ztVol }}</div>
              <el-form-item v-else prop="ztVol" class="margin-none">
                <el-input-number v-model="form.ztVol" placeholder="请输入直提体积" :min="0" style="width: 100%" controls-position="right"
                  @change="changeStockVol" :precision="2" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">出入库件数</template>
              <div class="nomal-text">{{ form.stockNum }}</div>
              <!-- <el-form-item v-else prop="stockNum" class="margin-none">
                <el-input-number v-model="form.stockNum" placeholder="请输入出入库件数" style="width: 100%"
                  @change="changeStockNum" :precision="2" :min="0" />
              </el-form-item> -->
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">出入库重量</template>
              <div class="nomal-text">{{ form.stockWt }}</div>
              <!-- <el-form-item v-else prop="stockWt" class="margin-none">
                <el-input-number v-model="form.stockWt" placeholder="请输入出入库重量" :min="0" style="width: 100%"
                  @change="changeStockWt" :precision="2" />
              </el-form-item> -->
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">出入库体积(m³)</template>
              <div class="nomal-text">{{ form.stockVol }}</div>
              <!-- <el-form-item v-else prop="stockVol" class="margin-none">
                <el-input-number v-model="form.stockVol" placeholder="请输入出入库体积" :min="0" style="width: 100%"
                  @change="changeStockVol" :precision="2" />
              </el-form-item> -->
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">单据编号<rq /></template>
              <div v-if="readonly" class="nomal-text">{{ form.billNumber }}</div>
              <el-form-item v-else prop="billNumber" class="margin-none">
                <bill-number-input ref="billInput" v-model="form.billNumber"
                  :type="form.opType === '2' ? 'CK' : 'RK'"></bill-number-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">单据时间<rq /></template>
              <div v-if="readonly" class="nomal-text">{{ form.billDate }}</div>
              <el-form-item v-else prop="billDate" class="margin-none">
                <el-date-picker clearable v-model="form.billDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择单据时间" style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
            </el-descriptions-item>
          </el-descriptions>
          <el-tooltip :disabled="readonly || form.stockNum > 0 || form.stockWt > 0 || form.stockVol > 0"
            content="实际入库的数量、重量或者体积存在时才可以添加去向" placement="top">
            <el-button style="margin: 10px 0;" :disabled="readonly" type="primary" size="small"
              @click="addParamsSetting">{{ readonly ? '出入库去向' : '添加出入库去向' }}
            </el-button>
          </el-tooltip>
          <el-table v-if="form.stockNum > 0 || form.stockWt > 0 || form.stockVol > 0" :data="tableData"
            style="width: 100%" class="table" size="mini" border v-enterboard>
            <el-table-column v-if="!readonly" label="操作" width="80">
              <template slot-scope="scope">
                <el-button :disabled="readonly" type="primary" size="small"
                  @click.native.prevent="deleteRow(scope.$index)">删除
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="库场名称" align="center" prop="stockId" min-width="180">
              <template slot-scope="scope">
                <div v-if="readonly">{{ warehouseName(scope.row) + '-' + scope.row.stockName }}</div>
                <el-select v-else v-model="scope.row.stockId" filterable placeholder="请输入库场名称" style="width: 100%"
                  clearable @change="setStockDetail(scope.row)">
                  <el-option v-for="item in stockList" :key="item.stockId"
                    :label="warehouseName(item) + '-' + item.stockName" :value="item.stockId">
                    <WarehouseName :stockCode="item.stockCode"></WarehouseName><span>-{{ item.stockName }}</span>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <!--       只有当出库的时候才需要展示       -->
            <el-table-column v-if="form.opType === '2'" label="单据编号" align="center" prop="billNumber" min-width="150">
              <template slot-scope="scope">
                <div v-if="readonly">{{ scope.row.billNumber }}</div>
                <el-select v-else v-model="scope.row.billNumber" filterable placeholder="请选择出库单据"
                  @change="setNowStockNum(scope.row, scope.$index)" clearable>
                  <el-option v-for="item in listMap[scope.row.stockId]" :key="item.billNumber" :label="item.billNumber"
                    :value="item.billNumber">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="现有库存" align="center">
              <el-table-column min-width="100" label="件数" align="center" prop="nowStockNum">
                <!-- <template slot-scope="scope">
                  <el-input disabled v-model="scope.row.nowStockNum"
                  ></el-input>
                </template> -->
              </el-table-column>
              <el-table-column min-width="100" label="重量" align="center" prop="nowStockWt">
                <!-- <template slot-scope="scope">
                  <el-input disabled v-model="scope.row.nowStockWt"
                  ></el-input>
                </template> -->
              </el-table-column>
              <el-table-column min-width="100" label="体积(m³)" align="center" prop="nowStockVol">
                <!-- <template slot-scope="scope">
                  <el-input disabled v-model="scope.row.nowStockVol"
                  ></el-input>
                </template> -->
              </el-table-column>
              <el-table-column min-width="100" label="剩余价值" align="center" prop="nowCargoValue">
                <!-- <template slot-scope="scope">
                  <el-input disabled v-model="scope.row.nowCargoValue"
                  ></el-input>
                </template> -->
              </el-table-column>
            </el-table-column>
            <el-table-column label="入（出）库量" align="center">
              <el-table-column label="出入库件数" align="center" prop="cargoNum" min-width="160">
                <template slot-scope="scope">
                  <div v-if="readonly">{{ scope.row.cargoNum }}</div>
                  <el-input-number v-else v-model="scope.row.cargoNum" @change="maxStockNum(scope.row)" :min="0" controls-position="right"
                    size="mini" type="number" :precision="2"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="出入库重量" align="center" prop="cargoWt" min-width="160">
                <template slot-scope="scope">
                  <div v-if="readonly">{{ scope.row.cargoWt }}</div>
                  <el-input-number v-else v-model="scope.row.cargoWt" type="number" :min="0" size="mini" controls-position="right"
                    @change="maxStockWt(scope.row)" :precision="2"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="出入库体积(m³)" align="center" prop="cargoVol" min-width="160">
                <template slot-scope="scope">
                  <div v-if="readonly">{{ scope.row.cargoVol }}</div>
                  <el-input-number v-else v-model="scope.row.cargoVol" type="number" :min="0" size="mini" controls-position="right"
                    @change="maxStockVol(scope.row)" :precision="2"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="货物价值" align="center" prop="cargoValue" min-width="160">
                <template slot-scope="scope">
                  <div v-if="readonly">{{ scope.row.cargoValue }}</div>
                  <el-input-number v-else v-model="scope.row.cargoValue" type="number" :min="0" size="mini" controls-position="right"
                    @change="maxCargoValue(scope.row)" :precision="2"></el-input-number>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { getBmcargo, delBmcargo, addBmcargo, updateBmcargo } from "@/api/jxc/bmcargo";
import { listCargo } from "@/api/jxc/cargo";
import { listCust } from "@/api/jxc/cust";
import BmcargoList from '@/views/jxc/bmcargo/components/BmcargoList';
import { stockNumList, warehouseList } from '@/api/jxc/ckstock';

const DefaultForm = {
  cargoNumber: null,
  itemNumber: null,
  bookNumber: null,
  customsNo: null,
  listNumber: null,
  opType: null,
  tradType: null,
  deptId: null,
  custId: null,
  cargoId: null,
  vesselName: null,
  billNo: null,
  unit: '吨',
  hatchTpe: null,
  cargoMachine: null,
  voyageNo: null,
  cargoNum: null,
  cargoWt: null,
  cargoVol: null,
  actNum: null,
  actWt: null,
  actVol: null,
  stockNum: 0,
  stockWt: 0,
  stockVol: 0,
  expiryDate: null,
  billNumber: null,
  billDate: null,
  originCountry: null,
  mark: null,
  cargoSpec: null,
};

export default {
  name: 'BmcargoConfirm',
  components: {
    BmcargoList,
  },
  dicts: ['sys_business_nature', 'sys_trade_nature', 'sys_measurement_unit', 'sys_hatch_type', 'sys_shipport_cargo_machinery', 'sys_package_type', 'sys_origin_country', 'sys_curr_type'],
  props: {
    voyageInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    bmcargo: {
      type: Object,
      default() {
        return {}
      }
    },
  },
  watch: {
    bmcargo: {
      handler(val) {
        this.initForm({
          ...DefaultForm,
          ...this.bmcargo
        });
      },
      immediate: true,
    }
  },
  data() {
    return {
      tempRow: DefaultForm,
      form: DefaultForm,
      stockList: [],
      // {
      //   stockId: '',
      //   stockCode: '',
      //   billNumber: '',
      //   stockName: '',
      //   cargoNum: '',
      //   cargoWt: '',
      //   cargoVol: '',
      //   cargoValue: '',
      //   nowStockNum: '',
      //   nowStockWt: '',
      //   nowStockVol: '',
      //   nowCargoValue: ''
      // }
      tableData: [],
      rules: {
        cargoNumber: [
          { required: true, message: "货物自然序号不能为空", trigger: "blur" }
        ],
        itemNumber: [
          { required: true, message: "商品料号不能为空", trigger: "blur" }
        ],
        bookNumber: [
          { required: true, message: "电子账册项号不能为空", trigger: "blur" }
        ],
        // customsNo: [
        //   { required: true, message: "报关单号不能为空", trigger: "blur" }
        // ],
        // listNumber: [
        //   { required: true, message: "核注清单号不能为空", trigger: "blur" }
        // ],
        opType: [
          { required: true, message: "业务性质不能为空", trigger: "blur" }
        ],
        tradType: [
          { required: true, message: "贸易性质不能为空", trigger: "blur" }
        ],
        // deptId: [
        //   { required: true, message: "所属公司不能为空", trigger: "blur" },
        // ],
        custId: [
          { required: true, message: "货主名称不能为空", trigger: "blur" },
        ],
        cargoId: [
          { required: true, message: "货物名称不能为空", trigger: "blur" },
        ],
        vesselName: [
          { required: true, message: "船舶名称不能为空", trigger: "blur" },
        ],
        billNo: [
          { required: true, message: "提运单号不能为空", trigger: "blur" },
        ],
        unit: [
          { required: true, message: "计量单位不能为空", trigger: "blur" },
        ],
        // hatchTpe: [
        //   { required: true, message: "舱口类型不能为空", trigger: "blur" },
        // ],
        // cargoMachine: [
        //   { required: true, message: "船港货机械不能为空", trigger: "blur" },
        // ],
        voyageNo: [
          { required: true, message: "航次号不能为空", trigger: "blur" },
        ],
        // cargoNum: [
        //   { required: true, message: "计划货物件数不能为空", trigger: "blur" },
        // ],
        cargoWt: [
          { required: true, message: "计划货物重量不能为空", trigger: "blur" },
        ],
        // cargoVol: [
        //   { required: true, message: "实际货物体积不能为空", trigger: "blur" },
        // ],
        // actNum: [
        //   { required: true, message: "实际货物件数不能为空", trigger: "blur" },
        // ],
        actWt: [
          { required: true, message: "实际货物重量不能为空", trigger: "blur" },
        ],
        // actVol: [
        //   { required: true, message: "实际货物体积不能为空", trigger: "blur" },
        // ],
        // stockNum: [
        //   { required: true, message: "出入库货物件数不能为空", trigger: "blur" },
        // ],
        stockWt: [
          { required: true, message: "出入库货物重量不能为空", trigger: "blur" },
        ],
        // stockVol: [
        //   { required: true, message: "出入库货物体积不能为空", trigger: "blur" },
        // ],
        expiryDate: [
          { required: true, message: "有效期至不能为空", trigger: "blur" },
        ],
        billNumber: [
          { required: true, message: "单据编号不能为空", trigger: "blur" },
        ],
        billDate: [
          { required: true, message: "单据日期不能为空", trigger: "blur" },
        ],
        currType: [
          { required: true, message: "币种不能为空", trigger: "blur" },
        ],
        unitPrice: [
          { required: true, message: "货物单价不能为空", trigger: "blur" },
        ],
        originCountry: [
          { required: true, message: "原产国不能为空", trigger: "blur" },
        ],
      },
      // 客户表格数据
      custList: [],
      // 货物表格数据
      cargoList: [],
      loading: false,
      // 正在更新表格数据
      updating: false,
      listMap: {},
    };
  },
  computed: {
    title() {
      if (this.readonly) {
        return '船舶载货清单详情';
      }
      return this.notAdd ? '编辑船舶载货清单' : '新增船舶载货清单';
    },
    readonly() {
      return this.voyageInfo.status == '1';
    },
    notAdd() {
      return !!this.form.id;
    }
  },
  created() {
    this.getCargoList();
    this.getCustList();
    this.getStockList();
    this.$store.dispatch('warehouse/getWarehouse', {})
  },
  methods: {
    warehouseName(row) {
      const stock = this.$store.getters.warehouseData[row.stockCode] || {};
      return stock.stockName;
    },
    // 判断对象值是否相等
    isObjectValueEqual(a, b) {
      return true;
      if (a === b) {
        return true;
      }
      if (!a || !b) {
        return false;
      }
      //取对象a和b的属性名
      let aProps = Object.keys(a);
      let bProps = Object.keys(b);
      //循环取出属性名，再判断属性值是否一致
      for (let i = 0; i < aProps.length; i++) {
        let propName = aProps[i];
        if ((a[propName] || b[propName]) && a[propName] != b[propName]) {
          return false;
        }
      }
      for (let i = 0; i < bProps.length; i++) {
        let propName = bProps[i];
        if ((a[propName] || b[propName]) && a[propName] != b[propName]) {
          return false;
        }
      }
      return true
    },
    maxStockNum(row) {
      if (!this.form.cargoNum) {
        this.$modal.msgError("请先填写实际交接量的数量");
        row.cargoNum = '0'
        return;
      }

      let count = 0
      for (let i = 0; i < this.tableData.length; i++) {
        count += Number(this.tableData[i].cargoNum)
      }
      this.$nextTick(() => {
        if (count > this.form.stockNum) {
          this.$set(row, "cargoNum", Math.max(0, Number(this.form.stockNum) - (Number(count) - Number(row.cargoNum))));
        }
        if (this.form.opType == '2') {
          if (row.cargoNum > row.nowStockNum) {
            row.cargoNum = row.nowStockNum
          }
        }
      })
    },
    maxStockWt(row) {
      if (!this.form.cargoWt) {
        this.$modal.msgError("请先填写实际交接量的重量");
        row.cargoWt = '0'
        return;
      }
      let count = 0
      for (let i = 0; i < this.tableData.length; i++) {
        count += Number(this.tableData[i].cargoWt)
      }
      this.$nextTick(() => {
        if (count > this.form.stockWt) {
          row.cargoWt = Number(this.form.stockWt) - (Number(count) - Number(row.cargoWt))
        }
        if (this.form.opType == '2') {
          if (row.cargoWt > row.nowStockWt) {
            row.cargoWt = row.nowStockWt
          }
        }
      })
    },
    maxStockVol(row) {
      if (!this.form.cargoVol) {
        this.$modal.msgError("请先填写实际交接量的体积");
        row.cargoVol = '0'
        return;
      }
      let count = 0
      for (let i = 0; i < this.tableData.length; i++) {
        count += Number(this.tableData[i].cargoVol)
      }
      this.$nextTick(() => {
        if (count > this.form.stockVol) {
          row.cargoVol = Number(this.form.stockVol) - (Number(count) - Number(row.cargoVol))
        }
        if (this.form.opType == '2') {
          if (row.cargoVol > row.nowStockVol) {
            row.cargoVol = row.nowStockVol
          }
        }
      })
    },
    maxCargoValue(row) {
      if (!this.form.cargoValue) {
        this.$modal.msgError("请先填写实际交接量的货物价值");
        row.cargoValue = '0'
        return;
      }
      let count = 0
      for (let i = 0; i < this.tableData.length; i++) {
        count += Number(this.tableData[i].cargoValue)
      }
      this.$nextTick(() => {
        if (count > this.form.cargoValue) {
          row.cargoValue = Number(this.form.cargoValue) - (Number(count) - Number(row.cargoValue))
        }
        if (this.form.opType == '2') {
          if (row.cargoValue > row.nowCargoValue) {
            row.cargoValue = row.nowCargoValue
          }
        }
      })
    },
    //设置现有库存
    setNowStockNum(row, index) {
      const findSame = this.tableData.some((ele, i) => {
        if (row.billNumber == ele.billNumber && row.stockId == ele.stockId && index != i) {
          this.$modal.msgError("已经存在这条出库记录了");
          this.tableData[index].billNumber = '';
          return true;
        }
      })
      if (findSame) {
        return;
      }
      this.listMap[row.stockId].forEach(ele => {
        if (ele.billNumber == row.billNumber) {
          row.nowStockNum = ele.cargoNum
          row.nowStockWt = ele.cargoWt
          row.nowStockVol = ele.cargoVol
          row.nowCargoValue = ele.cargoValue
        }
      })
    },
    getStockList() {
      if (this.form) {
        if (this.form.opType == '2') {
          let param = {
            custId: this.form.custId,
            cargoId: this.form.cargoId,
          }
          warehouseList(param).then(response => {
            this.stockList = response.stockList
            this.listMap = response.listMap || {};
          }).catch(e => {
          })
        } else {
          let param = {
            custId: this.form.custId,
            cargoId: this.form.cargoId,
          }
          stockNumList(param).then(response => {
            this.stockList = response.data
          }).catch(e => {
          })
        }
      }
    },
    // 点击了清单
    bmcargoClick(row) {
      this.$refs.form.clearValidate();
      this.tableData = row.billStockList;
      if (row.id === this.form.id) {
        return;
      }

      if (!this.isObjectValueEqual(this.form, this.tempRow)) {
        this.$confirm('您当前有修改未保存，是否保存？', '提示', {
          confirmButtonText: '保存',
          cancelButtonText: '不保存',
          type: 'warning',
          closeOnClickModal: false,
          distinguishCancelAndClose: true,
        }).then(() => {
          this.$refs.bmcargoList.setCurrentRow(this.tempRow);
          this.submitForm();
        }).catch((action) => {
          if (action === 'close') {
            this.$refs.bmcargoList.setCurrentRow(this.tempRow);
            return;
          }
          this.initForm(row);
        });
      } else {
        //console.log("row", row);
        this.initForm(row);
      }

    },
    // 设置出入库数量的默认值
    initForm(data) {
      const newData = { ...data };
      newData.opType = this.voyageInfo.opType;

      newData.cargoNum = newData.cargoNum || 0;
      newData.cargoWt = newData.cargoWt || 0;
      newData.cargoVol = newData.cargoVol || 0;

      if (!newData.actNum && newData.actNum !== 0) {
        newData.actNum = newData.cargoNum;
      }
      if (!newData.actWt && newData.actWt !== 0) {
        newData.actWt = newData.cargoWt;
      }
      if (!newData.actVol && newData.actVol !== 0) {
        newData.actVol = newData.cargoVol;
      }

      newData.ztNum = newData.ztNum || 0;
      newData.ztWt = newData.ztWt || 0;
      newData.ztVol = newData.ztVol || 0;

      this.tempRow = {
        ...newData,
      };
      this.form = newData;
      this.changeStockNum();
      this.changeStockWt();
      this.changeStockVol();
      this.updating = true;
      this.$nextTick(() => {
        this.updating = false;
      });
    },
    //货物
    setCargoDetail(cargoId) {
      this.cargoList.forEach(ele => {
        if (ele.id == cargoId) {
          this.form.cargoName = ele.cargoName;
          this.form.hsCode = ele.hsCode;
          this.form.cargoSpec = ele.cargoSpec;
          this.form.originCountry = ele.originCountry;
        }
      })
    },
    getCargoList() {
      let param = {};
      listCargo(param).then(response => {
        this.cargoList = response.data || [];
      }).catch(e => {
      });
    },
    setStockDetail(row) {
      //入库操作，赋值库存量
      this.stockList.forEach(ele => {
        if (ele.stockId == row.stockId) {
          //console.log(ele)
          row.stockName = ele.stockName
          row.stockCode = ele.stockCode
          if (this.form.opType == '1') {
            row.nowStockNum = ele.nowStockNum
            row.nowStockWt = ele.nowStockWt
            row.nowStockVol = ele.nowStockVol
            row.nowCargoValue = ele.nowCargoValue
          }
        }
      })
    },
    //客户
    setCustDetail(custId) {
      this.custList.forEach(ele => {
        if (ele.id == custId) {
          this.form.custName = ele.custName;
          this.form.custCode = ele.custCode;
        }
      })
    },
    getCustList() {
      let param = {};
      listCust(param).then(response => {
        this.custList = response.data;
      }).catch(e => {
      });
    },
    //动态添加行
    addList() {
      if (!this.tableData) {
        this.tableData = [{
          stockId: '',
          stockCode: '',
          stockName: '',
          cargoNum: '',
          cargoWt: '',
          cargoVol: '',
          cargoValue: '',
          nowStockNum: '',
          nowStockWt: '',
          nowStockVol: '',
          nowCargoValue: ''
        }]
      } else {
        this.tableData.push({
          stockId: '',
          stockCode: '',
          stockName: '',
          cargoNum: '',
          cargoWt: '',
          cargoVol: '',
          cargoValue: '',
          nowStockNum: '',
          nowStockWt: '',
          nowStockVol: '',
          nowCargoValue: ''
        })
      }
    },
    // 新增行
    addParamsSetting() {
      if (this.form.stockNum > 0 || this.form.stockWt > 0 || this.form.stockVol > 0) {
        this.addList()
      }

    },
    // 删除当前行
    deleteRow(index) {
      this.tableData.splice(index, 1)
    },
    getList() {
      if (this.$refs.bmcargoList) {
        this.$refs.bmcargoList.getList();
      }
    },
    //计算
    changeStockNum() {
      this.$nextTick(() => {
        if (!this.form.ztNum) {
          this.form.ztNum = 0;
        }
        if (!this.form.actNum) {
          this.form.actNum = 0;
        }
        if (this.form.opType == '1') {
          this.form.stockNum = Number(this.form.actNum) - Number(this.form.ztNum)
        } else {
          this.form.stockNum = this.form.actNum
        }
      })
    },
    changeStockWt() {
      this.$nextTick(() => {
        if (!this.form.ztWt) {
          this.form.ztWt = 0;
        }
        if (!this.form.actWt) {
          this.form.actWt = 0;
        }
        if (this.form.opType == '1') {
          this.form.stockWt = Number(this.form.actWt) - Number(this.form.ztWt)
        } else {
          this.form.stockWt = this.form.actWt
        }
      })
    },
    changeStockVol() {
      this.$nextTick(() => {
        if (!this.form.ztVol) {
          this.form.ztVol = 0;
        }
        if (!this.form.actVol) {
          this.form.actVol = 0;
        }
        if (this.form.opType == '1') {
          this.form.stockVol = Number(this.form.actVol) - Number(this.form.ztVol)
        } else {
          this.form.stockVol = this.form.actVol
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.voyageInfo.id && !this.form.voyageId) {
        this.$message.error(`航次信息获取出错`);
        return;
      }

      if (!this.form.billNumber) {
        this.$refs.billInput.updateNumber().then(res => {
          this.validSendData();
        }).catch(e => {
          this.$message.error('单据编号获取失败');
        });
        return;
      }
      this.validSendData();

    },
    validSendData() {
      this.$refs["form"].validate((valid, checkItem) => {
        if (valid) {
          this.loading = true;
          if (this.tableData) {
            this.form.billStockList = this.tableData;
          }
          if (this.form.id || this.form.id === 0) {
            updateBmcargo(this.form).then(response => {
              this.tempRow = this.form;
              this.$modal.msgSuccess("修改成功");
              this.loading = false;
              this.getList();
              this.$emit('completed');
            }).catch(e => {
              this.loading = false;
            });
          } else {
            const params = {
              ...this.form,
              voyageNo: this.voyageInfo.voyageNo,
              voyageId: this.voyageInfo.id,
              vesselName: this.voyageInfo.vesselName,
              deptId: this.voyageInfo.deptId,
              vesselId: this.voyageInfo.vesselId,
              netTon: this.voyageInfo.netTon,
              opType: this.voyageInfo.opType,
            }
            addBmcargo(params).then(response => {
              this.loading = false;
              this.initForm(DefaultForm);
              this.resetForm("form");
              this.$modal.msgSuccess("新增成功");
              this.getList();
              this.$emit('completed');
            }).catch(e => {
              this.loading = false;
            });
          }
        } else {
          this.$message({
            message: checkItem[Object.keys(checkItem)[0]][0].message,
            type: 'warning'
          });
        }
      });

    }
  }
}
</script>

<style lang="scss" scoped>
.bmcargo-edit {
  display: flex;
  flex-direction: row;
  height: 88vh;
}

.edit-header {
  height: 46px;
  padding: 0 10px;
  position: relative;
}

.header-title {
  line-height: 46px;
  width: 100%;
  text-align: center;
  font-size: 20px;
  font-weight: 500;
}

.header-btns {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
}

.edit-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.edit-scroll {
  flex: 1;
  width: 100%;
  overflow: scroll;
  overflow-x: scroll;
  overflow-y: scroll;
  background-color: #e8f4ff;
  border-radius: 4px;
  padding: 10px;
}

.nomal-text {
  padding: 10px;
}

.margin-none {
  margin: 0;
}

::v-deep .el-descriptions--medium.is-bordered .el-descriptions-item__cell {
  /* padding: 10px; */
  padding: 0;
}

::v-deep .el-descriptions :not(.is-bordered) .el-descriptions-item__cell {
  /* padding-bottom: 12px; */
  padding-bottom: 0;
}

::v-deep .el-descriptions .is-bordered .el-descriptions-item__cell {
  /* border: 1px solid #e6ebf5; */
  /* padding: 12px 10px; */
  padding: 0;
}

::v-deep .el-descriptions-item__label.is-bordered-label {
  padding: 5px !important;
  min-width: 130px;
  max-width: 160px;
}

::v-deep .el-descriptions {
  min-width: 862px;
}
</style>
