<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules"  label-width="90px">
      <el-row>
        <el-col :span="8">
          <el-form-item  ref="form" label="单据编号" prop="billNumber">
            <bill-number-input ref="billInput" v-model="form.billNumber" type="CK" :disabled="!!form.id"></bill-number-input>
<!--            <el-input v-model="form.billNumber" placeholder="请输入单据编号" />-->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item ref="form" label="单据时间" prop="billDate">
            <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-col>
        <el-col :span="8">
          <el-form-item  ref="form" label="货主" prop="custId">
            <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-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="出库类型" prop="outType">
            <el-select v-model="form.outType" placeholder="请选择出库类型" disabled  clearable style="width: 100%">
              <el-option v-for="dict in dict.type.sys_out_type" :key="dict.value"
                         :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
<!--        <el-col :span="8">-->
<!--          <el-form-item label="船舶名称" prop="vesselName">-->
<!--            <el-select v-model="form.vesselId" filterable placeholder="请输入船舶名称" style="width: 100%" clearable-->
<!--                       @change="setVesselDetail">-->
<!--              <el-option v-for="item in vesselList" :key="item.id" :label="item.vesselName" :value="item.id">-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="8">-->
<!--          <el-form-item label="航次号" prop="voyageNo">-->
<!--            <el-input v-model="form.voyageNo" placeholder="请输入航次号" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
      </el-row>
    </el-form>
    <div class="stock-content">
      <div v-if="!tableReadonly">
        <el-button type="primary" plain @click="addStockOut">添加出库单</el-button>
        <el-button type="danger" plain @click="deleteStocks">删除选中项</el-button>

      </div>
      <el-form ref="listForm" style="flex: 1;margin-top: 10px;" :model="form" v-enterboard>
        <el-table v-if="!loading" highlight-current-row ref="table" style="height: 100%;" height="62vh" :data="form.ckBillCargos" :summary-method="getSummaries"
          show-summary @selection-change="selectionChange" border stripe>
          <el-table-column v-bind="tableIndexAttrs" align="center" />
          <el-table-column type="expand" label="更多">
            <template slot-scope="scope">
              <el-descriptions class="desc-table" size="mini" :column="5" border>
                <el-descriptions-item label="HS编号">{{ scope.row.hsCode }}</el-descriptions-item>
                <el-descriptions-item label="自然序号">{{ scope.row.cargoNumber }}</el-descriptions-item>
                <el-descriptions-item label="商品料号">{{ scope.row.itemNumber }}</el-descriptions-item>
                <el-descriptions-item label="电子账册项号"> <el-input v-model="scope.row.bookNumber" placeholder="电子账册项号" /></el-descriptions-item>
                <el-descriptions-item label="报关单号"><el-input v-model="scope.row.customsNo" placeholder="报关单号" /></el-descriptions-item>
                <el-descriptions-item label="核注清单号"><el-input v-model="scope.row.listNumber" placeholder="核注清单号" /></el-descriptions-item>
                <el-descriptions-item label="有效期至"><el-date-picker v-model="scope.row.expiryDate" placeholder="有效期至" type="date" value-format="yyyy-MM-dd " /></el-descriptions-item>
                <el-descriptions-item label="规格类型品质">{{ scope.row.cargoSpec }}</el-descriptions-item>
                <el-descriptions-item label="原产国"><dict-tag :options="dict.type.sys_origin_country" :value="scope.row.originCountry"></dict-tag></el-descriptions-item>
                <el-descriptions-item label="船舶名称">{{ scope.row.vesselName }}</el-descriptions-item>
                <el-descriptions-item label="航次号">{{ scope.row.voyageNo }}</el-descriptions-item>
                <el-descriptions-item label="备案号">{{ scope.row.gdsSeqno }}</el-descriptions-item>
              </el-descriptions>
            </template>
          </el-table-column>

          <el-table-column label="单据编号" prop="billNumber">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.outBillNumber }}</div>
            </template>
          </el-table-column>
          <el-table-column label="货物" prop="cargoName">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.cargoName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="库场仓位" prop="stockName">
            <template slot-scope="scope">
              <div class="nomal-text"><WarehouseName :stockCode="scope.row.stockCode"/>-{{ scope.row.stockName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="件数" prop="cargoNum">
            <template slot-scope="scope">
              <el-form-item prop="cargoNum" class="margin-none">
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoNum }}</div>
                <el-input-number style="width: 100%" controls-position="right" v-else v-model="scope.row.cargoNum"
                  :min="0" :max="getMaxData(scope.row).cargoNum" :precision="2" placeholder="输入件数" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="重量" prop="cargoWt">
            <template slot-scope="scope">
              <el-form-item class="margin-none" :prop="'ckBillCargos.' + scope.$index + '.cargoWt'" :rules="rules.cargoWt">
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoWt }}</div>
                <el-input-number style="width: 100%" controls-position="right" v-else v-model="scope.row.cargoWt" :min="0"
                                 :precision="2" :max="getMaxData(scope.row).cargoWt" placeholder="输入重量" :disabled="true" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="体积" prop="cargoVol">
            <template slot-scope="scope">
              <el-form-item prop="cargoVol" class="margin-none">
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.cargoVol }}</div>
                <el-input-number style="width: 100%" controls-position="right" v-else v-model="scope.row.cargoVol"
                  :min="0" :precision="2" :max="getMaxData(scope.row).cargoVol" placeholder="输入体积" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="unitPrice">
            <template slot-scope="scope">
              <el-form-item prop="unitPrice" class="margin-none">
                <div v-if="tableReadonly" class="nomal-text">{{ scope.row.unitPrice }}</div>
                <el-input-number style="width: 100%" controls-position="right" v-else v-model="scope.row.unitPrice"
                                 :min="0" :precision="4"  placeholder="输入单价" />

              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="价值" prop="cargoValue">
            <template slot-scope="scope">
              <el-form-item prop="cargoValue" class="margin-none">
                <div   v-if="tableReadonly"  class="nomal-text">{{ scope.row.cargoValue }}</div>
                <el-input-number style="width: 100%" controls-position="right" v-else v-model="scope.row.cargoValue"
                                 :min="0" :precision="4" placeholder="输入价值" />
              </el-form-item>
            </template>


          </el-table-column>
          <el-table-column  label="操作">
            <template slot-scope="scope">
                <el-button type="info"  v-if="!tableReadonly" plain @click="handleImport(scope.row.outBillNumber,getMaxData(scope.row).cargoWt,scope.$index,form.billNumber)">导入</el-button>
              <el-button type="info" plain @click="carBillList(scope.row.outBillNumber,form.billNumber,scope.$index)">详情</el-button>

            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="stock-btns">
      <el-button v-if="!readonly" type="primary" plain
        style="margin-right: 20px;" @click="confirm">{{ form.billStatus == 1 ? '单据撤销' : '单据确认' }}</el-button>
      <el-button @click="cancel(!readonly)">取消</el-button>
      <el-button v-if="!readonly && form.billStatus != 1" type="primary" @click="save(false)">保存</el-button>
    </div>
    <el-dialog title="选择出库货物" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" destroy-on-close>

      <StockChoose style="height: 60vh;" :cust-id="form.custId" :disable-items="form.ckBillCargos" :search-keyword="searchKeyword" @confirm="chooseStock" @cancel="open = false" @updateList="updateStockList"></StockChoose>
    </el-dialog>

    <el-dialog :title="车辆批量出库" :visible.sync="carList.open" width="1500px" append-to-body>





        <el-table ref="table" style="flex: 1;" height="70vh" :data="billCarList" @select="select" @select-all="selectAll"
                  @selection-change="handleSelectionChange" highlight-current-row border stripe>


        <el-table-column type="selection" width="55" align="center" :selectable="selectable" />

          <el-table-column label="业务类型" prop="businessType">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.businessType }}</div>
            </template>
          </el-table-column>
          <el-table-column label="车辆类型" prop="carType">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.carType }}</div>
            </template>
          </el-table-column>
          <el-table-column label="船舶名称" prop="vesselName">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.vesselName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="泊位名称" prop="berthName">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.berthName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="入闸时间" prop="entryTime">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.entryTime }}</div>
            </template>
          </el-table-column>
          <el-table-column label="入闸车重" prop="entryWt">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.entryWt }}</div>
            </template>
          </el-table-column>
          <el-table-column label="出闸时间" prop="exitTime">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.exitTime }}</div>
            </template>
          </el-table-column>
          <el-table-column label="出闸车重" prop="exitWt">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.exitWt }}</div>
            </template>
          </el-table-column>
          <el-table-column label="作业确认" prop="jobConfirm">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.jobConfirm }}</div>
            </template>
          </el-table-column>
          <el-table-column label="作业数量" prop="jobNum">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.jobNum }}</div>
            </template>
          </el-table-column>
          <el-table-column label="作业重量" prop="jobWt">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.jobWt }}</div>
            </template>
          </el-table-column>
          <el-table-column label="委托单流水号" prop="orderNum">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.orderNum }}</div>
            </template>
          </el-table-column>
          <el-table-column label="所属作业区" prop="jobArea">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.jobArea }}</div>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" prop="cargoName">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.cargoName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="唛头" prop="mark">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.mark }}</div>
            </template>
          </el-table-column>
          <el-table-column label="货主名称" prop="custName">
            <template slot-scope="scope">
              <div class="nomal-text">{{ scope.row.custName }}</div>
            </template>
          </el-table-column>
        </el-table>
      <div v-if="!tableReadonly" class="stock-btns">
        <el-button @click="handleDelete">删除</el-button>
      </div>
    </el-dialog>


    <!-- 导入对话框 -->
    <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"
        :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>

  </div>

