<template>
  <!-- 万州港作业报表 -->
  <div class="dowmShipDynamicTable" style="width:100%">
    <div style="height:100%;width:100%">
      <div class="search" style="display:flex;margin: 10px;">
        <el-input
          placeholder="请输入"
          v-model="map.input"
          style="margin: 10px; width:10%"
          clearable
        ></el-input>
       <el-date-picker style="margin: 10px;" v-model="map.startTime" type="datetime" placeholder="起始日期"></el-date-picker>
      <el-date-picker style="margin: 10px;" v-model="map.endTime" type="datetime" placeholder="结束日期"></el-date-picker>
        <el-button
          type="primary"
          class="btn"
          @click="getTableData()"
          style="margin: 10px;"
        >
          <i class="el-icon-search"></i>查询
        </el-button>
      </div>
      <!-- 下游港口船舶动态表 -->
      <div class="loadData" style="height:500px;margin-left:5px;width:100%">
        <!-- <div style="font-size:16px;color:red">港口装车数据:共{{count}}车</div> -->
        <div class="loadTable" style="height:500px;overflow:scroll;width:100%">
        <el-table
          ref="loadTable"
          highlight-current-row
          empty-text="请查询数据"
          border
          fit
          show-summary
          :summary-method="getSummaries"
          :span-method="objectSpanMethod"
          :data="tableData"
          :row-style="{height:'40px'}"
          style="width: 100%;font-size: 18px">
          <el-table-column
          align="center"
            prop="portName"
            label="放货港口"
            width="100px">
          </el-table-column>
          <el-table-column
          align="center"
            prop="productName"
            label="品种/数量/放货日期"
            >
          </el-table-column>
          <el-table-column
          align="center"
            prop="gmTonnage"
            label="港口库存"
            width="100px">
          </el-table-column>
          <el-table-column
          align="center"
            prop="capacityNumber"
            label="船名"
            width="150px">
          </el-table-column>
           <el-table-column
          align="center"
            prop="planLoadTon"
            label="计划吨位"
            width="100px">
          </el-table-column>
           <el-table-column
          align="center"
          prop="shipDynamic"
            label="船舶动态"
            width="250px">
            <template slot-scope="scope">
                <el-input v-model="scope.row.shipDynamic"></el-input>
            </template>
          </el-table-column>
          <el-table-column
          align="center"
            label="装船（吨）"
            prop="loadDetails"
            width="250px">
            <template slot-scope="scope">
            <el-input v-model="scope.row.loadDetails"></el-input>
            </template>
          </el-table-column>
           <el-table-column fixed="right" label="操作" align="center" width="50">
            <template slot-scope="scope">
                <el-button @click="updateDynamic(scope.row)" type="text" size="small">保存</el-button>
            </template>
      </el-table-column>
        </el-table>
        </div >
      </div>
    </div>
  </div>
</template>

