<!--单包计量预报管理-->
<template>
  <div class="systemBase">
    <div>
      <div style="margin-top: 10px; border-bottom: 1px solid #d5d5d5">
        <el-form
          ref="searchData1"
          :inline="true"
          :model="search"
          style="padding-left: 12px"
        >
          <el-form-item prop="carNo" label="车号">
            <el-input
              v-model="search.carNo"
              clearable
              size="small"
              style="width: 120px"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item prop="meterTypeName" label="业务类型">
            <el-select
              v-model="search.meterTypeName"
              clearable
              filterable
              collapse-tags
              size="small"
              style="width: 120px"
            >
              <el-option
                v-for="(item, index) in meterTypeNameItem"
                :key="index"
                :label="item.baseName"
                :value="item.baseName"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="matterNo" label="物资名称">
            <el-select
              v-model="search.matterNo"
              clearable
              filterable
              collapse-tags
              size="small"
              style="width: 120px"
            >
              <el-option
                v-for="item in topMatList"
                :key="item.matterNo"
                :label="item.matterName"
                :value="item.matterNo"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="valueFlag" label="预报状态">
            <el-select
              v-model="search.valueFlag"
              clearable
              filterable
              collapse-tags
              size="small"
              style="width: 120px"
            >
              <el-option
                v-for="(item, index) in valueFlagItem"
                :key="index"
                :label="item.valueFlag"
                :value="item.valueFlag"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="startTime" label="开始时间">
            <el-date-picker
              class="measure-self-picker"
              v-model="search.startTime"
              clearable
              type="datetime"
              style="width: 140px"
              placeholder="选择日期"
              @change="dateChange(search.startTime, 'startTime', 'search')"
              size="small"
            ></el-date-picker>
          </el-form-item>
          <el-form-item prop="endTime" label="结束时间">
            <el-date-picker
              class="measure-self-picker"
              v-model="search.endTime"
              clearable
              type="datetime"
              style="width: 140px"
              placeholder="选择日期"
              @change="dateChange(search.endTime, 'endTime', 'search')"
              size="small"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label-width="20px">
            <el-button
              icon="el-icon-search"
              type="primary"
              size="mini"
              @click="searchDatas"
              v-loading.fullscreen.lock="operateLoading"
              v-privilege="activeMenu + 'QUERY'"
              >查询</el-button
            >
            <el-button
              icon="el-icon-circle-plus-outline"
              type="primary"
              size="mini"
              @click="showAddDialog"
              v-loading.fullscreen.lock="operateLoading"
              v-privilege="activeMenu + 'QUERY'"
              >录入重量</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <el-row>
        <el-col :span="24">
          <div style="border-right: 1px solid #d5d5d5">
            <div class="common-title-div">单包计量预报数据</div>
            <div class="common-table-div">
              <el-table
                v-loading="dataLoading"
                @row-click="rowChange"
                ref="forecastTable"
                highlight-current-row
                border
                :height="forecastTableHeight"
                :data="forecastList"
                :exchangeFilterMap="{
                  valueFlag: {
                    '0': '未配车',
                    '1': '未使用',
                    '2': '已使用',
                    '3': '已作废',
                    '4': '正使用',
                  },
                  predictionType: {
                    '0': '批次预报',
                    '1': '单次预报',
                    '2': '联运预报',
                    '3': '分检预报',
                  },
                  usedType: { '0': '次数', '1': '时间', '2': '总量' },
                }"
                :icore-filter-flag="icoreFilterFlag"
                >>
                <el-table-column
                  type="index"
                  label="序号"
                  fixed="left"
                  align="center"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="predictionNo"
                  label="预报编号"
                  min-width="120"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="valueFlag"
                  label="状态"
                  width="60"
                  min-width="100"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span v-if="scope.row.valueFlag == 0">未配车</span>
                    <span v-else-if="scope.row.valueFlag == 1">未使用</span>
                    <span v-else-if="scope.row.valueFlag == 2">已使用</span>
                    <span v-else-if="scope.row.valueFlag == 3">已作废</span>
                    <span v-else-if="scope.row.valueFlag == 4">正使用</span>
                  </template>
                </el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="contractNo"
                  label="合同号"
                  min-width="160"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="batchNo"
                  min-width="110"
                  label="批次号"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="carNo"
                  label="车号"
                  min-width="110"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="matterName"
                  label="物资名称"
                  min-width="120"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="shipmentNum"
                  min-width="100"
                  label="发运数量"
                  align="right"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="customerSupplierName"
                  min-width="160"
                  label="供应商"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="forwardingUnitName"
                  min-width="160"
                  label="发货单位"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="receivingUintName"
                  min-width="160"
                  label="收货单位"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="specName"
                  min-width="100"
                  label="规格"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="shipmentGrossWeight"
                  min-width="100"
                  label="发运毛重"
                  align="right"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="shipmentNetWeight"
                  min-width="100"
                  label="发运净重"
                  align="right"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="loadPointName"
                  min-width="100"
                  label="卸货地点"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="predictionType"
                  min-width="100"
                  label="预报类型"
                  align="left"
                >
                  <template slot-scope="scope">
                    <span v-if="scope.row.predictionType == 0">批次预报</span>
                    <span v-else-if="scope.row.predictionType == 1"
                      >单次预报</span
                    >
                    <span v-else-if="scope.row.predictionType == 2"
                      >联运预报</span
                    >
                    <span v-else-if="scope.row.predictionType == 3"
                      >分检预报</span
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="meterTypeName"
                  min-width="100"
                  label="业务类型"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="carAllocationTime"
                  min-width="160"
                  label="配车时间"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="memo"
                  min-width="200"
                  label="备注"
                  align="left"
                ></el-table-column>
              </el-table>
            </div>
            <div class="common-foot-style">
              <el-pagination
                v-loading="dataLoading"
                @size-change="pageSizeChange"
                @current-change="pageCurrentChange"
                :current-page="page.pageNum"
                :page-sizes="[100, 500, 1000]"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.totalPage"
              >
              </el-pagination>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div style="margin-top: 10px; border-bottom: 1px solid #d5d5d5">
            <el-form
              ref="searchData1"
              :inline="true"
              :model="actualSearchForm"
              style="padding-left: 12px"
            >
              <el-form-item prop="carNo" label="车号">
                <el-input
                  v-model="actualSearchForm.carNo"
                  clearable
                  size="small"
                  style="width: 120px"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
              <el-form-item prop="meterTypeName" label="业务类型">
                <el-select
                  v-model="actualSearchForm.meterTypeName"
                  clearable
                  filterable
                  collapse-tags
                  size="small"
                  style="width: 120px"
                >
                  <el-option
                    v-for="(item, index) in meterTypeNameItem"
                    :key="index"
                    :label="item.baseName"
                    :value="item.baseName"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="matterNo" label="物资名称">
                <el-select
                  v-model="actualSearchForm.matterNo"
                  clearable
                  filterable
                  collapse-tags
                  size="small"
                  style="width: 120px"
                >
                  <el-option
                    v-for="item in topMatList"
                    :key="item.matterNo"
                    :label="item.matterName"
                    :value="item.matterNo"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="startTime" label="开始时间">
                <el-date-picker
                  class="measure-self-picker"
                  v-model="actualSearchForm.startTime"
                  clearable
                  type="datetime"
                  style="width: 140px"
                  placeholder="选择日期"
                  @change="
                    dateChange(
                      actualSearchForm.startTime,
                      'startTime',
                      'actualSearchForm'
                    )
                  "
                  size="small"
                ></el-date-picker>
              </el-form-item>
              <el-form-item prop="endTime" label="结束时间">
                <el-date-picker
                  class="measure-self-picker"
                  v-model="actualSearchForm.endTime"
                  clearable
                  type="datetime"
                  style="width: 140px"
                  placeholder="选择日期"
                  @change="
                    dateChange(
                      actualSearchForm.endTime,
                      'endTime',
                      'actualSearchForm'
                    )
                  "
                  size="small"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label-width="20px">
                <el-button
                  icon="el-icon-search"
                  type="primary"
                  size="mini"
                  @click="searchActualData"
                  v-loading.fullscreen.lock="operateLoading"
                  v-privilege="activeMenu + 'QUERY1'"
                  >查询</el-button
                >
                <!-- <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                  @click="showEditDialog('single')"
                  v-loading.fullscreen.lock="operateLoading"
                  v-privilege="activeMenu + 'UPDATE'"
                  >修改</el-button
                > -->
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-check"
                  @click="showEditDialog('batch')"
                  v-loading.fullscreen.lock="operateLoading"
                  v-privilege="activeMenu + 'BATCHEDIT'"
                  >批量修改</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  @click="dropData"
                  v-loading.fullscreen.lock="operateLoading"
                  >作废</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div style="border-right: 1px solid #d5d5d5">
            <div class="common-title-div">
              单包计量实绩数据
              <!-- <div class="common-operation-button-div"> -->
              <!-- <el-button
                  icon="el-icon-circle-plus-outline"
                  type="primary"
                  size="mini"
                  @click="addData"
                  v-loading.fullscreen.lock="operateLoading"
                  v-privilege="activeMenu + 'ADD'"
                  >新增</el-button
                > -->
              <!-- <el-button
                  size="mini"
                  type="danger"
                  plain
                  icon="el-icon-remove-outline"
                  @click="discardData"
                  v-loading.fullscreen.lock="operateLoading"
                  v-privilege="activeMenu + 'ABOLISH'"
                  >废除</el-button
                > -->
              <!-- </div> -->
            </div>
            <div class="common-table-div">
              <el-table
                v-loading="dataLoading"
                @selection-change="selectionChange"
                ref="actualTable"
                highlight-current-row
                border
                :height="actualHeight"
                :row-class-name="tableRowClassName"
                :data="actualList"
                show-summary
                :summary-method="getSum"
                :exchangeFilterMap="{
                  valueFlag: {
                    '0': '未配车',
                    '1': '未使用',
                    '2': '已使用',
                    '3': '已作废',
                    '4': '正使用',
                  },
                  predictionType: {
                    '0': '批次预报',
                    '1': '单次预报',
                    '2': '联运预报',
                    '3': '分检预报',
                  },
                  usedType: { '0': '次数', '1': '时间', '2': '总量' },
                }"
                :icore-filter-flag="icoreFilterFlag"
                >>
                <el-table-column
                  type="index"
                  label="序号"
                  fixed="left"
                  align="center"
                ></el-table-column>
                <el-table-column
                  type="selection"
                  fixed="left"
                  align="center"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="predictionNo"
                  label="预报编号"
                  min-width="120"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="contractNo"
                  label="合同号"
                  min-width="160"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="batchNo"
                  min-width="110"
                  label="批次号"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="carNo"
                  label="车号"
                  min-width="110"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="grossWeight"
                  label="毛重/kg"
                  min-width="80"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="tareWeight"
                  label="皮重/kg"
                  min-width="80"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="netWeight"
                  label="净重/kg"
                  min-width="80"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="matterName"
                  label="物资名称"
                  min-width="120"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="shipmentNum"
                  min-width="100"
                  label="发运数量"
                  align="right"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="customerSupplierName"
                  min-width="160"
                  label="供应商"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="forwardingUnitName"
                  min-width="160"
                  label="发货单位"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="receivingUintName"
                  min-width="160"
                  label="收货单位"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="specName"
                  min-width="100"
                  label="规格"
                  align="left"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="shipmentGrossWeight"
                  min-width="100"
                  label="发运毛重"
                  align="right"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="shipmentNetWeight"
                  min-width="100"
                  label="发运净重"
                  align="right"
                ></el-table-column>
                <el-table-column
                  sortable
                  :show-overflow-tooltip="true"
                  prop="loadPointName"
                  min-width="100"
                  label="卸货地点"
                  align="left"
                ></el-table-column>
                <el-table-column
                  :show-overflow-tooltip="true"
                  min-width="100"
                  label="操作"
                  align="left"
                  fixed="right"
                >
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      size="mini"
                      @click="showEditDialog('single', scope.row)"
                      >修改</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="common-foot-style">
              <el-pagination
                v-loading="dataLoading1"
                @size-change="pageSizeChange1"
                @current-change="pageCurrentChange1"
                :current-page="page1.pageNum"
                :page-sizes="[100, 500, 1000]"
                :page-size="page1.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page1.totalPage"
              >
              </el-pagination>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog
      @close="closeDialog"
      :visible.sync="showFlag"
      customClass="weight-input-wrap"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formObj"
        label-width="70px"
        :inline="true"
        :model="formObj"
        :rules="rules"
      >
        <el-form-item prop="contractNo" label="合 同  号">
          <el-input
            v-model="formObj.contractNo"
            clearable
            size="small"
            style="width: 160px"
            placeholder="请输入"
            :disabled="editFlag === 'add' ? 'disabled' : false"
          ></el-input>
        </el-form-item>
        <el-form-item prop="batchNo" label="批次号" class="edit-row-wrap">
          <el-input
            style="width: 160px"
            v-model="formObj.batchNo"
            size="small"
            clearable
            placeholder="请输入"
            :disabled="editFlag === 'add' ? 'disabled' : false"
          ></el-input>
        </el-form-item>
        <el-form-item prop="matterName" label="物资名称">
          <el-select
            size="mini"
            style="width: 160px"
            filterable
            v-model="formObj.matterName"
            :disabled="editFlag === 'add' ? 'disabled' : false"
          >
            <el-option
              v-for="item in matList"
              :key="item.matterNo"
              :label="item.matterName"
              :value="item.matterName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="customerSupplierName" label="供应商">
          <el-select
            size="mini"
            style="width: 160px"
            filterable
            v-model="formObj.customerSupplierName"
            :disabled="editFlag === 'add' ? 'disabled' : false"
            :filter-method="filterECust"
            @change="custChange"
          >
            <el-option
              v-for="item in unitList"
              :key="item.customerSupplierNo"
              :label="item.customerSupplierName"
              :value="item.customerSupplierName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="forwardingUnitName" label="发货单位">
          <el-select
            size="mini"
            style="width: 160px"
            filterable
            v-model="formObj.forwardingUnitName"
            :disabled="editFlag === 'add' ? 'disabled' : false"
            :filter-method="filterESdr"
            @change="sdrChange"
          >
            <el-option
              v-for="item in editProList"
              :key="item.customerSupplierNo"
              :label="item.customerSupplierName"
              :value="item.customerSupplierName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="receivingUintName" label="收货单位">
          <el-select
            size="mini"
            style="width: 160px"
            filterable
            v-model="formObj.receivingUintName"
            :disabled="editFlag === 'add' ? 'disabled' : false"
            :filter-method="filterERcv"
            @change="rcvChange"
          >
            <el-option
              v-for="item in editReceList"
              :key="item.customerSupplierNo"
              :label="item.customerSupplierName"
              :value="item.customerSupplierName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="meterTypeName" label="业务类型">
          <el-select
            v-model="formObj.meterTypeName"
            clearable
            filterable
            collapse-tags
            size="small"
            style="width: 160px"
            @change="meterTypeChange"
          >
            <el-option
              v-for="(item, index) in meterTypeNameItem"
              :key="index"
              :label="item.baseName"
              :value="item.baseName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="carNo" label="车号" v-if="wgtFlag === 'single'">
          <el-input
            v-model="formObj.carNo"
            size="small"
            style="width: 160px"
            :disabled="editFlag === 'add' ? 'disabled' : false"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="shipmentNum"
          label="发运数量"
          v-if="wgtFlag === 'single'"
        >
          <el-input
            v-model="formObj.shipmentNum"
            size="small"
            type="number"
            style="width: 160px"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="grossWeight"
          label="毛重"
          v-if="wgtFlag === 'single'"
        >
          <el-input
            v-model="formObj.grossWeight"
            size="small"
            type="number"
            style="width: 160px"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="tareWeight"
          label="皮重"
          v-if="wgtFlag === 'single'"
        >
          <el-input
            v-model="formObj.tareWeight"
            size="small"
            type="number"
            style="width: 160px"
          ></el-input>
        </el-form-item>
        <el-form-item prop="netWeight" label="净重" v-if="wgtFlag === 'single'">
          <el-input
            v-model="formObj.netWeight"
            size="small"
            type="number"
            style="width: 160px"
            readonly
          ></el-input>
        </el-form-item>
        <el-form-item label="重量单位" v-if="wgtFlag === 'single'">
          <el-select v-model="unitFlag" size="small">
            <el-option
              v-for="item in wgtUnitList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" size="mini" @click="createData"
          >确定</el-button
        >
        <el-button size="mini" type="default" @click="closeDialog"
          >取消</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { formatDate, getCookie } from '@/utils/util.js';
