<template>
  <my-page>
    <!-- 搜索部分 -->
    <template slot="header">
      <SearchBlock v-model="billQuery" v-show="showSearch" size="mini" :menus="queryOption" @change="handleQuery"></SearchBlock>
      <!-- <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="100px">
        <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="vesselId" class="search-item">
          <el-select v-model="billQuery.vesselId" filterable placeholder="请输入船舶名称" style="width: 100%" clearable>
            <el-option v-for="item in vesselList" :key="item.id" :label="item.vesselName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="航次" prop="voyageNo" class="search-item">
          <el-input v-model="billQuery.voyageNo" placeholder="请输入航次" class="search-input" clearable
                    @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="货物名称" prop="cargoName" class="search-item">
          <el-input v-model="billQuery.cargoName" placeholder="请输入货物名称" class="search-input" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="stockCode" class="search-item">
          <el-select v-model="billQuery.stockCode" filterable placeholder="请选择">
            <el-option v-for="item in warehouses" :key="item.stockCode" :label="item.stockName" :value="item.stockCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓位名称" prop="stockName" class="search-item">
          <el-input v-model="billQuery.stockName" class="search-input" placeholder="请输入仓位名称" clearable
            @keyup.enter.native="handleQuery" />
        </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="queryTimeTwo" class="search-item">
          <el-date-picker clearable v-model="queryTimeTwo" 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" :params="billQuery" @rowClick="billClick"></BillList>
    </template>
    <!-- 列表部分 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="small" plain icon="el-icon-plus" @click="handleAdd('bill')"
          v-hasPermi="['jxc:ckcargo:add']">新增单据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="选择左侧单据号后新增明细" placement="top">
          <el-button type="primary" size="small"
            v-if="(this.selectedBill.sourceType == '1' && this.selectedBill.billStatus == '0')" plain icon="el-icon-plus"
            @click="handleAdd('out')" v-hasPermi="['jxc:ckcargo:add']">新增明细</el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="选择左侧单据后删除" placement="top">
          <el-button type="danger" size="small"
                     v-if="(this.selectedBill.sourceType == '1' && this.selectedBill.billStatus == '0')" plain icon="el-icon-delete"
                     @click="handleDel" v-hasPermi="['jxc:ckcargo:remove']">删除单据</el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="选择左侧单据号后撤销" placement="top">

          <el-button plain size="small" v-if="(this.selectedBill.sourceType == '1' && this.selectedBill.billStatus == '1')"
            type="warning" icon="el-icon-plus" v-hasPermi="['jxc:ckcargo:add']" @click="backBill">单据撤销</el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="选择左侧单据号后单据确认" placement="top">

          <el-button plain size="small" v-if="(this.selectedBill.sourceType == '1' && this.selectedBill.billStatus == '0')"
            type="success" icon="el-icon-plus" v-hasPermi="['jxc:ckcargo:add']" @click="confirm">单据确认</el-button>
        </el-tooltip>
      </el-col>
      <!-- <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="showDetail"
            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" highlight-current-row :data="ckcargoList" height="60vh" @sort-change="handleSortChange"
      @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="货物名称" align="center" prop="cargoName" sortable='custom' min-width="80" fixed="left" />
      <el-table-column label="仓库名称" align="center" prop="stockCode" sortable='custom' min-width="80" fixed="left">
        <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" fixed="left" />
      <el-table-column label="货主名称" align="center" prop="custName" sortable='custom' min-width="150" />
      <el-table-column label="船舶名称" align="center" prop="vesselName" sortable='custom' min-width="100" />
      <el-table-column label="船舶航次" align="center" prop="voyageNo" sortable='custom' min-width="100" />
      <el-table-column label="数据来源" align="center" prop="sourceType" sortable='custom' min-width="100">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.sourceType == '0' ? '载货清单' : scope.row.sourceType == '2' ? '转场' : scope.row.sourceType == '3' ? '混配' : '直接入库' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" sortable='custom' min-width="100">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.billStatus == '1' ? '已确认' : '未确认' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="货物自然序号" align="center" prop="cargoNumber" sortable='custom' min-width="140" />
      <el-table-column label="商品料号" align="center" prop="itemNumber" sortable='custom' min-width="100" />
      <el-table-column label="电子账册项号" align="center" prop="bookNumber" sortable='custom' min-width="130" />
      <el-table-column label="HS编号" align="center" prop="hsCode" sortable='custom' min-width="100" />
      <el-table-column label="报关单号" align="center" prop="customsNo" sortable='custom' min-width="100" />
      <el-table-column label="核注清单号" align="center" prop="listNumber" sortable='custom' min-width="130" />
      <el-table-column label="提运单号" align="center" prop="billNo" sortable='custom' min-width="100" />
      <el-table-column label="货物价值" align="center" prop="cargoValue" sortable='custom' min-width="100" />
      <el-table-column label="货物重量" align="center" prop="cargoWt" sortable='custom' min-width="100" />
      <el-table-column label="规格类型品质" show-overflow-tooltip align="center" prop="cargoSpec" sortable='custom' min-width="200" />
      <el-table-column label="原产国" align="center" prop="originCountry" sortable='custom' min-width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_origin_country"
            :value="scope.row.originCountry != null ? scope.row.originCountry : ''"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="有效期至" align="center" prop="expiryDate" min-width="180" sortable='custom'>
      </el-table-column>
      <el-table-column label="单据日期" align="center" prop="billDate" min-width="180" sortable='custom'>
      </el-table-column>
      <el-table-column label="单据编号" align="center" prop="billNumber" sortable='custom' min-width="100" />
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="120px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-check" @click="showDetail(scope.row)"
            v-hasPermi="['jxc:ckcargo:edit']">查看</el-button>
          <el-button size="mini" type="text" v-if="scope.row.billStatus == '0' && scope.row.sourceType == '1'"
            icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['jxc:ckcargo:edit']">修改</el-button>
          <!-- <el-button size="mini" type="text" v-if="scope.row.sourceType == '1' && scope.row.billStatus == '1'" -->
        </template>
      </el-table-column>
    </el-table>

    <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改仓库入库管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" fullscreen append-to-body :close-on-click-modal="false"
      destroy-on-close>
      <div slot="title" v-if="!hideEdit">
        <el-button type="primary" plain @click="$refs.billEdit.addBillTable()">添加入库单</el-button>
        <el-button type="danger" plain @click="$refs.billEdit.deleteSelectedBill()">删除选中项</el-button>
      </div>
      <BillEdit ref="billEdit" :billInfo="selectedBill" @close="handleClose" @refresh="refreshList"></BillEdit>
    </el-dialog>
  </my-page>