</template>

<script>

import { listCust } from "@/api/jxc/cust";
import { listBillCar,delBillCar } from "@/api/jxc/billCar";
import { listCkstock } from "@/api/jxc/ckstock";
import { getCkbillInfo, outBill } from '@/api/jxc/ckbill';
import { delCkcargo, recallOutBill } from '@/api/jxc/ckcargo';
import StockChoose from "../StockChoose";
import { listVessel } from "@/api/jxc/vessel";
import {getToken} from "@/utils/auth";

export default {
  name: 'StockOut',
  dicts: ['sys_origin_country','sys_out_type'],
  components: {
    StockChoose
  },
  props: {
    // 单据信息
    billInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    disableItems: {
      type: Array,
      default() {
        return [];
      }
    },
    // 传人的出库明细
    modifyData: {
      type: Object,
      default() {
        return {};
      }
    },
    readonly: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      // 导入参数
      carList:{
        open: false,
      },
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/jxc/billCar/importData"
      },
      vesselList: [],
      // 选中数组
      ids: [],
      billCargoNumber:"",
      // jobWt: [], // 使用数组代替原来的字符串
      jobIndex:"",
      outBillNumber:"",
      billCarList: [],
      open: false,
      loading: false,
      deleteWt:[],
      totalDeleteWt:"",
      form: {
        ckBillCargos: [],
        billNumber:"",
        outType: '',
      },
      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' }
        // ],
        expiryDate: [
          { required: true, message: '过期时间不能为空', trigger: 'blur' }
        ],
        cargoValue: [
          { required: true, message: '货物价值不能为空', trigger: 'blur' }
        ],
        stockId: [
          { required: true, message: '库场ID不能为空', trigger: 'blur' }
        ],
        billDate: [
          { required: true, message: '单据日期不能为空', trigger: 'blur' }
        ],
        billNumber: [
          { required: true, message: '单据编号不能为空', trigger: 'blur' }
        ],
        custId: [
          { required: true, message: '货主不能为空', trigger: 'blur' }
        ],
        cargoName: [
          { required: true, message: '货物名称不能为空', trigger: 'blur' }
        ],
        billNo: [
          { required: true, message: '提运单号不能为空', trigger: 'blur' }
        ],
        cargoWt: [
          { required: true, message: '货物重量不能为空', trigger: 'blur' }
        ],
        cargoNum: [
          { required: true, message: '货物件数不能为空', trigger: 'blur' }
        ],
        cargoVol: [
          { required: true, message: '货物体积不能为空', trigger: 'blur' }
        ],
        stockName: [
          { required: true, message: '库场名称不能为空', trigger: 'blur' }
        ],
        custName: [
          { required: true, message: '货主名称不能为空', trigger: 'blur' }
        ]
      },
      // 选中的库存明细
      selectedList: [],
      // 货主
      custList: [],
      // 货物库存列表
      stockList: [],
      // 记录选择的货主ID 用于新增切换货主时提示
      tempCustId: null,
    };
  },
  watch: {
    'form.billNumber': function(newValue, oldValue) {

      if (newValue && oldValue) { // 判断newValue和oldValue都存在
        for (let i = 0; i < this.form.ckBillCargos.length; i++) {
          this.form.ckBillCargos[i].cargoWt = 0;
        }
      }
    },
    // billInfo() {
    //   this.getDetail();
    // },
    // modifyData() {
    //   this.getDetail();
    // }
  },
  computed: {


    // 表格内容只读
    tableReadonly() {
      return this.readonly || this.form.billStatus == 1;
    },
    tableIndexAttrs() {
      if (this.tableReadonly) {
        return {
          label: '序号',
          type: 'index',
          width: '50',
        }
      }
      return {
        type: 'selection',
        width: '55',
      }
    }
  },
  created() {
    this.getVesselList();
    this.form.outType = '3';
  },
  methods: {
    // getCargoValue(row){
    //   const value = row.unitPrice * row.cargoWt;
    //   row.cargoValue = isNaN(value) ? 0 : value.toFixed(4);
    //   return row.cargoValue;
    // },
    // getUnitPrice(row) {
    //   return row.cargoWt !== 0 ? row.cargoValue / row.cargoWt : 0;
    // },
    // updateUnitPrice(row, value) {
    //   row.unitPrice = value;
    // },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.deleteWt = selection.map(item => item.jobWt)
      this.totalDeleteWt = this.deleteWt.reduce((accumulator, currentValue) => accumulator + currentValue, 0);


    },
    handleDelete() {
      if (!this.ids || this.ids.length === 0) {
        return; // 如果ids为空，则不执行删除操作
      }

      // 弹出确认框
      this.$confirm('确定要删除这些货物吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.ckBillCargos[this.jobIndex].cargoWt = this.form.ckBillCargos[this.jobIndex].cargoWt - this.totalDeleteWt;
        // 用户确认删除操作
        delBillCar(this.ids).then(res => {
          // 计算deleteWt总数
          let param = {"billCargoNumber":this.billCargoNumber,"outBillNumber":this.outBillNumber};
          listBillCar(param).then(response => {
            this.billCarList = response.data;
            this.carList.open = true;

          }).catch(e => {
          });
        }).catch(e => {
          this.loading = false;
        })
      }).catch(() => {
        // 用户取消删除操作
        // do nothing
      });
    },
    carBillList(billCargoNumber,outBillNumber,scopeIndex){
      this.jobIndex = scopeIndex;

      let param = {"billCargoNumber":billCargoNumber,"outBillNumber":outBillNumber};
      this.billCargoNumber = billCargoNumber;
      this.outBillNumber = outBillNumber
      listBillCar(param).then(response => {
        this.billCarList = response.data;
        this.carList.open = true;
      }).catch(e => {
      });
    },
    /** 导入按钮操作 */
    handleImport(billCargoNumber,maxWt,scopeIndex,outBillNumber) {
      this.jobIndex = scopeIndex;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.upload.url = process.env.VUE_APP_BASE_API + "/jxc/billCar/importData?billCargoNumber=" + billCargoNumber +"&maxWtStr="+maxWt + "&outBillNumber=" + outBillNumber
          this.upload.title = "车辆批量出库信息导入";
          this.upload.open = true;
        } else {
          // 表单校验失败，显示错误提示信息
          this.$message.error('请填写必填项');
        }
      });
    },
    /** 下载模板操作 */
    importTemplate() {
      const fileName = `车辆批量出库信息模板_${new Date().getTime()}.xlsx`;
      this.download(`jxc/billCar/importTemplate`, {}, fileName);
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      var regExp = /\d+(\.\d+)?/; // 匹配数字和小数点
      var matchResult = response.msg.match(regExp);
      var weight = matchResult ? matchResult[0] : ""; // 如果有匹配结果，则获取第一个数字，否则为空字符串
      // this.jobWt[this.jobIndex] = weight; // 将当前行的重量直接赋给对应的数组元素

      this.form.ckBillCargos[this.jobIndex].cargoWt = weight;
      // this.$set(this.jobWt, this.jobIndex, this.jobWt[this.jobIndex]); // 触发数据更新
      // // 强制重新渲染组件
      // this.$forceUpdate();

      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 });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    init() {
      this.getCustList();
      this.getDetail();
    },
    getVesselList() {
      let param = {};
      listVessel(param).then(response => {
        this.vesselList = response.data;
      }).catch(e => {
      });
    },
    setVesselDetail(vesselId) {
      this.vesselList.forEach(ele => {
        if (ele.id == vesselId) {
          this.form.vesselName = ele.vesselName;
        }
      })
    },
    getMaxData(row) {
      if (this.stockList.length) {
        const index = this.stockList.findIndex(val => val.stockId === row.outStockId && val.billNumber === row.outBillNumber && val.cargoId === row.cargoId);
        if (index > -1) {
          const item = this.stockList[index];
          return {
            cargoNum: item.cargoNum,
            cargoWt: item.cargoWt,
            cargoValue: item.cargoValue,
            cargoVol: item.cargoVol
          };
        }
      }
      return {
        cargoNum: Infinity,
        cargoWt: Infinity,
        cargoValue: Infinity,
        cargoVol: Infinity
      };
    },
    cancel(e) {
      this.$emit('close', e);
    },
    refreshList() {
      this.$emit('refresh');
    },
    validate(success) {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.ckBillCargos.length === 0) {
            this.$message({
              message: '请添加出库明细',
              type: 'warning'
            });
            return;
          }
          this.$refs.listForm.validate((listValid, checkItem) => {
            if (listValid) {
              const tempChoose = {};
              let findRepeat = false;
              let findValueEmpty = false;
              this.form.ckBillCargos.forEach(val => {
                const checkIdef = `${val.outStockId}/${val.outBillNumber}`;
                if (tempChoose[val.cargoId] && tempChoose[val.cargoId] === checkIdef) {
                  findRepeat = true;
                }
                tempChoose[val.cargoId] = checkIdef;
                if (!val.cargoWt && !val.cargoNum && !val.cargoVol) {
                  findValueEmpty = true;
                }
              });
              if (findRepeat) {
                this.$message({
                  message: '出库单重复了，请修改',
                  type: 'warning'
                });
                return;
              }
              if (findValueEmpty) {
                this.$message({
                  message: '货物重量、数量、体积不能同时为空',
                  type: 'warning'
                });
                return;
              }
              success();
            } else {
              this.$message({
                message: checkItem[Object.keys(checkItem)[0]][0].message,
                type: 'warning'
              });
            }
          });
        }
      });
    },
    save(submitStatus) {
      // if (this.form.ckBillCargos && this.form.ckBillCargos.length > 0) {
      //   for (let i = 0; i < this.form.ckBillCargos.length; i++) {
      //     this.form.ckBillCargos[i].cargoWt = this.jobWt[i];
      //   }
      // }
      if (!this.form.billNumber) {
        this.$refs.billInput.updateNumber().then(res => {
          this.validSendData(submitStatus);
        }).catch(e => {
          this.$message.error('单据编号获取失败');
        });
        return;
      }
      this.validSendData(submitStatus);
    },
    validSendData(submitStatus) {
      this.validate(() => {
        this.form.ckBillCargos.forEach(val => {
          val.custId = this.form.custId;
          val.custName = this.form.custName;
          val.custCode = this.form.custCode;
        });
        const params = { ...this.form };
        // 1入库 2出库
        // params.billType = '2';
        params.submitStatus = submitStatus;
        this.loading = true;
        outBill(params).then(res => {
          this.loading = false;
          this.cancel();
          this.refreshList();
          this.$message({
            message: '保存成功！',
            type: 'success'
          });
        }).catch(e => {
          this.loading = false;
        });
      });
    },
    confirm() {
      this.$confirm(`确定${this.form.billStatus == '1' ? '撤销' : '确认'}当前单据吗？`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: this.form.billStatus == '1' ? 'warning' : 'info',
      }).then(() => {
        if (this.form.billStatus == '1') {
          // 撤销
          this.loading = true;
          recallOutBill(this.form.id).then(res => {
            this.$message({
              message: '撤销成功！',
              type: 'success'
            });
            this.loading = false;
            this.cancel();
            this.refreshList();
          }).catch(e => {
            this.loading = false;
          });
          return;
        }

        //确认
        this.save(true);
      });
    },
    addStockOut() {
      if (!this.form.custId) {
        this.$message('请先选择货主');
        return;
      }
      this.open = true;
    },
    // 获取出库明细列表
    getDetail() {
      let billId = this.modifyData.billId || this.billInfo.id || '';
      if (billId) {
        this.loading = true;
        getCkbillInfo(billId).then(res => {
          const data = res.data || {};
          if (!data.ckBillCargos) {
            data.ckBillCargos = [];
          }
          const firstitem = data.ckBillCargos[0];
          if (firstitem) {
            data.custId = firstitem.custId;
            data.custName = firstitem.custName;
            data.custCode = firstitem.custCode;
          }

          this.form = data;

          this.getStockList();
          this.loading = false;
          this.$nextTick(() => {
            if (this.$refs.table) {
              this.$refs.table.doLayout();
            }
          });
        }).catch(e => {
          this.loading = false;
        });
      }

    },
    // 更新库存列表
    updateStockList(list) {
      this.stockList = list;
    },
    // 获取仓库库存列表
    getStockList() {
      if (!this.form.custId) {
        return;
      }
      listCkstock({
        custId: this.form.custId,
      }).then(res => {
        this.stockList = res.data || [];
      }).catch(e => {
      });
    },
    // 选择了货物库存
    chooseStock(list) {
      const noIdItems = list.map(val => {
        // 这里要确认接受什么参数
        return {
          ...val,
          outBillNumber: val.billNumber,
          outStockId: val.stockId,
          billNumber: null,
          stockId: null,
          cargoWt: null,
          id: null,
        };
      });
      this.open = false;
      this.form.ckBillCargos.splice(0, 0, ...noIdItems);
      this.$refs.table.bodyWrapper.scrollTop = this.$refs.table.bodyWrapper.scrollHeight;
      this.$nextTick(() => {
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.$refs.table.doLayout();
      });

    },
    // 设置客户货主
    setCustDetail(custId) {

      if (this.form.ckBillCargos.length && this.tempCustId && custId !== this.tempCustId) {
        this.$confirm('切换货主会清空当前出库表单, 是否继续?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          showClose: false,
        }).then(() => {
          this.tempCustId = custId;
          this.custList.forEach(ele => {
            if (ele.id == custId) {
              this.form.custName = ele.custName;
              this.form.custCode = ele.custCode;
            }
          })
          this.form.ckBillCargos = [];
          this.selectedList = [];
          this.$refs.table.clearSelection();
        }).catch(() => {
          this.form.custId = this.tempCustId;
        });
      } else {
        this.tempCustId = custId;
      }

    },
    // 获取客户货主
    getCustList() {
      listCust({}).then(response => {
        this.custList = response.data;
      }).catch(e => {
      });
    },
    // 选中库存明细
    selectionChange(sel) {
      this.selectedList = sel;
    },
    // 删除明细
    deleteStocks() {
      if (this.selectedList.length) {
        this.$confirm('删除的信息将无法找回，确定删除吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const serveIds = this.selectedList.filter(val => val.id).map(val => val.id).join();
          const didDelete = () => {
            this.form.ckBillCargos = this.form.ckBillCargos.filter(val => !this.selectedList.includes(val));
            this.selectedList = [];
            this.$refs.table.clearSelection();
          }
          if (serveIds) {
            // 删除
            this.loading = true;
            delCkcargo(serveIds).then(res => {
              didDelete();
              this.loading = false;
              this.refreshList();
            }).catch(e => {
              this.loading = false;
            })

            // let param = {"billCargoNumber":this.billCargoNumber,"outBillNumber":this.outBillNumber};
            // delBillCarByNum(param).then(res => {
            //   didDelete();
            //   this.loading = false;
            //   this.refreshList();
            // }).catch(e => {
            //   this.loading = false;
            // })
          } else {
            didDelete();
          }

        }).catch((action) => {

        });
      }
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index < 5) {
          sums[index] = '';
          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;
    }
  },

}
</script>

<style scoped>
.stock-btns {
  margin-top: 5px;
  display: flex;
  justify-content: right;
}

::v-deep .el-dialog__body {
  padding-top: 5px;
}

.stock-content {
  display: flex;
  flex-direction: column;
  height: 70vh;
}

.nomal-text {
  padding: 4px 5px;
}

.margin-none {
  margin: 0;
}

.desc-table {
  padding: 5px;
}


::v-deep .el-table td.el-table__cell {
  padding: 0;
}

::v-deep .el-table--border .el-table__cell {
  padding: 0;
}

::v-deep .el-table .cell {
  padding: 0;
  text-align: center;
}

::v-deep .el-table--border .el-table__cell:first-child .cell {
  padding-left: 0;
}

::v-deep .el-table th.el-table__cell>.cell {
  padding: 0;
}
</style>