<script>
import PageTitle from "@/components/Page/Title";
import { sjTime } from "@/utils/sharedJsFile";
import {getCookie} from "@/utils/util.js";
import BigNumber from "bignumber.js";
export default {
  components: { PageTitle },
  data() {
    return {
        tableData:[],
        spanArr: [], // 用于存放需要合并的行的个数
        spanIndex: 0, // 记录spanArr数组的下标
        spanArr2: [], // 用于存放需要合并的行的个数
        spanIndex2: 0, // 记录spanArr数组的下标
        spanArr3:[],
        spanIndex:0,
        map:{
            input:"",
            startTime:null,
            endTime:null
        },
    };
  },
  mounted(){
    //this.getTableData();
  },
  methods: {
    //查询表格数据
    getTableData(){
      console.log("map",this.map);
      //时间校验
      if(this.map.startTime && this.map.endTime){
        if(this.map.startTime>=this.map.endTime){
            this.$message({
                message:"结束日期必须大于起始日期!",
                type:"warning",
                duration:2000
            });
            return;
        }
        this.map.startTime=sjTime(this.map.startTime);
        this.map.endTime=sjTime(this.map.endTime);
      }else if((this.map.startTime && !this.map.endTime) || (!this.map.startTime && this.map.endTime)){
        this.$message({
            message:"起止日期错误!",
            type:"warning",
            duration:2000
        });
        return;
      }
      //发送请求
      this.axios.post('/api/v1/tms/getDownShipDynamaics',this.map).then((res)=>{
        if(res.data.code == "200"){
            this.getSpanArr(res.data.data);//先得到合并数组
            return Promise.resolve(res);
        }else {
          this.$message({
              type: "error",
              message: res.data.data,
          });
        }
      }).then((res)=>{
        //再给表格赋值
        this.tableData=res.data.data;
      });
    },
    updateDynamic(row){
        console.log("row:",row);
        if(!row.instructionsCapacityId){
             this.$message.warning("无法保存，请先操作装船指令!");
             return;
        }
        this.axios.post('/api/v1/tms/updateInstructionsCapacity',row).then((res)=>{
            if(res.data.code == "200"){
                this.$message.success("保存成功!");
                this.getTableData();
            }else {
                this.$message({
                    type: "error",
                    message: res.data.data,
                });
            }
        });
    },
    getSummaries(param) {
        console.log("param",param);
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          if (index === 3 || index===5) {
            sums[index] = '';
            return;
          }
          if(index === 2){
            let sum=new BigNumber(0);
            data.forEach((row,rowIndex)=>{
              if(rowIndex ==0 || row.gmId !=  data[rowIndex-1].gmId){
                sum=sum.plus(row.gmTonnage);
              }
            })
            sums[index] = sum.toNumber();
            return; 
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return new BigNumber(prev).plus(curr).toNumber();
              } else {
                return prev;
              }
            }, 0);
          } else {
            sums[index] = '';
          }
        });
        return sums;
    },
    //处理数据,得到合并数组
    getSpanArr(data) {
        this.spanArr=[];
        this.spanArr2=[];
        this.spanArr3=[];
        for (let i = 0; i < data.length; i++) {
            if (i == 0) {
                this.spanArr.push(1);
                this.spanArr2.push(1);
                this.spanArr3.push(1);
                this.spanIndex = 0;
                this.spanIndex2 = 0;
                this.spanIndex3 = 0;
            } else {
                // 判断当前行与前一行内容是否相同：港口名
                if (data[i].portName == data[i - 1].portName) {
                    this.spanArr[this.spanIndex] += 1; // 相同的话，当前下标所代表的值加一，例如：第一列的前三行可合并
                    this.spanArr.push(0);// 记录完毕后，再往数组里添加一个元素0，作为下一次合并的初始值
                } else {
                    this.spanArr.push(1); // 否则，依旧是一行
                    this.spanIndex = i;
                }
                // 判断当前行与前一行内容是否相同：发货通知
                if (data[i].productName == data[i - 1].productName) {
                    this.spanArr2[this.spanIndex2] += 1; // 相同的话，当前下标所代表的值加一，例如：第一列的前三行可合并
                    this.spanArr2.push(0);// 记录完毕后，再往数组里添加一个元素0，作为下一次合并的初始值
                } else {
                    this.spanArr2.push(1); // 否则，依旧是一行
                    this.spanIndex2 = i;
                }
                // 判断当前行与前一行内容是否相同：港口库存
                if (data[i].gmId == data[i - 1].gmId) {
                    this.spanArr3[this.spanIndex3] += 1; // 相同的话，当前下标所代表的值加一，例如：第一列的前三行可合并
                    this.spanArr3.push(0);// 记录完毕后，再往数组里添加一个元素0，作为下一次合并的初始值
                } else {
                    this.spanArr3.push(1); // 否则，依旧是一行
                    this.spanIndex3 = i;
                }
            }
        }
        console.log("spanArr",this.spanArr);
    },
    //合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0) {
            const _row = this.spanArr[rowIndex]; // 行数
            const _col = _row > 0 ? 1 : 0; // 列数
            return {
                rowspan: _row,
                colspan: _col
            };
        }else if(columnIndex === 1){
            const _row = this.spanArr2[rowIndex]; // 行数
            const _col = _row > 0 ? 1 : 0; // 列数
            return {
                rowspan: _row,
                colspan: _col
            };
        }else if(columnIndex === 2){
            const _row = this.spanArr3[rowIndex]; // 行数
            const _col = _row > 0 ? 1 : 0; // 列数
            return {
                rowspan: _row,
                colspan: _col
            };
        }
    },
  },
};
</script>
<style lang='scss'>

</style>