</template>

<script>
import { datePickerOpts } from "@/utils";
import {
  pageListCkcargo,
  getCkcargo,
  delCkcargo,
  addCkcargo,
  updateCkcargo,
  recallPutBill,
  confirmPutBill
} from '@/api/jxc/ckcargo'
import BillList from '@/views/jxc/ckwarehouse/components/BillList';
import BillEdit from '@/views/jxc/ckwarehouse/components/BillEdit';
import { listWarehouse } from "@/api/jxc/warehouse";
import {delCkbill} from "@/api/jxc/ckbill";
import { listVessel } from "@/api/jxc/vessel";

export default {
  name: "Ckwarehouse",
  dicts: ['sys_origin_country', 'sys_trade_nature', 'sys_inbound_outbound_type'],
  components: {
    BillList,
    BillEdit,
  },
  data() {
    return {
      //船名、航次、核注清单编号、单据日期
      queryOption: [
        {
          label: '船舶名称',
          prop: 'vesselId',
          type: 'select',
          getOptions: () => this.vesselList,
          optionsProp: 'id',
          optionsLabel: 'vesselName',
        },
        {
          label: '航次',
          prop: 'voyageNo',
          type: 'text',
        },
        {
          label: '核注清单号',
          prop: 'listNumber',
          type: 'text',
          labelWidth: '90px'
        },
        {
          label: '单据日期',
          prop: 'queryTime',
          type: 'daterange',
          options: datePickerOpts()
        },
        {
          label: '单据编号',
          prop: 'billNumber',
          type: 'text',
        },
        {
          label: '货物名称',
          prop: 'cargoName',
          type: 'text',
        },
        {
          label: '仓库名称',
          prop: 'stockCode',
          type: 'select',
          getOptions: () => this.warehouses,
          optionsProp: 'stockCode',
          optionsLabel: 'stockName',
        },
        {
          label: '仓位名称',
          prop: 'stockName',
          type: 'text',
        },
        {
          label: '报关单号',
          prop: 'customsNo',
          type: 'text',
        },
      ],
      activeName: ['1', '2', '3'],
      pickerOptions: datePickerOpts(),
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 选中名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 有效期
      queryTimeTwo: [],
      // 仓库入库管理表格数据
      ckcargoList: [],
      warehouses: [],
      vesselList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billId: null,
        billDate: null,
        billNumber: null,
        inoutType: "1",
        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,
        cargoValue: null,
        customsNo: null,
        listNumber: null,
        beginDate: null,
        endDate: null,
        cargoNumber: null,
        itemNumber: null,
        bookNumber: null,
        expiryDate: null,
        beginDateTwo: null,
        endDateTwo: null,
      },
      // 单据查询参数
      billQuery: {
        billNumber: null,
        cargoName: null,
        stockCode: null,
        stockName: null,
        customsNo: null,
        listNumber: null,
        beginDate: null,
        endDate: null,
      },
      // 选中单据
      selectedBill: {},
      modifyData: {},
      hideEdit: false,
    };
  },
  created() {
    listWarehouse({}).then(response => {
      this.warehouses = response.data;
    });
    this.getVesselList();
  },
  methods: {
    getVesselList() {
      let param = {};
      listVessel(param).then(response => {
        this.vesselList = response.data;
      }).catch(e => {
      });
    },
    // 点击单据
    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.ckcargoList = [];
      }
    },
    // 刷新列表
    refreshList() {
      this.queryParams.billNumber = '';
      if (this.billQuery.queryTime) {
        this.billQuery.beginDate = this.billQuery.queryTime[0];
        this.billQuery.endDate = this.billQuery.queryTime[1];
      } else {
        this.billQuery.beginDate = null;
        this.billQuery.endDate = null;
      }
      this.$nextTick(() => {
        this.$refs.billList.getList();
        //this.ckcargoList = [];
      })
    },
    /** 查询仓库入库管理列表 */
    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;
      // }
      pageListCkcargo(this.queryParams).then(response => {
        this.ckcargoList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(e => {
        this.loading = false;
      });
    },
    handleClose(show) {
      if (this.hideEdit || !show) {
        this.open = false;
        return;
      }
      this.$confirm('关闭后未保存信息会丢失', '确认关闭？')
        .then(_ => {
          // done && done();
          this.open = false;
        })
        .catch(_ => { });
    },
    //排序
    handleSortChange(col) {
      this.$sortBy(col, this.queryParams);
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // this.getList();
      this.refreshList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryTimeTwo = [];
      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;
      this.modifyData = selection[0] || {};
    },
    handleDel() {
      if (this.selectedBill.billStatus == '0') {
        const ids = this.selectedBill.id || this.ids;
        this.$modal.confirm('是否确认删除"' + this.selectedBill.billNumber+ '"的入库单据？').then(function() {
          return delCkbill(ids);
        }).then(() => {
          this.refreshList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    },
    /** 新增按钮操作 */
    handleAdd(type) {
      this.hideEdit = false;
      if (type === 'bill') {
        this.open = true;
        this.$nextTick(() => {
          this.$refs.billEdit.open({ type: 1 });
        })
        return;
      }
      if (this.selectedBill.billStatus == '1') {
        this.$confirm('当前选中单据已确认，是否新增单据？', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info',
        }).then(() => {
          this.open = true;
          this.$nextTick(() => {
            this.$refs.billEdit.open({ type: 1 });
          })
        });
        return;
      }
      this.open = true;
      this.$nextTick(() => {
        this.$refs.billEdit.open({ type: 1, data: this.selectedBill });
      })
    },
    backBill() {
      this.$confirm(`确定撤销当前单据吗？`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        // 撤销
        this.loading = true;
        recallPutBill(this.selectedBill.id).then(res => {
          this.$message({
            message: '撤销成功！',
            type: 'success'
          });
          this.loading = false;
          this.refreshList();
        }).catch(e => {
          this.loading = false;
        });
      });
    },
    confirm() {
      this.$confirm(`确定提交当前单据吗？`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        // 撤销
        this.loading = true;
        confirmPutBill(this.selectedBill.id).then(res => {
          this.$message({
            message: '提交成功！',
            type: 'success'
          });
          this.loading = false;
          this.refreshList();
        }).catch(e => {
          this.loading = false;
        });
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.hideEdit = row.billStatus == '1';
      this.open = true;
      this.$nextTick(() => {
        this.$refs.billEdit.open({ type: 0, data: row });
      })
    },
    showDetail(row) {
      this.hideEdit = true;
      this.open = true;
      this.$nextTick(() => {
        this.$refs.billEdit.open({ type: 2, data: row.id ? row : this.modifyData });
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.id || this.names;
      this.$modal.confirm('是否确认删除"' + row.billNumber + '"的数据项？').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 {
  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: 150px;
}

::v-deep .el-dialog.is-fullscreen {
  display: flex;
  flex-direction: column;
}

::v-deep .el-dialog__body {
  padding-top: 20px;
  flex: 1;
  overflow: hidden;
}
</style>
