<template>
  <div class="descriptions-edit">
    <el-descriptions :column="4" border :labelStyle="{width: '100px'}" :contentStyle="{minWidth:'100px'}">
      <template slot="title"><span class="vehicle-title">订单信息</span></template>
        <el-descriptions-item>
          <template slot="label">订单</template>
          <div v-if="editType !== TransPlanEditType.add">{{ order.orderNo }}</div>
          <OrderInput v-else width="100%" orderType="1" placeholder="请选择订单" :value="order.orderNo" :label="order.orderNo"
            @change="handleOrderChange"></OrderInput>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">状态</template>
          <el-tag :type="order.status == '1' ? 'success' : ''">{{ order.status == 1 ? '已完成' : '未完成'
            }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="order.sourceNo">
          <template slot="label">关联托运订单</template>
          {{ order.sourceNo }}
        </el-descriptions-item>
        <el-descriptions-item v-if="order.cargoInfo">
          <template slot="label">货物名称</template>
          {{ order.cargoInfo }}
        </el-descriptions-item>
        <el-descriptions-item v-if="order.custName">
          <template slot="label">承运企业</template>
          {{ order.custName }}
        </el-descriptions-item>
        <el-descriptions-item v-if="order.freightRates">
          <template slot="label">承运价</template>
          {{ order.freightRates }}
        </el-descriptions-item>
        <el-descriptions-item v-if="order.currency">
          <template slot="label">币种</template>
          <dict-tag :options="dict.type.sys_curr_type" :value="order.currency" />
        </el-descriptions-item>
        <el-descriptions-item v-if="order.orderDate">
          <template slot="label">订单时间</template>
            {{order.orderDate}}
        </el-descriptions-item>
        <el-descriptions-item v-if="order.remark">
          <template slot="label">备注</template>
          {{ order.remark }}
        </el-descriptions-item>
      </el-descriptions>
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" :show-message="false" v-enterboard>
      <div class="vehicle-header">
        <span class="vehicle-title">运输计划</span>
        <el-button v-if="!readonly && editType === TransPlanEditType.add" :disabled="!order.orderNo" icon="el-icon-plus" type="primary" size="small" plain
          @click="handleAuto">自动生成计划</el-button>
        <el-button v-if="!readonly && editType === TransPlanEditType.add" :disabled="!order.orderNo" icon="el-icon-upload" type="success" size="small" plain
          @click="handleImport">导入运输计划</el-button>
        <VehicleInput v-if="!readonly && order.orderNo && editType === TransPlanEditType.add" :custId="order.custId" multiple @confirm="handleVehicleConfirm">
          <el-button icon="el-icon-truck" type="primary" size="small" plain>选择车辆添加计划</el-button>
        </VehicleInput>
        <el-tooltip v-else-if="!readonly && editType === TransPlanEditType.add" class="item" effect="dark" content="请先选择订单" placement="top">
          <el-button disabled icon="el-icon-truck" type="primary" size="small" plain>选择车辆添加计划</el-button>
        </el-tooltip>

        <el-tooltip v-if="!readonly && editType === TransPlanEditType.add" class="item" effect="dark" :disabled="!!order.orderNo" content="请先选择订单" placement="top">
          <el-button icon="el-icon-plus" type="info" size="small" plain :disabled="!order.orderNo"
          @click="addVehicle">添加运输计划</el-button>
        </el-tooltip>
        <el-popconfirm v-if="editType === TransPlanEditType.add" title="确定删除勾选中的运输计划吗？" @confirm="deleteVehicle">
          <el-button slot="reference" v-if="!readonly" icon="el-icon-delete" :disabled="selectVehicles.length === 0"
            type="danger" size="small" plain>删除勾选计划</el-button>
        </el-popconfirm>
      </div>
      <el-table v-if="!loading" class="cargo-table" highlight-current-row ref="table" max-height="500px"
        :data="form.lsTrans" @expand-change="vehicleExpandChange" @selection-change="vehicleSelectionChange"
        border stripe>
        <el-table-column label="展/收" width="30" type="expand">
          <template slot-scope="scope">
            <div class="cargo-input">
              <div class="cargo-header" v-if="!readonly">
                <el-button icon="el-icon-plus" type="info" size="mini" plain
                  @click="addCargo(scope.row)">添加货物</el-button>
                <el-popconfirm title="确定删除勾选中的货物吗？" @confirm="deleteCargo(scope.row, scope.$index)">
                  <el-button slot="reference" icon="el-icon-delete" :disabled="selectCargos.length === 0"
                    type="danger" size="mini" plain>删除勾选货物</el-button>
                </el-popconfirm>
              </div>
              <el-table class="cargo-table" highlight-current-row :ref="'subtable' + scope.$index" :data="scope.row.lsCargos"
               @selection-change="cargoSelectionChange" border stripe :summary-method="getCargoSummaries" show-summary>
              <el-table-column v-if="!readonly" type="selection" width="30" align="center" />
              <el-table-column type="index" :index="(index) => `(${index + 1})`" width="30" align="center" />
              <el-table-column label="运输货物" prop="cargoName" align="center" min-width="100">
                <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.cargoName`"
                    :value="subscope.row.cargoName" :readonly="readonly" :rules="rules.cargoName">
                    <!-- <el-input v-model="subscope.row.cargoName" placeholder="请输入运输货物" /> -->
                    <CarriageCargoInput :label="subscope.row.cargoName" :orderId="order.id" @change="cargoChange($event, subscope.row)" />
                  </MyFormItem>
                </template>
              </el-table-column>
              <el-table-column label="装货车重(吨)" prop="pierCarWeight" align="center" min-width="100">
                <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.pierCarWeight`"
                    :readonly="readonly" :rules="rules.pierCarWeight">
                    <el-input v-model="subscope.row.pierCarWeight" placeholder="请输入装货车重(吨)" @input="changeRealLoadWtOrRealTransWt(subscope.row)"/>
                  </MyFormItem>
                </template>
              </el-table-column>
              <el-table-column label="装货毛重(吨)" prop="grossWeightLoading" align="center" min-width="100">
                <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.grossWeightLoading`"
                    :readonly="readonly" :rules="rules.grossWeightLoading">
                    <el-input v-model="subscope.row.grossWeightLoading" placeholder="请输入装货毛重(吨)" @input="changeRealLoadWtOrRealTransWt(subscope.row)"/>
                  </MyFormItem>
                </template>
              </el-table-column>
              <el-table-column label="装货净重(吨)" prop="realLoadWt" align="center" min-width="100">
                <!-- <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.realLoadWt`"
                    :readonly="readonly" :rules="rules.realLoadWt">
                    <el-input v-model="subscope.row.realLoadWt" placeholder="请输入装货净重(吨)" />
                  </MyFormItem>
                </template> -->
              </el-table-column>
              <el-table-column label="卸货车重(吨)" prop="plantCarWeight" align="center" min-width="100">
                <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.plantCarWeight`"
                    :readonly="readonly" :rules="rules.plantCarWeight">
                    <el-input v-model="subscope.row.plantCarWeight" placeholder="请输入卸货车重(吨)" @input="changeRealLoadWtOrRealTransWt(subscope.row)"/>
                  </MyFormItem>
                </template>
              </el-table-column>
              <el-table-column label="卸货毛重(吨)" prop="grossWeightUnloading" align="center" min-width="100">
                <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.grossWeightUnloading`"
                    :readonly="readonly" :rules="rules.grossWeightUnloading">
                    <el-input v-model="subscope.row.grossWeightUnloading" placeholder="请输入卸货毛重(吨)" @input="changeRealLoadWtOrRealTransWt(subscope.row)"/>
                  </MyFormItem>
                </template>
              </el-table-column>
              <el-table-column label="卸货净重(吨)" prop="realTransWt" align="center" min-width="100">
                <!-- <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.realTransWt`"
                    :readonly="readonly" :rules="rules.realTransWt">
                    <el-input v-model="subscope.row.realTransWt" placeholder="请输入卸货净重(吨)" />
                  </MyFormItem>
                </template> -->
              </el-table-column>
              <el-table-column label="磅差(吨)" prop="poundDifference" align="center" min-width="100" />
              <el-table-column label="录入时间" prop="inputDate" align="center" min-width="100">
                <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.inputDate`" :value="subscope.row.inputDate" :readonly="readonly">
                    <el-date-picker class="el-date-picker" v-model="subscope.row.inputDate" value-format="yyyy-MM-dd" type="date" placeholder="请选择录入时间" prefix-icon="n" :clearable="false">
                    </el-date-picker>
                  </MyFormItem>
                </template>
              </el-table-column>
              <el-table-column label="计划装货量(吨)" prop="loadWt" align="center" min-width="100">
                <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.loadWt`"
                    :value="subscope.row.loadWt" :readonly="readonly" :rules="rules.loadWt">
                    <el-input v-model="subscope.row.loadWt" placeholder="请输入计划装货量(吨)" />
                  </MyFormItem>
                </template>
              </el-table-column>
              <el-table-column label="计划发货时间" prop="departTime" align="center" min-width="136">
                <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.departTime`"
                    :readonly="readonly" :rules="rules.departTime">
                    <el-date-picker
                      class="el-date-picker"
                      v-model="subscope.row.departTime"
                      type="datetime" :clearable="false"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      prefix-icon="n"
                      placeholder="选择计划发货时间">
                    </el-date-picker>
                  </MyFormItem>
                </template>
              </el-table-column>
              <el-table-column label="计划到货时间" prop="arrivalTime" align="center" min-width="136">
                <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.arrivalTime`"
                    :readonly="readonly" :rules="rules.arrivalTime">
                    <el-date-picker
                      class="el-date-picker"
                      v-model="subscope.row.arrivalTime"
                      type="datetime" :clearable="false"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      prefix-icon="n"
                      placeholder="选择到货时间">
                    </el-date-picker>
                  </MyFormItem>
                </template>
              </el-table-column>
              <el-table-column label="实际发货时间" prop="realDepartTime" align="center" min-width="136">
                <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.realDepartTime`"
                    :readonly="readonly" :rules="rules.realDepartTime">
                    <el-date-picker
                      class="el-date-picker"
                      v-model="subscope.row.realDepartTime"
                      type="datetime" :clearable="false"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      prefix-icon="n"
                      placeholder="选择实际发货时间">
                    </el-date-picker>
                  </MyFormItem>
                </template>
              </el-table-column>
              <el-table-column label="实际到货时间" prop="realArrivalTime" align="center" min-width="136">
                <template slot-scope="subscope">
                  <MyFormItem :prop="`lsTrans.${scope.$index}.lsCargos.${subscope.$index}.realArrivalTime`"
                    :readonly="readonly" :rules="rules.realArrivalTime">
                    <el-date-picker
                      class="el-date-picker"
                      v-model="subscope.row.realArrivalTime"
                      type="datetime" :clearable="false"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      prefix-icon="n"
                      placeholder="选择实际到货时间">
                    </el-date-picker>
                  </MyFormItem>
                </template>
              </el-table-column>
            </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="!readonly && editType === TransPlanEditType.add" type="selection" width="30" align="center" />
        <el-table-column type="index" width="30" align="center" />
        <el-table-column label="车牌号" prop="vehicleNumber" align="center">
          <template slot-scope="scope">
            <MyFormItem :prop="'lsTrans.' + scope.$index + '.vehicleNumber'" :value="scope.row.vehicleNumber"
              :readonly="readonly" :rules="rules.vehicleNumber">
              <el-input v-model="scope.row.vehicleNumber" placeholder="请输入车牌号码" />
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="品牌型号" prop="vehicleBrand" align="center">
          <template slot-scope="scope">
            <MyFormItem :prop="'lsTrans.' + scope.$index + '.vehicleBrand'" :value="scope.row.vehicleBrand" :readonly="readonly"
              :rules="rules.vehicleBrand">
              <el-input v-model="scope.row.vehicleBrand" placeholder="请输入品牌型号" />
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="载重(吨)" prop="vehicleLoad" align="center">
          <template slot-scope="scope">
            <MyFormItem :prop="'lsTrans.' + scope.$index + '.vehicleLoad'" :value="scope.row.vehicleLoad" :readonly="readonly"
              :rules="rules.vehicleLoad">
              <el-input v-model="scope.row.vehicleLoad" placeholder="请输入载重(吨)" />
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="装载体积(m³)" prop="vehicleVol" align="center">
          <template slot-scope="scope">
            <MyFormItem :prop="'lsTrans.' + scope.$index + '.vehicleVol'" :value="scope.row.vehicleVol" :readonly="readonly"
              :rules="rules.vehicleVol">
              <el-input v-model="scope.row.vehicleVol" placeholder="请输入装载体积(m³)" />
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="司机" prop="driverName" align="center">
          <template slot-scope="scope">
            <MyFormItem :prop="'lsTrans.' + scope.$index + '.driverName'" :value="scope.row.driverName" :readonly="readonly"
              :rules="rules.driverName">
              <DriverInput type="input" width="100%" :custId="form.custId" :value="scope.row.driverId" :clearable="false" :readonly="readonly" :label="scope.row.driverName" placeholder="请输入司机" @change="handleDriverChange($event, scope.row)" />
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" prop="driverMobile" align="center">
          <template slot-scope="scope">
            <MyFormItem :prop="'lsTrans.' + scope.$index + '.driverMobile'" :value="scope.row.driverMobile" :readonly="readonly"
              :rules="rules.driverMobile">
              <el-input v-model="scope.row.driverMobile" placeholder="请输入联系方式" />
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="录入时间" prop="inputDate" align="center" min-width="100">
          <template slot-scope="scope">
            <MyFormItem :prop="'lsTrans.' + scope.$index + '.inputDate'" :value="scope.row.inputDate" :readonly="readonly">
              <el-date-picker class="el-date-picker" v-model="scope.row.inputDate" value-format="yyyy-MM-dd" type="date" placeholder="请选择录入时间" prefix-icon="n" :clearable="false">
              </el-date-picker>
            </MyFormItem>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="trans-footer">
      <el-button type="primary" @click="submitForm()">保 存</el-button>
      <el-button @click="$emit('cancel')">取 消</el-button>
    </div>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&orderId=' + upload.orderId" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的运输计划数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog v-dialogDrag custom-class="dialog-edit" title="自动计算运输计划" :visible.sync="openAuto" width="50%" append-to-body :close-on-click-modal="false">
      <TransPlanAuto v-if="openAuto" :order="order" @success="calcAutoSuccess" @cancel="openAuto = false"></TransPlanAuto>
    </el-dialog>
  </div>
</template>

<script>
import { getOrder, addOrder, updateOrder } from "@/api/tm/order";
import { saveTrans, delTrans, addTrans, updateTrans } from "@/api/order/trans";
import DriverInput from "@/views/tm/components/DriverInput";
import VehicleInput from '@/views/tm/components/VehicleInput';
import OrderInput from '@/views/tm/components/OrderInput';
import CarriageCargoInput from '@/views/tm/components/CarriageCargoInput';
import { getToken } from "@/utils/auth";
import TransPlanAuto from "./TransPlanAuto";
import { formatDateToDataStr } from '@/utils';

const TransPlanEditType = {
  add: 'add',
  update: 'update',
};

export default {
  name: 'TransPlanEdit',
  components: {
    DriverInput,
    VehicleInput,
    OrderInput,
    TransPlanAuto,
    CarriageCargoInput
  },
  dicts: ['sys_curr_type'],
  props: {
    trans: [Array],
    readonly: Boolean,
    editType: {
      type: String,
      validator: (value) => {
        return Object.values(TransPlanEditType).includes(value);
      },
    },
  },
  computed: {
    TransPlanEditType() {
      return TransPlanEditType;
    }
  },
  data() {
    return {
      loading: false,
      order: {},
      form: this.defaultForm(),
      rules: {
        custId: [
          { required: true, message: "承运企业不能为空", trigger: "change" }
        ],
        cargoName: [
          { required: true, message: "货物名称不能为空", trigger: "blur" }
        ],
        cargoInfo: [
          { required: true, message: "货物名称不能为空", trigger: "blur" }
        ],
        orderNo: [
          { required: true, message: "订单号不能为空", trigger: "change" }
        ],
        // loadWt: [
        //   { required: true, message: "预计装货量不能为空", trigger: "blur" }
        // ],
        vehicleNumber: [
          { required: true, message: "车辆不能为空", trigger: "change" }
        ],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/trans/cargo/importData",
        orderId: 0,
      },
      openAuto: false,
      // 选择的车辆
      selectVehicles: [],
      // 选择的货物
      selectCargos: [],
    }
  },
  created() {
    if (this.editType !== TransPlanEditType.add &&  this.trans && this.trans.length > 0) {
      const tranData = {};
      this.trans.forEach(item => {
        const order = item.order || {};
        if (!tranData[`${order.id}${order.orderNo}`]) {
          tranData[`${order.id}${order.orderNo}`] = [];
        }
        tranData[`${order.id}${order.orderNo}`].push(item);
      });
      let trans = [];
      Object.values(tranData).forEach(item => {
        if (item.length > trans.length) {
          trans = item;
        }
      });
      this.form = this.defaultForm({
        lsTrans: trans,
      });
      // this.getOrder(trans[0].orderId);
      this.order = trans[0].order || {};
    }

  },
  methods: {
    handleOrderChange(orders) {
      this.order = orders[0] || {};

      this.getOrder(this.order.id);
      this.upload.orderId = this.order.id;
    },
    // 自动计算计划成功
    calcAutoSuccess(list) {
      this.openAuto = false;
      this.form = this.defaultVehicleForm({
        ...this.form,
        lsTrans: list,
      });
    },
    // 车辆选择确定
    handleVehicleConfirm(vehicles) {
      if (vehicles) {
        vehicles.forEach(item => {
          this.form.lsTrans.push(this.defaultVehicleForm({
            custId: item.custId,
            custName: item.custName,
            vehicleNumber: item.vehicleNumber,
            vehicleBrand: item.vehicleBrand,
            vehicleLoad: item.vehicleLoad,
            vehicleVol: item.vehicleVol,
            driverId: item.id,
            driverName: item.driverName,
            driverMobile: item.driverMobile,
          }));
        });
      }
    },
    // 添加车辆
    addVehicle() {
      this.form.lsTrans.push(this.defaultVehicleForm());
    },
    // 删除车辆
    deleteVehicle() {
      this.form.lsTrans = this.form.lsTrans.filter(item => {
        return this.selectVehicles.indexOf(item) === -1;
      });
      this.$refs.table.clearSelection();
    },
    // 添加货物
    addCargo(row) {
      if (!row.lsCargos) {
        row.lsCargos = [];
      }
      row.lsCargos.push(this.defaultCargoForm());
      this.$refs.table.doLayout();
    },
    // 删除货物
    deleteCargo(row, index) {
      row.lsCargos = row.lsCargos.filter(item => {
        return this.selectCargos.indexOf(item) === -1;
      });
      if (this.$refs['subtable' + index]) {
        this.$refs['subtable' + index].clearSelection();
      }
    },
    // 修改司机
    handleDriverChange(drivers, row) {
      const driver = drivers.length > 0 ? drivers[0] : {};
      row.driverId = driver.driverId;
      row.driverName = driver.driverName;
    },
    // 车辆选择
    vehicleSelectionChange(sel) {
      this.selectVehicles = sel || [];
    },
    cargoChange(cargos, row) {
      const cargo = cargos[0] || {};
      row.cargoName = cargo.cargoInfo;
      row.cargoId = cargo.id;
    },
    // 货物选择
    cargoSelectionChange(sel) {
      this.selectCargos = sel || [];
    },
    // 货物合记
    getCargoSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const property = column.property;
        if (!['loadWt', 'grossWeightLoading', 'realLoadWt', 'grossWeightUnloading', 'realTransWt', 'poundDifference'].includes(property)) {
          return '';
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 吨';
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },
    // 装货净重和卸货净重改变
    changeRealLoadWtOrRealTransWt(row) {
      
      let realLoadWt = row.grossWeightLoading - row.pierCarWeight;
      if (isNaN(realLoadWt)) {
        realLoadWt = 0;
      }
      row.realLoadWt = realLoadWt.toFixed(4).replace(/\.?0*$/, '');

      let realTransWt = row.grossWeightUnloading - row.plantCarWeight;
      if (isNaN(realTransWt)) {
        realTransWt = 0;
      }
      row.realTransWt = realTransWt.toFixed(4).replace(/\.?0*$/, '');

      let poundDifference = row.realLoadWt - row.realTransWt;
      if (isNaN(poundDifference)) {
        poundDifference = 0;
      }
      row.poundDifference = poundDifference.toFixed(4).replace(/\.?0*$/, '');
    },
    // 展开行变化
    vehicleExpandChange(row, expandedRows) {
      if (expandedRows.some(item => item === row)) {
        const exp = expandedRows.filter(item => item !== row);
        // 关闭其他展开行
        exp.forEach(item => {
          this.$refs.table.toggleRowExpansion(item, false);
        });
      }

    },
    // 获取订单
    getOrder(id) {
      if (!id) return;
      this.loading = true;
      getOrder(id).then((res) => {
        this.loading = false;
        this.order = res.data || {};
      }).catch((err) => {
        this.loading = false;
      });
    },
    // 默认表单
    defaultForm(data) {
      if (data) {
        if (!data.lsTrans) {
          data.lsTrans = [];
        }

        data.lsTrans = data.lsTrans.map(item => {
          return this.defaultVehicleForm(item);
        });
      }

      return {
        lsTrans: [],
        ...data,
      };
    },
    // 车辆默认表单
    defaultVehicleForm(data) {
      if (data && !data.lsCargos) {

        if (!data.lsCargos) {
          data.lsCargos = [];
        }
        data.lsCargos = data.lsCargos.map(item => {
          return this.defaultCargoForm(item);
        });
      }

      return {
        vehicleNumber: '',
        vehicleBrand: '',
        vehicleLoad: '',
        vehicleVol: '',
        driverName: '',
        driverMobile: '',
        inputDate: data && data.id ? '' : formatDateToDataStr(),
        remark: '',
        lsCargos: [],
        ...data,
      };
    },
    // 货物默认表单
    defaultCargoForm(data) {
      return {
        cargoName: '',
        loadWt: '',
        pierCarWeight: '',//装货车重
        plantCarWeight: '',//卸货车重
        grossWeightLoading: '',
        grossWeightUnloading: '',
        poundDifference: '',
        realLoadWt: '',
        realTransWt: '',
        inputDate: data && data.id ? '' : formatDateToDataStr(),
        departTime: '',
        freightRates: '',
        arrivalTime: '',
        realDepartTime: '',
        realArrivalTime: '',
        remark: '',
        ...data,
      };
    },
    // 打开自动生成计划
    handleAuto() {
      this.openAuto = true;
    },
    // 提交表单
    submitForm(type) {
      if (!this.order.id) {
        this.$modal.msgWarning("请先选择订单");
        return;
      }
      const params = {
        orderId: this.order.id,
        orderNo: this.order.orderNo,
        ...this.form
      }

      this.$refs.form.validate((valid, rules) => {
        if (!valid) {
          this.$modal.formWarning(rules);
          return;
        }
        if (this.form.lsTrans.length === 0) {
          this.$modal.msgWarning("请添加运输车辆计划");
          return;
        }
        const isAdd = this.editType === TransPlanEditType.add;
        saveTrans(params).then(response => {
          this.$modal.msgSuccess(isAdd ? "新增成功":"修改成功");
          this.$emit('saved', isAdd);
        });
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "车辆运输计划导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      const fileName = `车辆运输计划模板_${new Date().getTime()}.xlsx`;
      this.download(`trans/cargo/importTemplate`, {}, fileName);
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.data) {
        const list = response.data.lsTrans || [];
        this.form = this.defaultVehicleForm({
          ...this.form,
          lsTrans: list,
        });
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
}
</script>

<style scoped lang="scss">
.descriptions-edit {
  height: calc(100vh - 210px);
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0 15px 80px;
  ::v-deep .el-descriptions-item__label.is-bordered-label {
    padding: 5px !important;
    width: 100px;
  }

  .trans-footer {
    position: absolute;
    bottom: 5px;
    right: 30px;
    z-index: 100;
  }
}
.go-and-come {
  display: flex;
  align-items: center;

  .el-descriptions {
    flex: 1;
  }
}

.vehicle-header {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin: 10px 0;

  .el-button {
    margin-left: 10px;
  }
}
.vehicle-title {
    font-size: 17px;
    font-weight: 500;
    margin-right: 20px;
    color: #606266;
  }

.cargo-table {
  ::v-deep .el-table__cell {
    padding: 0px !important;

    .cell {
      padding: 2px !important;
      line-height: 18px;
    }

    .el-checkbox__label {
      padding-left: 4px;
    }
  }
  ::v-deep .el-input__inner {
    padding: 0 !important;
    text-align: center;
  }
}
.cargo-input {
  background-color: rgb(225, 243, 216);
  padding: 10px 0 20px 30px;
  .el-button {
    margin-right: 10px;
    margin-bottom: 5px;
  }
}
</style>
