<template>
  <my-page v-if="show === 0">
    <!-- 搜索部分 -->
    <template slot="header">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" size="mini" label-width="68px">
        <el-form-item label="单据编号" prop="billNumber" class="search-item">
          <el-input v-model="billQuery.billNumber" class="search-input" placeholder="请输入单据编号" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="委托单号" prop="wtNumber">
          <el-input v-model="billQuery.wtNumber" placeholder="请输入委托单号" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="批次号" prop="batchNumber">
          <el-input v-model="billQuery.batchNumber" placeholder="请输入批次号" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="货物名称" prop="cargoName">
          <el-input v-model="billQuery.cargoName" placeholder="请输入货物名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="货主名称" prop="custName">
          <el-input v-model="billQuery.custName" placeholder="请输入货主名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="库场名称" prop="stockName">
          <el-input v-model="billQuery.stockName" placeholder="请输入库场名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="单据日期" prop="queryTime" class="search-item">
          <el-date-picker clearable v-model="queryTime" style="width: 200px;" size="mini"
            :picker-options="pickerOptions" end-placeholder="结束日期" range-separator="-" start-placeholder="开始日期"
            type="daterange" value-format="yyyy-MM-dd" placeholder="请选择单据日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
    <!-- 单据部分 -->
    <template slot="left">
      <BillList ref="billList" billType="4" :params="billQuery" @rowClick="billClick"></BillList>
    </template>
    <!-- 列表部分 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['jxc:ckcargo:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="showView"
          v-hasPermi="['jxc:ckcargo:edit']">查看
        </el-button>
      </el-col>
      <!--        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
            v-hasPermi="['jxc:ckcargo:export']">导出
          </el-button>
        </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" height="60vh" :data="tableData" highlight-current-row @sort-change="handleSortChange"
      @selection-change="handleSelectionChange" row-key="id" default-expand-all border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column type="selection" align="center" fixed="left" />
      <el-table-column label="单据类型" align="center" prop="inoutType" sortable="custom" min-width="100" fixed="left" />
      <el-table-column label="货物名称" align="center" prop="cargoName" sortable="custom" min-width="100" fixed="left" />
<!--      <el-table-column label="委托单号" align="center" prop="wtNumber" sortable="custom" min-width="80" />-->
<!--      <el-table-column label="批次号" align="center" prop="batchNumber" sortable="custom" min-width="80" />-->
      <el-table-column label="重量" align="center" prop="cargoWt" sortable="custom" min-width="80" />
      <el-table-column label="仓库名称" align="center" prop="stockCode" sortable='custom' min-width="80">
        <template slot-scope="scope">
          <WarehouseName :stockCode="scope.row.stockCode" />
        </template>
      </el-table-column>
      <el-table-column label="库场名称" align="center" prop="stockName" sortable="custom" min-width="80" />
      <el-table-column label="货主名称" align="center" prop="custName" sortable="custom" min-width="150" />

      <el-table-column label="操作" fixed="right" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="!scope.row.isChildren" size="mini" type="text" icon="el-icon-edit" @click="showView(scope.row)"
            v-hasPermi="['jxc:ckcargo:edit']">查看
          </el-button>
          <el-button v-if="!scope.row.isChildren" size="mini" type="text" icon="el-icon-edit" @click="editView(scope.row)"
            v-hasPermi="['jxc:ckcargo:edit']">修改
          </el-button>
          <el-button v-if="!scope.row.isChildren && scope.row.billStatus == '1'" size="mini" type="text"
            icon="el-icon-edit" @click="recallBill(scope.row)" v-hasPermi="['jxc:ckcargo:edit']">撤回
          </el-button>
          <el-button v-if="!scope.row.isChildren && scope.row.billStatus == '0'" size="mini" type="text"
                     icon="el-icon-edit" @click="deleteBill(scope.row)" v-hasPermi="['jxc:ckcargo:edit']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </my-page>
  <div class="app-container" v-else>
    <el-button @click="cancel" style="align-self: flex-end;">返 回</el-button>
    <el-collapse v-model="activeName">
      <el-collapse-item name="2">
        <template slot="title">
          <span style="color:#ff4949 ; font-size: 18px;font-weight: 800">单据信息</span>
        </template>
        <el-header style="height: 130px; border: 2px solid #eee;padding: 20px 10px;">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <!-- <div class="block">
                <span class="demonstration" style="font-weight: 700;font-size: 15px">生成比例</span>
                <el-slider v-model="form.proportion" input-size="small" @change="changeWt" :max="100" :marks="marks"
                  show-input></el-slider>
              </div> -->
            <el-row>
            <el-col :span="8">
              <el-form-item label="货主名称" prop="custName">
                <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-col :span="8">
              <el-form-item 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 label="单据编号" prop="billNumber">
                <!--                  <el-input v-model="form.billNumber" placeholder="请输入单据编号" />-->
                <bill-number-input ref="billInput" v-model="form.billNumber" type="HP"></bill-number-input>
              </el-form-item>
            </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="委托单号" prop="wtNumber">
                  <el-input v-model="form.wtNumber" placeholder="请输入委托单号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="批次号" prop="batchNumber">
                  <el-input v-model="form.batchNumber" placeholder="请输入批次号" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-header>
      </el-collapse-item>
      <el-collapse-item v-if="form.custId" name="3">
        <template slot="title">
          <span style="color:#ff4949 ; font-size: 18px;font-weight: 800">原货物</span>
        </template>
        <div>
          <el-button type="primary" size="small" @click="addParamsSetting">添加货物</el-button>
          <el-form ref="historyForm" :model="historyForm" size="small" style="margin-top: 10px">
            <el-table :data="historyForm.tableData" style="width: 100%" class="list-table" size="mini" border>
              <el-table-column label="操作" width="80" size="mini" align="center">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope.$index)">删除
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="货物名称" align="center" prop="cargoId">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.cargoId" filterable size="mini" clearable
                    @change="setCargoDetail(scope.row, true)" placeholder="请选择货物名称">
                    <el-option v-for="item in cargoList" :key="item.gdsSeqno" :label="item.cargoName + ' (' + item.gdsSeqno + ')'" :value="item.id" >
                      <span>{{ item.cargoName }} ({{ item.gdsSeqno }})</span>
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="库场名称" align="center" prop="stockId">
                <template slot-scope="scope">
                  <!--                <el-input v-model="form.stockId"></el-input>-->
                  <el-select v-model="scope.row.stockId" filterable placeholder="请输入库场名称" style="width: 100%" clearable
                    @change="setStockDetail(scope.row, true)">
                    <el-option v-for="item in scope.row.stockList ? scope.row.stockList : allStockList"
                      :key="item.stockId" :label="warehouseName(item) + '-' + item.stockName" :value="item.stockId">
                      <WarehouseName :stockCode="item.stockCode"></WarehouseName><span>-{{ item.stockName }}</span>
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="单据编号" align="center" prop="billNumber">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.billNumber" filterable placeholder="请选择出库单据"
                    @change="setNowStockNum(scope.row, scope.$index)" clearable>
                    <el-option v-for="item in scope.row.listMap ? scope.row.listMap[scope.row.stockId] : []"
                      :key="item.billNumber" :label="item.billNumber" :value="item.billNumber">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column width="60" label="当前数量" align="center" prop="nowStockNum">
              </el-table-column>
              <el-table-column width="60" label="当前体积" align="center" prop="nowStockVol">
              </el-table-column>
              <el-table-column width="60" label="当前重量" align="center" prop="nowStockWt">
              </el-table-column>
              <el-table-column width="60" label="当前价值" align="center" prop="nowCargoValue">
              </el-table-column>
              <el-table-column label="出库数量" align="center" prop="cargoNum">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.cargoNum" size="mini"
                    :max="isShow ? Infinity : scope.row.nowStockNum" @change="changeWt" style="width: 100%" :precision="2"
                    :min="0" />

                </template>
              </el-table-column>
              <el-table-column label="出库体积" align="center" prop="cargoVol">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.cargoVol" size="mini"
                    :max="isShow ? Infinity : scope.row.nowStockVol" @change="changeWt" style="width: 100%" :precision="2"
                    :min="0" />
                </template>
              </el-table-column>
              <el-table-column label="出库重量" align="center" prop="cargoWt">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.cargoWt" :max="isShow ? Infinity : scope.row.nowStockWt"
                    @change="changeWt" size="mini" style="width: 100%" :precision="2" :min="0" />
                </template>
              </el-table-column>
              <el-table-column label="出库价值" align="center" prop="cargoValue">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.cargoValue" :max="isShow ? Infinity : scope.row.nowCargoValue"
                    @change="changeWt" size="mini" style="width: 100%" :precision="2" :min="0" />
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-collapse-item>
      <el-collapse-item v-if="form.custId" name="4">
        <template slot="title">
          <span style="color:#ff4949 ; font-size: 18px;font-weight: 800">生成货物</span>
        </template>
        <div>
          <!--          <el-button type="primary" size="small" @click="addParamsSetting2">添加生成货物</el-button>-->
          <el-form ref="historyForm2" :model="historyForm2" size="small">
            <el-row :gutter="20">

              <el-col :span="8">
                <el-form-item label="货物自然序号" prop="cargoNumber">
                  <el-input v-model="historyForm2.tableData[0].cargoNumber" placeholder="请输入货物自然序号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="商品料号" prop="itemNumber">
                  <el-input v-model="historyForm2.tableData[0].itemNumber" placeholder="请输入商品料号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="电子账册项号" prop="bookNumber">
                  <el-input v-model="historyForm2.tableData[0].bookNumber" placeholder="请输入电子账册项号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="报关单号" prop="customsNo">
                  <el-input v-model="historyForm2.tableData[0].customsNo" placeholder="请输入报关单号" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="核注清单号" prop="listNumber">
                  <el-input v-model="historyForm2.tableData[0].listNumber" placeholder="请输入核注清单号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="有效期至" prop="expiryDate">
                  <el-date-picker clearable v-model="historyForm2.tableData[0].expiryDate" type="date"
                    value-format="yyyy-MM-dd" placeholder="请选择有效期至" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="货物价值" prop="cargoValue">
                  <el-input-number v-model="historyForm2.tableData[0].cargoValue" placeholder="请输入货物价值"
                    style="width: 100%" :precision="2" :min="0" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-table :data="historyForm2.tableData" style="width: 100%" class="list-table" size="mini" border>
              <!--              <el-table-column label="操作" width="80" size="mini" align="center">
                                <template slot-scope="scope">
                                  <el-button type="primary" size="mini" @click.native.prevent="deleteRow2(scope.$index)">删除
                                  </el-button>
                                </template>
                              </el-table-column>-->
              <el-table-column label="货物名称" align="center" prop="cargoId">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.cargoId" filterable size="mini" placeholder="请选择货物名称" clearable
                    @change="setCargoDetail(scope.row, false)">
                    <el-option v-for="item in cargoList" :key="item.gdsSeqno" :label="item.cargoName + ' (' + item.gdsSeqno + ')'" :value="item.id" >
                      <span>{{ item.cargoName }} ({{ item.gdsSeqno }})</span>
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="库场名称" align="center" prop="stockId" size="mini">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.stockId" filterable style="width: 100%" clearable size="mini"
                    placeholder="请选择库场名称" @change="setStockDetail(scope.row, false)">
                    <el-option v-for="item in allStockList" :key="item.id"
                      :label="warehouseName(item) + '-' + item.stockName" :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column width="80" label="当前数量" align="center" prop="nowStockNum">
              </el-table-column>
              <el-table-column width="80" label="当前体积" align="center" prop="nowStockVol">
              </el-table-column>
              <el-table-column width="80" label="当前重量" align="center" prop="nowStockWt">
              </el-table-column>
              <el-table-column width="80" label="当前价值" align="center" prop="nowCargoValue">
              </el-table-column>
              <el-table-column label="数量" align="center" prop="cargoNum">
              </el-table-column>
              <el-table-column label="体积" align="center" prop="cargoVol">
              </el-table-column>
              <el-table-column label="重量" align="center" prop="cargoWt">
              </el-table-column>

            </el-table>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
    <div slot="footer" style="margin-top: 10px;">
      <el-button style="margin-right: 20px;" @click="cancel">取 消</el-button>
      <el-button type="primary" v-if="!isShow && (form.billStatus && form.billStatus == '0')" @click="submitFun(true)"
        style="margin-right: 20px;">确认单据</el-button>
      <el-button type="primary" v-if="!isShow && (form.billStatus && form.billStatus == '1')" @click="recallBill"
        style="margin-right: 20px;">单据撤回</el-button>
      <el-button type="primary" v-if="!isShow && (form.billStatus && form.billStatus == '0')" @click="submitFun(false)"
        style="margin-right: 20px;">保 存</el-button>
    </div>
  </div>
