//站台库存信息一览表
<template>
  <div id="platformStockInfo">
    <div class="head">
      <!-- //需要一个日期查询框 -->
      <el-form :inline="true">
        <el-form-item>
          <label class="el-form-item__label" style="width: auto;"
            >入库时间：</label
          >
          <el-date-picker
            v-model="startTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width:200px"
          >
          </el-date-picker>
          <span>至</span>
          <el-date-picker
            v-model="endTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width:200px"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="screen"
            placeholder="请选择需筛选的内容"
            clearable
            style="width:150px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            style="width:200px"
            v-model="input"
            placeholder="请输入查询条件"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportAllReportToExcel"
            ><i class="el-icon-download"></i>Excel</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="refresh">
            <i class="el-icon-refresh"></i>
          </el-button>
          <el-button type="primary" class="btn" @click="onclick">
            <i class="el-icon-search"></i>
          </el-button>
          <el-button type="primary" class="btn" @click="batchOperate"
            >批量保存</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="main">
      <el-table
        :data="tableData"
        ref="tableRef"
        border
        stripe
        style="width: 100%; margin-top: 20px"
        max-height="500px"
        :row-style="{ height: '30px' }"
        :cell-style="{ fontWeight: '700' }"
        :summary-method="getSummaries"
        show-summary
        class="table"
        :span-method="objectSpanMethod"
      >
        <el-table-column width="50" label="序号" align="center" type="index">
        </el-table-column>
        <el-table-column
          prop="sendStation"
          label="发站"
          width="120px"
          align="center"
          column-key="sendStation"
          :filters="[
            { text: '专用线', value: '专用线' },
            { text: '达州站', value: '达州站' }
          ]"
          :filter-method="filterSend"
        >
        </el-table-column>
        <el-table-column
          prop="consigneeName"
          label="收货单位"
          width="200px"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="unloadPoint"
          label="卸货地点"
          width="200px"
          align="center"
        >
          <template slot-scope="scope">
            <el-autocomplete
              class="inline-input"
              v-model="scope.row.unloadPoint"
              :fetch-suggestions="querySearchWarehouse"
              placeholder="请输入卸货点名称"
              :trigger-on-focus="false"
              @select="handleSelectWarehouse(scope.row, scope.$index)"
            >
            </el-autocomplete>
          </template>
        </el-table-column>
        <el-table-column
          prop="belongCompany"
          label="所属公司"
          width="200px"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="orderType"
          label="直发/移库"
          width="120px"
          align="center"
          :filters="[
            { text: '移库', value: '移库' },
            { text: '直发', value: '直发' }
          ]"
          :filter-method="filterType"
        >
        </el-table-column>
        <el-table-column
          prop="arrivalStation"
          label="到站"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          prop="railwayBureau"
          label="到局"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          prop="capacityNum"
          label="车牌号"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          prop="materialName"
          label="物资名称"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          prop="materialSpa"
          label="规格"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          prop="materialNum"
          label="件数"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          prop="materialWeight"
          label="重量"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          prop="theoryWeight"
          label="理重"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          prop="orderNum"
          label="运输订单号"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          prop="wgmDelete"
          label="入库状态"
          align="center"
          width="150px"
          column-key="wgmDelete"
          :filters="[
            { text: '入库', value: '入库' },
            { text: '出库', value: '出库' },
            { text: '待入库', value: '待入库' }
          ]"
          :filter-method="filterDeleted"
        >
        </el-table-column>
        <el-table-column
          prop="EnStation"
          label="进站日期"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.EnStation"
              type="date"
              placeholder="选择进站日期"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column
          prop="wagonNo"
          label="发出车号"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.wagonNo" placeholder="发出车号">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="wagonBillWeight"
          label="计费吨位"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">
            <el-input
              v-model.number="scope.row.wagonBillWeight"
              @change="mergeChange(scope.row)"
              placeholder="计费吨位"
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="OutStation"
          label="发出日期"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.OutStation"
              type="date"
              placeholder="选择发出日期"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column
          prop="number"
          label="票号"
          align="center"
          width="180px"
        >
        </el-table-column>
        <el-table-column
          prop="consigneeName"
          label="客户"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          prop="isAccept"
          label="是否验收"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column
          prop="isAcceptTime"
          label="验收时间"
          align="center"
          width="150px"
        >
        </el-table-column>
        <el-table-column label="操作" align="center" width="150px" prop="operation">
          <template slot-scope="scope">
            <el-button type="text" @click="operate(scope.row)">保存</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