import { cookieUserId, cookieUserName } from '@/config/config.js';
import { recordChange } from '~/utils/utils'
export default {
  data () {
    return {
      search: {
        predictionNo: '',
        carNo: '',
        meterTypeName: '',
        matterNo: '',
        valueFlag: '',
        predictionType: '',
        startTime: formatDate(new Date(), 'yyyy-MM-dd') + ' 00:00:00',
        endTime: formatDate(new Date(), 'yyyy-MM-dd') + ' 23:59:59',
        contractNo: ''
      },
      actualSearchForm: {
        predictionNo: '',
        carNo: '',
        meterTypeName: '',
        matterNo: '',
        predictionType: '',
        startTime: formatDate(new Date(), 'yyyy-MM-dd') + ' 00:00:00',
        endTime: formatDate(new Date(), 'yyyy-MM-dd') + ' 23:59:59',
        contractNo: ''
      },
      page: {
        pageSize: 100,
        pageNum: 1,
        totalPage: 0
      },
      page1: {
        pageSize: 100,
        pageNum: 1,
        totalPage: 0
      },
      dataLoading: false,
      actualList: [],
      forecastList: [],
      icoreFilterFlag: true,
      forecastTableHeight: '270',
      actualHeight: '400',
      topMatList: [],
      bottomMatList: [],
      meterTypeNameItem: [],
      valueFlagItem: [
        { valueFlag: '未配车' },
        { valueFlag: '未使用' },
        { valueFlag: '已使用' },
        { valueFlag: '已作废' },
        { valueFlag: '正使用' }
      ],
      operateLoading: false,
      dataLoading1: false,
      showFlag: false,
      forecastRow: {},
      actualRow: {},
      formObj: {
        forwardingUnitName: '',
        forwardingUnitNo: '',
        meterTypeName: '',
        meterTypeNo: '',
        receivingUintName: '',
        receivingUintNo: '',
        contractNo: '',
        matterName: '',
        matterNo: '',
        customerSupplierName: '',
        customerSupplierNo: '',
        carNo: '',
        batchNo: '',
        grossWeight: 0,
        tareWeight: 0,
        netWeight: 0,
        shipmentNum: ''
      },
      formObjCache: {
        forwardingUnitName: '',
        forwardingUnitNo: '',
        meterTypeName: '',
        meterTypeNo: '',
        receivingUintName: '',
        receivingUintNo: '',
        contractNo: '',
        matterName: '',
        matterNo: '',
        customerSupplierName: '',
        customerSupplierNo: '',
        carNo: '',
        batchNo: '',
        grossWeight: 0,
        tareWeight: 0,
        netWeight: 0
      },
      wgtObj: {
        grossWeight: 0,
        tareWeight: 0,
        netWeight: 0
      },
      rules: {
        grossWeight: [{ required: true, message: '毛重不能为空', trigger: 'blur' }],
        tareWeight: [{ required: true, message: '皮重不能为空', trigger: 'blur' }],
        netWeight: [{ required: true, message: '净重不能为空', trigger: 'blur' }],
        contractNo: [{ required: true, message: '合同号不能为空', trigger: 'blur' }],
        matterName: [{ required: true, message: '物资不能为空', trigger: 'blur' }],
        forwardingUnitName: [{ required: true, message: '发货单位不能为空', trigger: 'blur' }],
        receivingUintName: [{ required: true, message: '收货单位不能为空', trigger: 'blur' }],
        meterTypeName: [{ required: true, message: '业务类型不能为空', trigger: 'blur' }]
      },
      unitFlag: 'kg',
      wgtUnitList: [{ id: 'kg', name: '千克' }, { id: 't', name: '吨' }],
      editFlag: 'add',
      wgtFlag: 'single',
      batchList: [],
      dialogTitle: '单包计量新增',
      matList: [],
      unitList: [],
      editCustList: [],
      editReceList: [],
      editProList: []
    }
  },
  created () {
    this.activeMenu = window.top.localStorage.getItem('activeMenu')
    this.getMatterNameItem();//物料
    this.getMeterbasecustomersupplier(); // 客商数据
    this.getMeterTypeNameItem();//业务类型
  },
  mounted () {
    this.searchDatas()
    this.searchActualData()
  },
  methods: {
    init () {
      this.searchDatas()
      this.searchActualData()
    },
    searchDatas (flag = 1) {
      if (flag === 1) {
        this.page.pageNum = 1;
      }
      // 将预报表格滚动到顶部
      this.$refs.forecastTable.bodyWrapper.scrollTop = 0;
      this.dataLoading = true;
      let meterTypeName = this.search.meterTypeName === '' ? '单包计量' : this.search.meterTypeName
      this.search.valueFlag1 = this.search.valueFlag === '未配车' ? 0 : this.search.valueFlag === '未使用' ? 1 : this.search.valueFlag === '已使用' ? 2 : this.search.valueFlag === '已作废' ? 3 : this.search.valueFlag === '正使用' ? 4 : ''
      this.axios.get('pass/systemBase/v1/pretrackscales/' + '?pageNum=' + this.page.pageNum + '&pageSize=' + this.page.pageSize + '&carNo=' + this.search.carNo + '&predictionNo=' + this.search.predictionNo
        + '&predictionType=' + this.search.predictionType + '&meterTypeName=' + meterTypeName + '&matterNo=' + this.search.matterNo + '&valueFlag=' + this.search.valueFlag1 +
        `&startTime=${this.search.startTime}&endTime=${this.search.endTime}&contractNo=${this.search.contractNo}`)
        .then(res => {
          this.dataLoading = false;
          if (res.data && res.data.list) {
            this.forecastList = res.data.list;
            this.page.totalPage = res.data.total;
          } else {
            this.forecastList = []
            this.page.totalPage = 0
          }

        }).catch(e => {
          this.dataLoading = false;
        });
    },
    rowChange (val) {
      this.forecastRow = { ...val }
    },
    rowChange1 (val) {
      this.actualRow = { ...val }
    },
    tableRowClassName ({
      row,
      rowIndex
    }) {
      if (row.valueFlag === '3') {
        return 'error-row2';
      }
      return '';
    },
    async dropData (row) {
      if (this.batchList.length <= 0) return this.$message.error('请勾选要进行废除的数据')
      let stateFlag = true
      this.batchList.forEach(item => {
        if (item.valueFlag - 0 !== 0) {
          stateFlag = false
        }
      })
      if (!stateFlag) return this.$message.error('选中数据中存在已作废数据，无法进行作废操作')
      let confirm = await this.$confirm('确认要作废这些记录吗？').catch(() => 'cancel')
      if (confirm === 'cancel') return
      this.batchList.forEach(item => {
        item.valueFlag = '1'
      })
      const data = await this.axios.post('pass/systemBase/v1/meterworkcaractuals/updateByDanBao', [...this.batchList], { individualType: 'json' })
      if (data.status === 'succeed') {
        this.$message.success('作废成功')
        this.init()
      } else {
        this.$message.error(data.message)
      }
    },
    // 显示批量录入窗口
    showAddDialog () {
      if (JSON.stringify(this.forecastRow) === "{}") {
        return this.$message.error('请点选要进行重量录入的单包计量预报')
      }
      this.dialogTitle = '单包计量新增'
      this.showFlag = true
      this.editFlag = 'add'
      this.wgtFlag = 'single'
      this.formObj = { ...this.forecastRow, ...this.wgtObj }
    },
    meterTypeChange (val) {
      if (val) {
        let item = this.meterTypeNameItem.find(o => o.baseName === val)
        if (item) {
          this.formObj.meterTypeNo = item.baseCode;
        }
      } else {
        this.formObj.meterTypeNo = '';
      }
    },
    selectionChange (val) {
      this.batchList = [...val]
    },
    // 单包计量数据维护
    async createData () {
      let msg = this.editFlag === 'add' ? '新增' : '修改'
      if (this.unitFlag === 'kg') {
        if (this.formObj.netWeight < 150) {
          let confirmFlag = await this.$confirm(`当前输入净重小于150千克，确定要进行${msg}吗？`).catch(() => 'cancel');
          if (confirmFlag === 'cancel') return false;
        }
      } else {
        if (this.formObj.netWeight > 150) {
          let confirmFlag = await this.$confirm(`当前输入净重大于150吨，确定要进行${msg}吗？`).catch(() => 'cancel');
          if (confirmFlag === 'cancel') return false;
        }
      }
      // 判断是新增还是修改
      if (this.editFlag === 'add') {
        // 新增
        // 数据校验
        let valid = await this.$refs.formObj.validate().catch(() => false)
        if (!valid) return this.$message.error('请规范填写数据')
        if (this.unitFlag !== 'kg') {
          this.formObj.grossWeight = this.formObj.grossWeight * 1000
          this.formObj.tareWeight = this.formObj.tareWeight * 1000
          this.formObj.netWeight = this.formObj.netWeight * 1000
        }
        const data = await this.axios.post('pass/systemBase/v1/meterworkcaractuals/insertByScale', this.formObj, { individualType: 'json' })
        if (data.status === 'succeed') {
          this.$message.success('新增成功')
          this.searchDatas()
          this.searchActualData()
          this.closeDialog()
        } else {
          this.$message.error(data.message)
          if (this.unitFlag !== 'kg') {
            this.formObj.grossWeight = this.pageFloatComputed((this.formObj.grossWeight - 0), 1000, '/')
            this.formObj.tareWeight = this.pageFloatComputed((this.formObj.tareWeight - 0), 1000, '/')
            this.formObj.netWeight = this.pageFloatComputed((this.formObj.netWeight - 0), 1000, '/')
          }
        }
      } else {
        // 修改
        let paramList = []
        if (this.wgtFlag === 'single') {
          // 校验必填项
          let valid = await this.$refs.formObj.validate().catch(() => false)
          if (!valid) return this.$message.error('请规范填写数据')
          if (this.unitFlag !== 'kg') {
            this.formObj.grossWeight = this.formObj.grossWeight * 1000
            this.formObj.tareWeight = this.formObj.tareWeight * 1000
            this.formObj.netWeight = this.formObj.netWeight * 1000
          }
          paramList = [
            {
              ...this.formObj
            }
          ]
        } else if (this.wgtFlag === 'batch') {
          this.rules['grossWeight'].required = false
          this.rules['tareWeight'].required = false
          this.rules['netWeight'].required = false
          let valid = await this.$refs.formObj.validate().catch(() => false)
          if (!valid) return this.$message.error('请规范填写数据')
          paramList = []
          this.batchList.forEach(item => {
            paramList.push({
              ...item,
              contractNo: this.formObj.contractNo,
              batchNo: this.formObj.batchNo,
              matterName: this.formObj.matterName,
              matterNo: this.formObj.matterNo,
              customerSupplierName: this.formObj.customerSupplierName,
              customerSupplierNo: this.formObj.customerSupplierNo,
              forwardingUnitName: this.formObj.forwardingUnitName,
              forwardingUnitNo: this.formObj.forwardingUnitNo,
              receivingUintName: this.formObj.receivingUintName,
              receivingUintNo: this.formObj.receivingUintNo,
              meterTypeName: this.formObj.meterTypeName,
              meterTypeNo: this.formObj.meterTypeNo
            })
          })
        }
        const data = await this.axios.post('pass/systemBase/v1/meterworkcaractuals/updateByDanBao', paramList, { individualType: 'json' })
        if (data.status === 'succeed') {
          this.$message.success('修改成功')
          this.searchDatas()
          this.searchActualData()
          this.closeDialog()
        } else {
          this.$message.error(data.message)
          if (this.unitFlag !== 'kg') {
            this.formObj.grossWeight = this.pageFloatComputed((this.formObj.grossWeight - 0), 1000, '/')
            this.formObj.tareWeight = this.pageFloatComputed((this.formObj.tareWeight - 0), 1000, '/')
            this.formObj.netWeight = this.pageFloatComputed((this.formObj.netWeight - 0), 1000, '/')
          }
        }
      }
    },
    pageFloatComputed (arg1, arg2, sign) {
      if (!arg1) {
        arg1 = 0;
      }
      if (!arg2) {
        arg2 = 0;
      }
      let val1 = arg1 + '';
      let val2 = arg2 + '';
      let rate = 1;
      let rate1 = 1;
      let rate2 = 1;
      if (val1.indexOf('.') < 0) {
        rate1 = 0;
      } else {
        rate1 = val1.length - val1.indexOf('.') - 1;
      }
      if (val2.indexOf('.') < 0) {
        rate2 = 0;
      } else {
        rate2 = val2.length - val2.indexOf('.') - 1;
      }
      rate = rate2;
      val2 = val2.replace('.', '');
      val1 = val1.replace('.', '');
      if (rate1 > rate2) {
        rate = rate1;
        for (let i = 0; i < rate1 - rate2; i++) {
          val2 = val2 + '0'
        }
      } else {
        for (let i = 0; i < rate2 - rate1; i++) {
          val1 = val1 + '0';
        }
      }
      let rateNum = Math.pow(10, rate);
      if (sign === '-') {
        return (Number(val1) - Number(val2)) / rateNum
      }
      if (sign === '+') {
        return (Number(val1) + Number(val2)) / rateNum
      }
      if (sign === '*') {
        return (Number(val1) * Number(val2)) / (rateNum * rateNum)
      }
      if (sign === '/') { // 默认保留4位
        let num = 0;
        if (Number(val1) - 0 !== 0 && Number(val2) - 0 !== 0) {
          num = (Number(val1) / Number(val2)) + '';
          if (num.split('.').length > 0) {
            if (num[1].length > 4) {
              num = num.toFixed(8);
            }
          }
        }
        return num;
      }
      return null;
    },
    // 单包计量实绩数据查询
    async searchActualData (flag = 1) {
      if (flag === 1) {
        this.page1.pageNum = 1
      }
      let meterTypeName = this.search.meterTypeName === '' ? '单包计量' : this.search.meterTypeName
      let paramStr = `pageNum=${this.page1.pageNum}&pageSize=${this.page1.pageSize}&carNo=${this.actualSearchForm.carNo}&meterTypeName=${meterTypeName}&matterNo=${this.actualSearchForm.matterNo}&netTime1=${this.actualSearchForm.startTime}&netTime2=${this.actualSearchForm.endTime}&valueFlag=0`
      const { data: res } = await this.axios.get(`pass/systemBase/v1/meterworkcaractuals/selectView?${paramStr}`)
      if (res && res.list) {
        this.actualList = [...res.list];
        this.page1.totalPage = res.total - 0
      } else {
        this.actualList = [];
        this.page1.totalPage = 0;
      }
    },
    getMatterNameItem () {
      this.axios.get('pass/systemBase/v1/meterbasematterinfos/noPage' + '?validFlag=1')
        .then(res => {
          this.topMatList = [...res.data]
          this.matList = [...res.data]
        })
    },
    // 查询客商表里面的所有有效数据
    async getMeterbasecustomersupplier () {
      const { data: res } = await this.axios.get('pass/systemBase/v1/meterbasecustomersuppliers/like/?pageNum=1&pageSize=100000&checkFlag=1&validFlag=1')
      // 给供应商，发货单位，收货单位赋值
      this.unitList = [...res.list];
      this.editCustList = [...res.list].slice(0, 300);
      this.editReceList = [...res.list].slice(0, 300);
      this.editProList = [...res.list].slice(0, 300);
    },
    getMeterTypeNameItem () {
      this.axios.get('pass/systemBase/v1/combaseinfos/noPage' + '?pBaseCode=001038' + '&validFlag=1')
        .then(res => {
          this.meterTypeNameItem = [...res.data];
        })
    },
    // 物资选中
    matChange (val) {
      if (val) {
        let item = this.matList.find(item => item.matterName === val)
        if (item) {
          this.formObj.matterNo = item.matterNo
        }
      }
    },
    // 发货单位筛选
    filterESdr (val) {
      if (val) {
        this.editProList = this.unitList.filter(item => {
          if (item.customerSupplierName.indexOf(val) !== -1) {
            return true
          }
        }).slice(0, 300)
      } else {
        this.editProList = [...this.unitList].slice(0, 300)
      }
    },
    // 收货单位筛选
    filterERcv (val) {
      if (val) {
        this.editReceList = this.unitList.filter(item => {
          if (item.customerSupplierName.indexOf(val) !== -1) {
            return true
          }
        }).slice(0, 300)
      } else {
        this.editReceList = [...this.unitList].slice(0, 300)
      }
    },
    // 供应商筛选
    filterECust (val) {
      if (val) {
        this.editCustList = this.unitList.filter(item => {
          if (item.customerSupplierName.indexOf(val) !== -1) {
            return true
          }
        }).slice(0, 300)
      } else {
        this.editCustList = [...this.unitList].slice(0, 300)
      }
    },
    // 供应商选中
    custChange (val) {
      if (val) {
        let item = this.unitList.find(item => item.customerSupplierName === val)
        if (item) {
          this.formObj.customerSupplierNo = item.customerSupplierNo
        }
      }
    },
    // 发货单位选中
    sdrChange (val) {
      if (val) {
        let item = this.unitList.find(item => item.customerSupplierName === val)
        if (item) {
          this.formObj.forwardingUnitNo = item.customerSupplierNo
        }
      }
    },
    // 收货单位选中
    rcvChange (val) {
      if (val) {
        let item = this.unitList.find(item => item.customerSupplierName === val)
        if (item) {
          this.formObj.receivingUintNo = item.customerSupplierNo
        }
      }
    },
    getSum ({ columns, data }) {
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          if (column.property === 'grossWeight' | column.property === 'tareWeight' | column.property === 'netWeight' | column.property === 'shipmentNum') {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value) && value - 0 !== 0) {
                return this.floatComputed1(prev, curr, '+');
              } else {
                return prev;
              }
            }, 0);
            // if (column.property !== 'shipmentNum') {
            //   sums[index] = this.floatComputed1(sums[index], 1000, '/')
            // }
          }
        }
      });
      return sums;
    },
    floatComputed1 (arg1, arg2, sign) {
      if (!arg1) {
        arg1 = 0;
      }
      if (!arg2) {
        arg2 = 0;
      }
      let val1 = arg1 + '';
      let val2 = arg2 + '';
      let rate = 1;
      let rate1 = 1;
      let rate2 = 1;
      if (val1.indexOf('.') < 0) {
        rate1 = 0;
      } else {
        rate1 = val1.length - val1.indexOf('.') - 1;
      }
      if (val2.indexOf('.') < 0) {
        rate2 = 0;
      } else {
        rate2 = val2.length - val2.indexOf('.') - 1;
      }
      rate = rate2;
      val2 = val2.replace('.', '');
      val1 = val1.replace('.', '');
      if (rate1 > rate2) {
        rate = rate1;
        for (let i = 0; i < rate1 - rate2; i++) {
          val2 = val2 + '0'
        }
      } else {
        for (let i = 0; i < rate2 - rate1; i++) {
          val1 = val1 + '0';
        }
      }
      let rateNum = Math.pow(10, rate);
      if (sign === '-') {
        return (Number(val1) - Number(val2)) / rateNum
      }
      if (sign === '+') {
        return (Number(val1) + Number(val2)) / rateNum
      }
      if (sign === '*') {
        return (Number(val1) * Number(val2)) / (rateNum * rateNum)
      }
      if (sign === '/') { // 默认保留4位
        let num = 0;
        if (Number(val1) - 0 !== 0 && Number(val2) - 0 !== 0) {
          num = (Number(val1) / Number(val2)) + '';
          if (num.split('.').length > 0) {
            if (num[1].length > 4) {
              num = num.toFixed(4);
            }
          }
        }
        return num;
      }
      return null;
    },
    closeDialog () {
      this.showFlag = false
      if (this.editFlag === 'add') {
        this.$refs.forecastTable.setCurrentRow(this.forecastRow, false);
        this.forecastRow = {}
      } else {
        this.$refs.actualTable.setCurrentRow(this.actualRow, false);
        this.rules['grossWeight'].required = true
        this.rules['tareWeight'].required = true
        this.rules['netWeight'].required = true
        this.actualRow = {}
      }
      this.formObj = { ...this.formObjCache }
      // this.$refs.forecastTable.clearSelection()
    },
    // 时间改变回调
    dateChange (val, timeName, formName) {
      if (val) {
        if (formName === 'search') {
          this.search[timeName] = formatDate(val, 'yyyy-MM-dd HH:mm:ss')
        } else {
          this.actualSearchForm[timeName] = formatDate(val, 'yyyy-MM-dd HH:mm:ss')
        }
      }
    },
    showEditDialog (flag, row) {
      if (flag === 'single') {
        this.actualRow = { ...row }
      } else {
        if (this.batchList.length === 0) {
          return this.$message.error('请先勾选要进行批量修改的计量数据')
        }
        this.actualRow = { ...this.batchList[0] }
      }
      this.dialogTitle = '单包计量修改'
      this.editFlag = 'edit'
      this.wgtFlag = flag
      this.formObj = { ...this.actualRow }
      this.showFlag = true
    },
    pageSizeChange (newSize) {
      this.page.pageSize = newSize
      this.searchDatas()
    },
    pageCurrentChange (newIndex) {
      this.page.pageNum = newIndex
      this.searchDatas(2)
    },
    pageSizeChange1 (newSize) {
      this.page1.pageSize = newSize
      this.searchActualData()
    },
    pageCurrentChange1 (newIndex) {
      this.page1.pageNum = newIndex
      this.searchActualData(2)
    }
  },
  watch: {
    'formObj.grossWeight': {
      handler: function (val) {
        let reg = /^(-?\d+)(\.\d+)?$/
        if (!reg.test(val - 0)) {
          this.formObj.grossWeight = 0
          return this.$message.error('毛重需要为数值')
        }
        if (val - 0 !== 0) {
          this.formObj.netWeight = this.floatComputed(this.formObj.grossWeight - 0, this.formObj.tareWeight - 0, '-')
        }
      }
    },
    'formObj.tareWeight': {
      handler: function (val) {
        let reg = /^(-?\d+)(\.\d+)?$/
        if (!reg.test(val - 0)) {
          this.formObj.tareWeight = 0
          return this.$message.error('皮重需要为数值')
        }
        if (val - 0 !== 0) {
          this.formObj.netWeight = this.floatComputed(this.formObj.grossWeight - 0, this.formObj.tareWeight - 0, '-')
        }
      }
    },
    unitFlag (val) {
      switch (val) {
        case 'kg':
          // 分别判断三个值是否大于1000
          // 小于1000乘以1000
          if (this.formObj.grossWeight && this.formObj.grossWeight - 0 !== 0 && this.formObj.grossWeight - 0 < 1000) {
            this.formObj.grossWeight = this.floatComputed(this.formObj.grossWeight, 1000, '*')
          }
          if (this.formObj.tareWeight && this.formObj.tareWeight - 0 !== 0 && this.formObj.tareWeight - 0 < 1000) {
            this.formObj.tareWeight = this.floatComputed(this.formObj.tareWeight, 1000, '*')
          }
          if (this.formObj.netWeight && this.formObj.netWeight - 0 !== 0 && this.formObj.netWeight - 0 < 1000) {
            this.formObj.netWeight = this.floatComputed(this.formObj.netWeight, 1000, '*')
          }
          break;
        case 't':
          // 分别判断三个值是否大于1000
          // 大于1000除以1000
          if (this.formObj.grossWeight && this.formObj.grossWeight - 0 !== 0 && this.formObj.grossWeight - 0 > 1000) {
            this.formObj.grossWeight = this.floatComputed(this.formObj.grossWeight, 1000, '/')
          }
          if (this.formObj.tareWeight && this.formObj.tareWeight - 0 !== 0 && this.formObj.tareWeight - 0 > 1000) {
            this.formObj.tareWeight = this.floatComputed(this.formObj.tareWeight, 1000, '/')
          }
          if (this.formObj.netWeight && this.formObj.netWeight - 0 !== 0 && this.formObj.netWeight - 0 > 1000) {
            this.formObj.netWeight = this.floatComputed(this.formObj.netWeight, 1000, '/')
          }
          break;
      }
    }
  }
}
</script>
<style>
.measure-self-picker .el-input__inner {
  padding: 0px 0px 0px 4px !important;
}

.measure-self-picker .el-icon-time {
  display: none;
}

.weight-input-wrap.el-dialog .el-dialog__header {
  background-color: #409eff;
  border-radius: 4px 4px 0 0;
  color: #fff;
  padding: 14px;
}
</style>