<template>
  <my-page>
    <!-- 搜索部分 -->
    <template slot="header">
      <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="船舶名称" prop="vesselName" class="search-item">
          <el-input v-model="billQuery.vesselName" class="search-input" placeholder="请输入船舶名称" clearable
                    @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="航次号" prop="voyageNo" class="search-item">
          <el-input v-model="billQuery.voyageNo" class="search-input" placeholder="请输入航次号" clearable
                    @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="泊位名称" prop="berthName" class="search-item">
          <el-input v-model="billQuery.berthName" class="search-input" placeholder="请输入泊位名称" clearable
                    @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="货物名称" prop="cargoName" class="search-item">
          <el-input v-model="billQuery.cargoName" class="search-input" placeholder="请输入货物名称" clearable
                    @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="货主名称" prop="custName" class="search-item">
          <el-input v-model="billQuery.custName" class="search-input" placeholder="请输入货主名称" clearable
                    @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="提运单号" prop="billNo" class="search-item">
          <el-input v-model="billQuery.billNo" class="search-input" placeholder="请输入提运单号" clearable
                    @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="业务性质" prop="opType" class="search-item">
          <el-select filterable v-model="billQuery.opType" class="search-input" placeholder="请选择业务性质" clearable>
            <el-option v-for="dict in dict.type.sys_business_nature" :key="dict.value" :label="dict.label"
                       :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="贸易性质" prop="tradType" class="search-item">
          <el-select filterable v-model="billQuery.tradType" class="search-input" placeholder="请选择贸易性质" clearable>
            <el-option v-for="dict in dict.type.sys_trade_nature" :key="dict.value" :label="dict.label"
                       :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="报关单号" prop="customsNo" class="search-item">
          <el-input v-model="billQuery.customsNo" class="search-input" placeholder="请输入报关单号" clearable
                    @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="核注清单" prop="listNumber" class="search-item">
          <el-input v-model="billQuery.listNumber" class="search-input" placeholder="请输入核注清单号" clearable
                    @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="靠泊日期" prop="queryTime" class="search-item">
          <el-date-picker clearable style="width: 200px;" v-model="queryTimeTwo" 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 class="search-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">
      <VoyageNumber ref="voyageNumber" :params="billQuery" @rowClick="voyageNumberClick"></VoyageNumber>
    </template>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['jxc:bmcargo:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="选择左侧航次号后进行确认" placement="top">
          <el-button type="primary" v-if="this.selectedVoyage.voyageNo && this.selectedVoyage.status == '0'" plain
                     icon="el-icon-check" size="mini" @click="handleCheck" v-hasPermi="['jxc:bmcargo:check']">确认
          </el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="选择左侧航次号后进行取消确认" placement="top">
          <el-button type="warning" v-if="this.selectedVoyage.voyageNo && this.selectedVoyage.status == '1'" plain
                     icon="el-icon-close" size="mini" @click="handleCancelCheck" v-hasPermi="['jxc:bmcargo:check']">取消确认
          </el-button>
        </el-tooltip>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table class="table" height="60vh" v-loading="loading" :data="bmcargoList" @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" fixed="left" align="center" />

      <!-- <el-table-column label="船舶信息" align="center" > -->

      <!--          <el-table-column label="航次号" align="center" prop="voyageNo" sortable='custom' width="100" fixed="left" />-->
      <!--          <el-table-column label="船舶名称" align="center" prop="vesselName" sortable='custom' width="100" fixed="left" />-->



      <!-- </el-table-column> -->
      <el-table-column label="货物名称" fixed="left" align="center" prop="cargoName" sortable='custom' width="100" />
      <el-table-column label="货主名称" fixed="left" align="center" prop="custName" sortable='custom' width="200" />
      <el-table-column label="货物自然序号" align="center" prop="cargoNumber" sortable='custom' width="130" />
      <el-table-column label="商品料号" align="center" prop="itemNumber" sortable='custom' width="100" />
      <el-table-column label="电子账册项号" align="center" prop="bookNumber" sortable='custom' width="130" />
      <el-table-column label="HS编号" align="center" prop="hsCode" sortable='custom' width="100" />
      <el-table-column label="报关单号" align="center" prop="customsNo" sortable='custom' width="100" />
      <el-table-column label="核注清单号" align="center" prop="listNumber" sortable='custom' width="130" />
      <el-table-column label="提运单号" align="center" prop="billNo" sortable='custom' width="100" />
      <el-table-column label="货物价值" align="center" prop="cargoValue" sortable='custom' width="100" />
      <el-table-column label="业务性质" align="center" prop="opType" sortable='custom' width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_business_nature" :value="scope.row.opType" />
        </template>
      </el-table-column>
      <el-table-column label="贸易性质" align="center" prop="tradType" sortable='custom' width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_trade_nature" :value="scope.row.tradType" />
        </template>
      </el-table-column>

      <el-table-column label="计划货物件数" align="center" prop="cargoNum" sortable='custom' width="130" />
      <el-table-column label="计划货物重量" align="center" prop="cargoWt" sortable='custom' width="130" />
      <el-table-column label="计划货物体积" align="center" prop="cargoVol" sortable='custom' width="130" />
      <el-table-column label="唛头" align="center" prop="mark" sortable='custom' />

      <el-table-column label="包装类型" align="center" prop="packType" sortable='custom' width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_package_type" :value="scope.row.packType" />
        </template>
      </el-table-column>

      <el-table-column label="计量单位" align="center" prop="unit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_measurement_unit" :value="scope.row.unit" />
        </template>
      </el-table-column>
      <el-table-column label="所属港口公司" align="center" prop="deptId" sortable='custom' width="100"
                       :formatter="deptFormatter" />
      <el-table-column label="舱口类型" align="center" prop="hatchTpe">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_hatch_type" :value="scope.row.hatchTpe" />
        </template>
      </el-table-column>

      <el-table-column label="船港货机械" align="center" prop="cargoMachine" width="130">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_shipport_cargo_machinery" :value="scope.row.cargoMachine" />
        </template>
      </el-table-column>

      <el-table-column label="单件重量" align="center" prop="pieceWeight" sortable='custom' width="100" />
      <el-table-column label="有效期至" align="center" prop="expiryDate" width="180" sortable='custom'>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expiryDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>


      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="120px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['jxc:bmcargo:edit']">修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList" />
    <el-dialog class="dialog" :title="title" :visible.sync="open" width="95%" append-to-body
               :close-on-click-modal="false" fullscreen>
      <BmcargoConfirm v-if="open" :voyageInfo="selectedVoyage" :bmcargo="modifyBmcargo" @completed="handleQuery">
      </BmcargoConfirm>
    </el-dialog>
  </my-page>
</template>

<script>
import {
  pageListBmcargo, updateBmcargo
} from '@/api/jxc/bmcargo'
import { listBmvoyage, checkBmvoyage, uncheckBmvoyage, getBmvoyage } from "@/api/jxc/bmvoyage";
import Treeselect from "@riophae/vue-treeselect";
import { deptTreeSelect } from "@/api/system/user";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import VoyageNumber from "@/views/jxc/bmcargo/components/VoyageNumber";
import BmcargoConfirm from "@/views/jxc/bmcargo/components/BmcargoConfirm";
import { listDept } from "../../../api/system/dept";

export default {
  name: 'Ckconfirm',
  components: { Treeselect, VoyageNumber, BmcargoConfirm },
  dicts: ['sys_hatch_type', 'sys_package_type', 'sys_shipport_cargo_machinery', 'sys_measurement_unit', 'sys_business_nature', 'sys_trade_nature'],
  data() {
    const equalToAct = (rule, value, callback) => {
      if ((this.form.stockNum > 0 || this.form.stockWt > 0 || this.form.stockVol > 0) && !this.form.stockId) {
        callback(new Error('库场名称不能为空'))
      } else {
        callback()
      }
    }
    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]);
          }
        }]
      },
      activeName: ['1', '2', '3', '4', '5', '6'],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 选中名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      queryTimeTwo: [],
      // 仓库表格数据
      stockList: [],
      deptList: [],
      listMap: [],
      // 部门树选项
      deptOptions: [],
      // 船舱表格数据
      vesselList: [],
      // 客户表格数据
      custList: [],
      // 货物表格数据
      cargoList: [],
      // 确认交接表格数据
      bmcargoList: [],
      // 弹出层标题
      // title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        billStockList: [],
        history: null,
        pageNum: 1,
        pageSize: 10,
        voyageId: null,
        voyageNo: null,
        vesselId: null,
        vesselName: null,
        cargoId: null,
        hsCode: null,
        cargoName: null,
        billNo: null,
        custId: null,
        custName: null,
        opType: null,
        tradType: null,
        cargoNum: null,
        cargoWt: null,
        cargoVol: null,
        mark: null,
        packType: null,
        unit: null,
        hatchTpe: null,
        cargoMachine: null,
        pieceWeight: null,
        actNum: null,
        actWt: null,
        actVol: null,
        ztNum: null,
        ztWt: null,
        ztVol: null,
        stockNum: null,
        stockWt: null,
        stockVol: null,
        deptId: null,
        stockName: null,
        cargoValue: null,
        customsNo: null,
        listNumber: null,
        cargoNumber: null,
        itemNumber: null,
        bookNumber: null,
        expiryDate: null,
        beginDateTwo: null,
        endDateTwo: null,
      },
      billQuery: {
        pageNum: 1,
        pageSize: 10,
        billNumber: null,
        cargoName: null,
        vesselName: null,
        berthName: null,
        voyageNo: null,
        customsNo: null,
        listNumber: null,
        beginDate: null,
        endDate: null,
        custName: null,
        billNo: null,
        optype: null,
        tradType: null,
      },
      // 表单参数
      form: {

      },
      tableData: [{
        stockId: '',
        stockCode: '',
        billNumber: '',
        stockName: '',
        cargoNum: '',
        cargoWt: '',
        cargoVol: '',
        cargoValue: '',
        nowStockNum: '',
        nowStockWt: '',
        nowStockVol: '',
        nowCargoValue: ''

      }],
      selectedVoyage: {},
      selection: [],
      modifyBmcargo: {},
      // 表单校验
      rules: {

      }
    }

  },
  computed: {
    title() {
      if (!this.selectedVoyage) {
        return '';
      }
      return `航次号：${this.selectedVoyage.voyageNo} - 船舶名称：${this.selectedVoyage.vesselName} - 泊位名称：${this.selectedVoyage.berthName}`;
    }
  },
  created() {
    //this.getDeptTree();
    listDept({}).then(response => {
      this.deptList = response.data;
    });
  },
  methods: {
    voyageNumberClick(row) {
      const isChange = this.selectedVoyage.id !== row.id;
      this.selectedVoyage = row;
      this.queryParams.voyageId = row.id;
      // 切换的时候重新搜索，否则刷新当前
      //isChange ? this.handleQuery() : this.getList();
      if (isChange) {
        this.queryParams.pageNum = 1;
      }
      if (this.queryParams.voyageId) {
        this.getList();
      } else {
        this.bmcargoList = [];
      }
    },
    // 刷新列表
    refreshList() {
      this.queryParams.voyageId = '';
      if (this.queryTimeTwo != null) {
        this.billQuery.beginDate = this.queryTimeTwo[0];
        this.billQuery.endDate = this.queryTimeTwo[1];
      } else {
        this.billQuery.beginDate = null;
        this.billQuery.endDate = null;
      }
      this.$nextTick(() => {
        this.$refs.voyageNumber.getList();
        //this.ckcargoList = [];
      })
      //this.$refs.voyageNumber.getList();
    },
    deptFormatter(row, column, cellValue, index) {
      const obj = this.deptList.find((obj) => obj.deptId === cellValue)
      return obj ? obj.deptName : cellValue
    },
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询确认交接列表 */
    getList() {
      this.loading = true
      // if (this.queryTimeTwo != null) {
      //   this.queryParams.beginDateTwo = this.queryTimeTwo[0];
      //   this.queryParams.endDateTwo = this.queryTimeTwo[1];
      // } else {
      //   this.queryParams.beginDateTwo = null;
      //   this.queryParams.endDateTwo = null;
      // }
      pageListBmcargo(this.queryParams).then(response => {
        this.bmcargoList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(e => {
        this.loading = false
      })
    },
    //排序
    handleSortChange(col) {
      this.$sortBy(col, this.queryParams)
      this.getList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      //this.getList();
      this.refreshList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.queryTimeTwo = [];
      this.billQuery = {
        billNumber: null,
        cargoName: null,
        vesselName: null,
        berthName: null,
        voyageNo: null,
        customsNo: null,
        listNumber: null,
        beginDate: null,
        endDate: null,
        custName: null,
        billNo: null,
        optype: null,
        tradType: null,
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection;
      this.ids = selection.map(item => item.id);
      this.names = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      getBmvoyage(row.voyageId || this.selection[0].voyageId).then(response => {
        if (response.data) {
          this.modifyBmcargo = { ...(row.voyageId ? row : this.selection[0]) };
          this.selectedVoyage = response.data;
          this.open = true;
        }
      }).catch(e => {
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (!this.tableData) {
            this.$modal.msgError('请添加出（入）库信息')
          }
          let countNum = 0;
          let countWt = 0;
          let countVol = 0;
          let countValue = 0;
          this.tableData.forEach(ele => {
            countNum = Number(countNum) + Number(ele.cargoNum)
            countWt = Number(countWt) + Number(ele.cargoWt)
            countVol = Number(countVol) + Number(ele.cargoVol)
            countValue = Number(countValue) + Number(ele.cargoValue)
          });
          if (countNum != this.form.stockNum || countWt != this.form.stockWt || countVol != this.form.stockVol || countValue != this.form.cargoValue) {
            this.$modal.msgError('出（入）库去向信息数量或价值与出入库数量或价值不符')
            return;
          }
          this.form.billStockList = this.tableData
          //confirmOrder(this.form).then(response => {
          updateBmcargo(this.form).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })

        }
      })
    },
    handleCheck() {

      this.$modal.confirm('是否确认"' + this.selectedVoyage.vesselName + "-航次为：" + this.selectedVoyage.voyageNo + '"的交接清单数据？').then(() => {
        //console.log("selectedVoyage", this.selectedVoyage);
        checkBmvoyage(this.selectedVoyage.id).then(response => {
          this.$modal.msgSuccess('确认成功')
          this.refreshList();
        });
      })
    },
    handleCancelCheck() {

      this.$modal.confirm('是否取消确认"' + this.selectedVoyage.vesselName + "-航次为：" + this.selectedVoyage.voyageNo + '"的交接清单数据？').then(() => {
        uncheckBmvoyage(this.selectedVoyage.id).then(response => {
          this.$modal.msgSuccess('取消确认成功')
          this.refreshList();
        });
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jxc/bmcargo/export', {
        ...this.queryParams
      }, `交接确认_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped lang="scss">
.app-container {
  display: flex;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
}

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

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

.table {
  flex: 1;
}

.search-input {
  max-width: 120px;
}

::v-deep .el-dialog__body {
  padding-top: 10px;
}
</style>