//需要设计-发站、移库/直发的表格筛选传递给后端
//需要设计-件数,重量,理重,标重,计费吨位的合计
import { sjTime } from "@/utils/sharedJsFile";
import { getCookie } from "@/utils/util.js";
export default {
  data() {
    return {
      startTime: null,
      endTime: null,
      options: [
        {
          value: "发站",
          lable: "发站"
        },
        {
          value: "收货单位",
          lable: "收货单位"
        },
        {
          value: "车皮号",
          lable: "车皮号"
        },
        {
          value: "到站",
          lable: "到站"
        }
      ],
      input: null,
      tableData: [],
      screen: null,
      sumList: [
        "wagonBillWeight",
        "wagonWeight",
        "theoryWeight",
        "materialWeight",
        "materialNum"
      ],
      operateName: "编辑",
      unloadPointList: [],
      spanArr: [],
      mergeList: ["wagonNo","wagonBillWeight","OutStation"]
    };
  },
  created() {
    this.getRequestUrl();
  },
  mounted() {
    this.showSummariesPosition();
  },
  methods: {
    batchOperate() {
      this.$refs.tableRef.data.forEach((e, index) => {
        this.$refs.tableRef.data.forEach((item, index) => {
          if (
            item.unloadPointId == null &&
            e.consigneeId == item.consigneeId &&
            e.consigneeId != null &&
            e.unloadPointId != null
          ) {
            item.unloadPointId = e.unloadPointId;
            item.unloadPoint = e.unloadPoint;
          }
        });
      });
      this.$refs.tableRef.data.forEach(row => {
        row.personnelSsoId = getCookie("userId");
        if (
          (typeof row.EnStation == "object" ||
            typeof row.EnStation == "string") &&
          row.EnStation != null
        ) {
          row.EnStation = sjTime(new Date(row.EnStation));
        }
        if (
          (typeof row.OutStation == "object" ||
            typeof row.OutStation == "string") &&
          row.OutStation != null
        ) {
          row.OutStation = sjTime(new Date(row.OutStation));
        }
      });
      this.axios
        .post("/api/v1/wms/listAfterInwardOutbound", this.$refs.tableRef.data)
        .then(res => {
          if (res.data.code == "200") {
            this.$message.success("批量保存成功");
            this.getRequestUrl();
          }
        });
      console.log(this.$refs.tableRef.data);
    },
    handleSelectWarehouse(row, index, item) {
      console.log(item);
      this.unloadPointList.forEach(e => {
        if (e.warehouseName == row.unloadPoint) {
          row.unloadPointId = e.warehouseId;
          row.unloadPoint = e.warehouseName;
        }
      });
    },
    //边输边查卸货点
    querySearchWarehouse(queryString, cb) {
      if (queryString.length >= 2) {
        this.axios
          .post("/api/v1/uc/selectUnloadingPoint?index=" + queryString)
          .then(res => {
            console.log(res.data);
            if (res.data.length > 0) {
              console.log(res);
              var restaurantsConsignee = res.data;
              this.unloadPointList = res.data;
              var results = queryString
                ? restaurantsConsignee.filter(
                    this.createFilterConsignee(queryString)
                  )
                : restaurantsConsignee;
              // 调用 callback 返回建议列表的数据
              cb(results);
            }
          });
      }
    },
    createFilterConsignee(queryString) {
      return restaurantsConsignee => {
        return (
          restaurantsConsignee.value
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) > -1
        );
      };
    },
    //修改合并行同步
    mergeChange(row){
      let index=this.tableData.indexOf(row);
      for(let i=index;i<this.tableData.length && row.wagonNo==this.tableData[i].wagonNo && row.OutStation==this.tableData[i].OutStation;i++){
        this.tableData[i].wagonBillWeight=row.wagonBillWeight;
      }
    },
    operate(row) {
      row.personnelSsoId = getCookie("userId");
      if (
        (typeof row.EnStation == "object" ||
          typeof row.EnStation == "string") &&
        row.EnStation != null
      ) {
        row.EnStation = sjTime(new Date(row.EnStation));
      }
      if (
        (typeof row.OutStation == "object" ||
          typeof row.OutStation == "string") &&
        row.OutStation != null
      ) {
        row.OutStation = sjTime(new Date(row.OutStation));
      }
      console.log(typeof row.EnStation);
      console.log(typeof row.OutStation);
      this.axios
        .post("/api/v1/wms/afterInwardOutbound", row)
        .then(res => {
          if (res.data.code == "200") {
            this.$message.success("保存成功");
            this.getRequestUrl();
          } else {
            this.$message.error(res.data.data);
            this.getRequestUrl();
          }
        })
        .catch(e => {
          this.$message.error(e);
          this.getRequestUrl();
        });
    },
    //查询事件
    onclick() {
      let startTime = null;
      let endTime = null;
      let wagonNo = null;
      let consigneeName = null;
      let sendStation = null;
      let toTheStation = null;
      if (this.screen == "发站") {
        sendStation = this.input;
      } else if (this.screen == "到站") {
        toTheStation = this.input;
      } else if (this.screen == "收货单位") {
        consigneeName = this.input;
      } else if (this.screen == "车皮号") {
        wagonNo = this.input;
      }
      if (this.startTime && this.endTime) {
        startTime = sjTime(this.startTime);
        endTime = sjTime(this.endTime);
      }
      this.axios
        .post(
          "/api/v1/oms/getWagonShippingDetails?startTime=" +
            startTime +
            "&endTime=" +
            endTime +
            "&wagonNo=" +
            wagonNo +
            "&consigneeName=" +
            consigneeName +
            "&toTheStation=" +
            toTheStation +
            "&sendStation=" +
            sendStation +
            "&i=" +
            new Date()
        )
        .then(res => {
          this.tableData = res.data.data;
          this.showSummariesPosition();
          this.getSpanArr(this.tableData);
        });
    },
    //获取后台数据
    getRequestUrl() {
      this.axios
        .post(
          "/api/v1/oms/getWagonShippingDetails?startTime=null&endTime=null&i=" +
            new Date()
        )
        .then(res => {
          console.log(res.data.data);
          this.tableData = res.data.data;
          this.getSpanArr(this.tableData);
          this.showSummariesPosition();
        });
    },
    //刷新
    refresh() {
      this.screen = null;
      this.input = null;
      this.getRequestUrl();
    },
    //筛选发站
    filterSend(value, row, column) {
      return row.sendStation === value;
    },
    //筛选类型
    filterType(value, row, column) {
      return row.orderType === value;
    },
    //筛选是否入库数据
    filterDeleted(value, row, column) {
      return row.wgmDelete === value;
    },
    //将合计行置顶
    showSummariesPosition() {
      const table = document.querySelector(".table");
      const footer = document.querySelector(".table .el-table__footer-wrapper");
      const body = document.querySelector(".table .el-table__body-wrapper");
      table.removeChild(footer); // 移除表格最下方的合计行
      table.insertBefore(footer, body); // 把合计行插入到表格body的上面
    },
    //表尾合计行
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        //如果索引值为0,则展示‘合计’
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (this.sumList.includes(column.property)) {
          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] = sums[index].toFixed(2);
            // console.log("sums");
            // console.log(sums[index]);
          } else {
            sums[index] = "N/A";
          }
        }
        //遍历数组,找到符合条件的列
      });
      return sums;
    },
    getSpanArr(data) {
      //每次调用方法初始化
      this.spanArr = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          data[i].group = i;
          this.pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].wagonNo === data[i - 1].wagonNo
          && data[i].OutStation === data[i - 1].OutStation) {
            this.spanArr[this.pos] += 1;
            data[i].group = data[i - 1].group;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.pos = i;
            data[i].group = data[i - 1].group + 1;
          }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.mergeList.includes(column.property)) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    //导出Excel
    exportAllReportToExcel() {
      console.log(this.$refs.tableRef);
      const loading = this.$loading({
        lock: true,
        text: "正在导出Excel",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      var title = this.tableTitle;
      let tHeader = [];
      let filterVal = [];
      console.log(this.$refs.tableRef);
      this.$refs.tableRef.$children.forEach(item => {
        if (item.label != undefined && item.prop != undefined) {
          if (tHeader.indexOf(item.label) === -1) {
            tHeader.push(item.label);
          }
          if (filterVal.indexOf(item.prop) === -1) {
            filterVal.push(item.prop);
          }
        }
      });
      this.downloadLoading = true;
      require.ensure([], () => {
        const {
          export_json_to_excel
        } = require("@/assets/excel/Export2Excel.js"); //这里必须使用绝对路径，使用@/+存放export2Excel的路径
        let data = this.tableData.map(v => filterVal.map(j => v[j])); //3.formatJson格式转换
        export_json_to_excel(tHeader, data, title); // (title)导出的表格名称
      });
      loading.close();
    }
  }
};
</script>
<style lang="scss">
#platformStockInfo {
  .head {
    margin-top: 20px;
    margin-left: 20px;
  }
  .main {
    margin-top: 20px;
    margin-left: 20px;
    ::-webkit-scrollbar {
      // width: 20px;
      height: 20px;
      background-color: transparent;
    }
  }
}
</style>