</template>

<script>

import { pageListCkcargo, getCkcargo, delCkcargo, addCkcargo, updateCkcargo } from '@/api/jxc/ckcargo'
import { listStock } from '@/api/jxc/stock'
import { listCust } from '@/api/jxc/cust'
import { custCargoList, listCargo } from '@/api/jxc/cargo'
import { listVessel } from '@/api/jxc/vessel'
import { listBmvoyage } from '@/api/jxc/bmvoyage'
import { addCkbill, addMixture, mixtureList, getMixtureInfo, recallMixture,deleteBill  } from '@/api/jxc/ckbill'
import { stockNumList, warehouseList } from '@/api/jxc/ckstock'
import BillList from '@/views/jxc/ckwarehouse/components/BillList';

export default {
  name: 'Ckmixed',
  dicts: ['sys_business_nature', 'sys_trade_nature', 'sys_inbound_outbound_type'],
  components: {
    BillList,
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },

      tableData: [],

      activeName: ['1', '2', '3', '4'],

      show: 0,
      isShow: false,
      marks: {
        0: '0%',
        100: '100%'
      },
      historyForm2: this.initTableDate(),
      historyForm: this.initTableDate(),
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 选中名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单据时间
      queryTime: [],
      // 船舶航次表格数据
      bmvoyageList: [],
      // 船舱表格数据
      vesselList: [],
      // 客户表格数据
      custList: [],
      // 货物表格数据
      cargoList: [],
      custCargoList: [],
      // 仓库表格数据
      allStockList: [],
      listMap: {},
      // 混配矿单表格数据
      ckcargoList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billId: null,
        billDate: null,
        billNumber: null,
        inoutType: null,
        voyageId: null,
        voyageNo: null,
        vesselId: null,
        vesselName: null,
        cargoId: null,
        hsCode: null,
        cargoName: null,
        billNo: null,
        cargoSpec: null,
        originCountry: null,
        custId: null,
        custName: null,
        opType: null,
        tradType: null,
        cargoNum: null,
        cargoWt: null,
        cargoVol: null,
        stockId: null,
        stockCode: null,
        stockName: null,
        beginDate: null,
        endDate: null
      },
      billQuery: {
        billNumber: null,
        cargoName: null,
        stockCode: null,
        stockName: null,
        customsNo: null,
        listNumber: null,
        beginDate: null,
        endDate: null,
      },
      // 表单参数
      form: {
        proportion: 100,
        billStatus: '0',
      },
      // 表单校验
      rules: {

        custId: [
          { required: true, message: '货主名称不能为空', trigger: 'blur' }
        ],

        billDate: [
          { required: true, message: '单据日期不能为空', trigger: 'blur' }
        ],
        billNumber: [
          { required: true, message: '单据编号不能为空', trigger: 'blur' }
        ]
      },
      // 选中的单据
      selectedBill: {},
    }
  },
  created() {
    this.getCustList()
    this.getCargoList()
    this.getVesselList()
    this.getBmvoyage()

  },
  methods: {
    // 点击单据
    billClick(row) {
      const isChange = this.selectedBill.id !== row.id;
      this.selectedBill = row || {};
      this.queryParams.billNumber = this.selectedBill.billNumber;
      if (isChange) {
        this.queryParams.pageNum = 1;
      }
      if (this.queryParams.billNumber) {
        this.getList();
      } else {
        this.tableData = [];
      }
    },
    // 刷新列表
    refreshList() {
      this.queryParams.billNumber = '';
      if (this.queryTime.length) {
        this.billQuery.beginDate = this.queryTime[0];
        this.billQuery.endDate = this.queryTime[1];
      } else {
        this.billQuery.beginDate = null;
        this.billQuery.endDate = null;
      }
      this.$nextTick(() => {
        this.$refs.billList.getList();
      });
    },
    warehouseName(row) {
      const stock = this.$store.getters.warehouseData[row.stockCode] || {};
      return stock.stockName;
    },
    //航次
    getBmvoyage() {
      let param = {}
      listBmvoyage(param).then(response => {
        this.bmvoyageList = response.data
      }).catch(e => {
      })
    },

    changeWt() {
      let countNum = 0
      let countWt = 0
      let countVol = 0
      for (let i = 0; i < this.historyForm.tableData.length; i++) {
        countNum += Number(this.historyForm.tableData[i].cargoNum)
        countWt += Number(this.historyForm.tableData[i].cargoWt)
        countVol += Number(this.historyForm.tableData[i].cargoVol)
      }
      countNum = (countNum * Number(this.form.proportion / 100)).toFixed(2)
      countWt = (countWt * Number(this.form.proportion / 100)).toFixed(2)
      countVol = (countVol * Number(this.form.proportion / 100)).toFixed(2)
      this.historyForm2.tableData[0].cargoNum = countNum
      this.historyForm2.tableData[0].cargoWt = countWt
      this.historyForm2.tableData[0].cargoVol = countVol
    },
    changeadvanced() {
      this.advanced = !this.advanced
    },
    // 显示更多（rows为下拉的行数，根据下拉行数计算高度）
    toggleSearch(rows = 1) {
      this.showMoreSearch = !this.showMoreSearch
      this.searchTitle = this.showMoreSearch ? '收起' : '显示全部'
      this.searchboxHeight = this.showMoreSearch ? rows * 64 + 200 : 200
    },
    //动态添加行
    addList() {
      this.historyForm.tableData.push({
        stockId: '',
        billNumber: '',
        cargoNum: 0,
        cargoVol: 0,
        cargoWt: 0
      })
    },
    //动态添加行
    addList2() {
      this.historyForm2.tableData.push({
        diseaseName: '',
        drugName: '',
        dose: ''
      })
    },
    // 新增行
    addParamsSetting() {
      this.addList()
    },
    // 新增行
    addParamsSetting2() {
      if (this.historyForm2.tableData.length < 1) {
        this.addList2()

      }
    },
    // 删除当前行
    deleteRow(index) {
      this.historyForm.tableData.splice(index, 1)
    },
    submitFun(status) {
      if (!this.form.billNumber) {
        this.$refs.billInput.updateNumber().then(res => {
          this.validSendData(status);
        }).catch(e => {
          this.$message.error('单据编号获取失败');
        });
        return;
      }
      this.validSendData(status);
    },
    validSendData(status) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.historyForm.tableData.length < 2) {
            this.$modal.alertError('原货物至少是两个货物')
            return true
          }
          const flag = this.historyForm.tableData.some(ele => {
            console.log('ele:', ele)
            if (!ele.cargoId || !ele.stockId || !ele.billNumber) {
              this.$modal.alertError('原货物的货物名称、库场名称、单据编号不能为空')
              return true
            }
            if (!ele.cargoNum && !ele.cargoWt && !ele.cargoVol) {
              this.$modal.alertError('原货物的货物数量、体积、重量 必须有一项大于0')
              return true
            }
          })
          if (flag) {
            return
          }
          const flag1 = this.historyForm2.tableData.some(ele => {
            if (!ele.cargoId || !ele.stockId) {
              this.$modal.alertError('生成货物的 货物名称、库场名称 不能为空')
              return true
            }
            if (!ele.cargoNum && !ele.cargoWt && !ele.cargoVol) {
              this.$modal.alertError('生成货物的 出库数量、出库体积、出库重量必须有一项大于0')
              return true
            }
          })
          if (flag1) {
            return
          }
          this.form.submitStatus = status;
          this.form.oldCargos = this.historyForm.tableData
          this.form.newCargos = this.historyForm2.tableData
          if (status) {
            this.$confirm(`确定提交当前单据吗？`, '温馨提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(() => {
              addMixture(this.form).then(response => {
                this.$modal.msgSuccess('提交成功')
                this.reset()
                this.show = 0
                this.historyForm = this.initTableDate()
                this.historyForm2 = this.initTableDate()
                this.refreshList()
              })
            });
          } else {
            addMixture(this.form).then(response => {
              this.$modal.msgSuccess('保存成功')
              this.reset()
              this.show = 0
              this.historyForm = this.initTableDate()
              this.historyForm2 = this.initTableDate()
              this.refreshList()
            })
          }
        }
      })

    },
    recallBill(row) {
      const id = row.id || this.form.id;
      this.$confirm(`确定撤回当前单据吗？`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        recallMixture(id).then(response => {
          this.$modal.msgSuccess("撤回成功");
          this.reset()
          this.historyForm = this.initTableDate()
          this.historyForm2 = this.initTableDate()
          this.show = 0
          this.refreshList();
        });
      });
    },
    deleteBill(row) {
      const id = row.id;
      this.$confirm(`确定删除当前单据吗？`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteBill(id).then(response => {
          this.$modal.msgSuccess("删除成功");
          this.refreshList();
        });
      });
    },
    // 删除当前行
    deleteRow2(index) {
      this.historyForm2.tableData.splice(index, 1)
    },
    submitFun2() {
    },
    //船舶
    setVesselDetail(vesselId) {
      this.vesselList.forEach(ele => {
        if (ele.id == vesselId) {
          this.form.vesselName = ele.vesselName

        }
      })
    },

    getVesselList() {
      let param = {}
      listVessel(param).then(response => {
        this.vesselList = response.data
      }).catch(e => {
      })
    },

    //货物
    setCargoDetail(row, flag) {
      // if (!flag) {
      //   this.historyForm.tableData.some(ele => {
      //     if (ele.cargoId == row.cargoId) {
      //       row.cargoId = ''
      //       this.$modal.alertError('生成货物不允许为原货物请重新选择')
      //       return;
      //     }
      //   })
      // }
      this.getStockList(row, flag)
      row.stockId = ''
      row.billNumber = ''
      if (flag) {
        this.custCargoList.forEach(ele => {
          if (ele.id == row.cargoId) {
            this.$set(row, 'cargoName', ele.cargoName);
            this.$set(row, 'cargoSpec', ele.cargoSpec);
            this.$set(row, 'hsCode', ele.hsCode);
          }
        })
      } else {
        this.cargoList.forEach(ele => {
          if (ele.id == row.cargoId) {
            this.$set(row, 'cargoName', ele.cargoName);
            this.$set(row, 'cargoSpec', ele.cargoSpec);
            this.$set(row, 'hsCode', ele.hsCode);
          }
        })
      }

    },

    getCargoList() {
      let param = {}
      listCargo(param).then(response => {
        this.cargoList = response.data
      }).catch(e => {
      })
    },

    getCustCargoList(custId) {
      let param = { 'custId': custId }
      custCargoList(param).then(response => {
        this.custCargoList = response.data
      }).catch(e => {
      })
    },

    //客户
    setCustDetail(custId) {
      this.historyForm = this.initTableDate()
      this.historyForm2 = this.initTableDate()
      this.getCustCargoList(custId);
      this.custList.forEach(ele => {
        if (ele.id == custId) {
          this.form.custName = ele.custName
          this.form.custCode = ele.custCode
        }
      })
    },

    getCustList() {
      let param = {}
      listCust(param).then(response => {
        this.custList = response.data
      }).catch(e => {
      })
    },

    //仓库
    setStockDetail(row, flag) {
      row.billNumber = ''
      //入库操作，赋值库存量
      let list
      if (flag) {
        list = row.stockList
      } else {
        list = this.allStockList
      }
      list.forEach(ele => {
        if (ele.stockId == row.stockId) {
          this.$set(row, 'hsstockNameCode', ele.stockName);
          this.$set(row, 'stockCode', ele.stockCode);
          this.$set(row, 'nowStockNum', ele.nowStockNum);
          this.$set(row, 'nowStockWt', ele.nowStockWt);
          this.$set(row, 'nowStockVol', ele.nowStockVol);
          this.$set(row, 'nowCargoValue', ele.nowCargoValue);
        }
      })
    },
    //设置现有库存
    setNowStockNum(row, index) {
      this.historyForm.tableData.some((ele, i) => {
        if (row.billNumber == ele.billNumber && row.stockId == ele.stockId && ele.cargoId == row.cargoId && index != i) {
          this.$modal.msgError('已经存在这条出库记录了')
          this.historyForm.tableData[index].billNumber = ''
          return
        }
      })
      console.log(row);
      row.listMap[row.stockId].forEach(ele => {
        if (ele.billNumber == row.billNumber) {
          this.$set(row, 'nowStockNum', ele.cargoNum);
          this.$set(row, 'nowStockWt', ele.cargoWt);
          this.$set(row, 'nowStockVol', ele.cargoVol);
          this.$set(row, 'nowCargoValue', ele.cargoValue);
        }
      })
    },
    getStockList(row, flag) {
      if (flag) {
        let param = {
          custId: this.form.custId,
          cargoId: row.cargoId
        }
        warehouseList(param).then(response => {
          this.$set(row, 'stockList', response.stockList);
          this.$set(row, 'listMap', response.listMap);
        }).catch(e => {
        })
      } else {
        let param = {
          custId: this.form.custId,
          cargoId: row.cargoId
        }
        stockNumList(param).then(response => {
          this.allStockList = response.data
        }).catch(e => {
        })
      }
    },
    /** 查询混配矿单列表 */
    getList() {
      this.loading = true
      mixtureList(this.queryParams).then(response => {
        this.tableData = response.rows
        this.total = response.total
        this.loading = false
      }).catch(e => {
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {

      this.open = false
      this.reset()
      this.show = 0
      this.historyForm = this.initTableDate()
      this.historyForm2 = this.initTableDate()
    },
    initTableDate() {
      return {
        tableData: [{
          stockId: '',
          billNumber: '',
          nowStockNum: 0,
          nowStockVol: 0,
          nowStockWt: 0,
          nowCargoValue: 0,
          cargoNum: 0,
          cargoVol: 0,
          cargoValue: 0,
          cargoWt: 0
        }]
      }
    },
    // 表单重置
    reset() {

      this.form = {
        proportion: 100,
        billStatus: '0',
        id: null,
        billId: null,
        billDate: null,
        billNumber: null,
        inoutType: null,
        voyageId: null,
        voyageNo: null,
        vesselId: null,
        vesselName: null,
        cargoId: null,
        hsCode: null,
        cargoName: null,
        billNo: null,
        cargoSpec: null,
        originCountry: null,
        custId: null,
        custName: null,
        opType: null,
        tradType: null,
        cargoNum: null,
        cargoWt: null,
        cargoVol: null,
        stockId: null,
        stockCode: null,
        stockName: null,
        remark: null
      }
      this.resetForm('form')
    },
    //排序
    handleSortChange(col) {
      this.$sortBy(col, this.queryParams)
      this.getList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.refreshList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryTime = []
      this.billQuery = {
        billNumber: null,
        cargoName: null,
        stockCode: null,
        stockName: null,
        customsNo: null,
        listNumber: null,
        beginDateTwo: null,
        endDateTwo: null,
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isShow = false
      this.show = 1
      this.reset()
      this.open = true
      this.title = '添加混配矿单'
    },
    showView(row) {
      this.isShow = true;
      this.handleUpdate(row)
    },
    editView(row) {
      this.isShow = false;

      this.handleUpdate(row)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let param = {
        custId: row.custId,
        cargoId: row.cargoId
      }
      stockNumList(param).then(response => {
        this.allStockList = response.data
      }).catch(e => {
      })

      this.reset()
      const id = row.id || this.ids
      getMixtureInfo(id).then(response => {
        this.historyForm.tableData = [...response.data.oldCargos]
        this.historyForm2.tableData = [...response.data.newCargos]
        this.form = { ...response.data }
        console.log("historyForm", response.data)
        console.log("historyForm", response)
        this.open = true
        this.show = 1
        this.title = '修改混配矿单'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.show = 0
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCkcargo(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.refreshList()
            })
          } else {
            addCkcargo(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.refreshList()
            })
          }
        }
      })

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const names = row.id || this.names
      this.$modal.confirm('是否确认删除混配矿单为"' + names + '"的数据项？').then(function () {
        return delCkcargo(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jxc/ckcargo/export', {
        ...this.queryParams
      }, `混配矿单_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped>
.app-container {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  overflow-y: scroll;
  display: flex;
  flex-direction: column;
}

.left-container {
  width: 100%;
  height: 100%;
  display: flex;
}

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

.search-item {
  margin-bottom: 6px;
}

.table {
  flex: 1;
}

.search-input {
  max-width: 150px;
}
</style>
