<!-- 计费账单 -->
<template>
  <div id="detailsStatement">
    <div class="top">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="shipName" placeholder="请输入船名"></el-input>
        </el-form-item>
        <!-- <el-form-item>
          <span class="demonstration">离港日期</span>
          <el-date-picker
            v-model="startTime"
            type="date"
            placeholder="选择日期"
            style="width:200px"
          >
          </el-date-picker>
          <span>至</span>
          <el-date-picker
            v-model="endTime"
            type="date"
            placeholder="选择日期"
            style="width:200px"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <el-button @click="onClick" type="primary" icon="el-icon-search">查询</el-button>
        </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>
          <span class="totalWillTonage">合计已预开票吨位</span>
          <el-input
            v-model="totalWillTonageedValue"
            disabled
            style="width:80px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <span class="totalWillTonage">合计已预开金额</span>
          <el-input
            v-model="totalWillTonageedMoney"
            disabled
            style="width:80px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <span class="totalWillTonage">合计本次实际开票吨位</span>
          <el-input
            v-model="totalActuallyTonageedValue"
            disabled
            style="width:80px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <span class="totalWillTonage">合计本月实际开票金额</span>
          <el-input
            v-model="totalActuallyTonageedMoney"
            disabled
            style="width:80px"
          ></el-input>
        </el-form-item> -->
      </el-form>
    </div>
    <div class="main">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="未结算" name="first">
          <el-table
            :data="tableData"
            ref="tableRef"
            border
            style="width: 100%; margin-top: 0px"
            max-height="500px"
            :row-style="{ height: '30px' }"
            :cell-style="{ fontWeight: '700' }"
            class="table"
            :span-method="objectSpanMethod"
          >
            <el-table-column
              prop="index"
              width="50"
              label="序号"
              align="center"
              :resizable="false"
            >
              <template slot-scope="scope">{{ scope.row.group + 1 }}</template>
            </el-table-column>
            <el-table-column
              prop="materialName"
              label="品种"
              width="120px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="resultForeignShipName"
              label="船名"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="portName"
              label="放货港口"
              width="120px"
              align="center"
            >
            </el-table-column>
            <!-- <el-table-column
              prop="carrierName"
              label="承运单位"
              width="100px"
              align="center"
            >
            </el-table-column> -->
            <el-table-column
              prop="resultOutPortTime"
              label="离港日期"
              width="100px"
              align="center"
            >
            </el-table-column>
             <el-table-column
              prop="monthLoadTonnage"
              label="月份装船吨位"
              width="100px"
              align="center"
            >
             <template slot-scope="scope" v-if="scope.row.unitPriceId">
                {{(scope.row.monthLoadTonnage).toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="monthLoadingProportion"
              label="月份装船比例"
              width="70px"
              align="center"
            >
             <template slot-scope="scope" v-if="scope.row.unitPriceId">
                {{(scope.row.monthLoadingProportion*100).toFixed(2)}}%
              </template>
            </el-table-column>
            <el-table-column
              prop="monthRealTonnage"
              label="月份结算吨位"
              width="100px"
              align="center"
            >
             <template slot-scope="scope">
                {{(scope.row.monthRealTonnage).toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="monthMakeTonnage"
              label="月份开票吨位"
              width="100px"
              align="center"
            >
             <template slot-scope="scope">
                {{(scope.row.monthMakeTonnage).toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="totalEnTonnage"
              label="到厂湿吨"
              width="120px"
              align="center"
            >
              <template slot-scope="scope">
                <el-input type="number" v-model="scope.row.totalEnTonnage"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="unitPrice"
              label="合同单价"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="inspectionFees"
              label="水分检测费"
              width="120px"
              align="center"
            >
              <template slot-scope="scope">
                  <el-input type="number" v-model="scope.row.inspectionFees"></el-input>
              </template>
            </el-table-column>
             <el-table-column
              prop="totalPreviewTonnage"
              label="已预开总吨位"
              width="120px"
              align="center"
            >
              <template slot-scope="scope">
                <el-input type="number" v-model="scope.row.totalPreviewTonnage"></el-input>
              </template>
            </el-table-column>
             <el-table-column
              prop="totalPreviewFee"
              label="已预开总金额"
              width="120px"
              align="center"
            >
              <template slot-scope="scope" v-if="scope.row.totalPreviewFee">
                {{(scope.row.totalPreviewFee).toFixed(2)}}
              </template>
            </el-table-column>
             <el-table-column
              prop="statementTotalAmount"
              label="总计开票金额"
              width="100px"
              align="center"
            >
            </el-table-column>
             <el-table-column
              prop="capacityNumber"
              label="江船"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="loadTonnage"
              label="装船吨位"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="loadingProportion"
              label="装船比例"
              width="70px"
              align="center"
            >
             <template slot-scope="scope">
                {{(scope.row.loadingProportion*100).toFixed(2)}}%
              </template>
            </el-table-column>
            <el-table-column
              prop="realTonnage"
              label="结算吨位"
              width="100px"
              align="center"
            >
             <template slot-scope="scope" v-if="scope.row.realTonnage">
                {{(scope.row.realTonnage).toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="fee"
              label="水运费"
              width="100px"
              align="center"
            >
             <template slot-scope="scope" v-if="scope.row.fee">
                {{(scope.row.fee).toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="previewTonnage"
              label="已预开票吨位"
              width="120px"
              align="center"
            >
             <template slot-scope="scope" v-if="scope.row.previewTonnage">
                {{(scope.row.previewTonnage).toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="previewFee"
              label="已预开票金额"
              width="100px"
              align="center"
            >
            <template slot-scope="scope" v-if="scope.row.previewFee">
                {{(scope.row.previewFee).toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="makeTonnage"
              label="实际开票吨位"
              width="100px"
              align="center"
            >
            <template slot-scope="scope" v-if="scope.row.makeTonnage">
                {{(scope.row.makeTonnage).toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="actuallyMoney"
              label="实际开票金额"
              width="100px"
              align="center"
            >
             <template slot-scope="scope" v-if="scope.row.actuallyMoney">
                {{(scope.row.actuallyMoney).toFixed(2)}}
              </template>
            </el-table-column>
            <!-- <el-table-column
              prop="feeMake"
              label="本月实际开票金额"
              
              align="center"
            >
            </el-table-column> -->
            <el-table-column
              prop="operate"
              label="操作"
              width="100px"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="operate(scope.row)"
                  >预开票</el-button
                >
                <el-button type="text" @click="settlement(scope.row)"
                  >结算</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="已结算" name="second">
          <el-table
            :data="tableData1"
            ref="tableRef1"
            border
            max-height="600px"
            :row-style="{ height: '30px' }"
            :cell-style="{ fontWeight: '700' }"
            class="table"
            :span-method="objectSpanMethod1"
          >
            <el-table-column
              prop="index"
              width="50"
              label="序号"
              align="center"
              :resizable="false"
            >
              <template slot-scope="scope">{{ scope.row.group + 1 }}</template>
            </el-table-column>
            <el-table-column
              prop="materialName"
              label="品种"
              width="150px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="resultForeignShipName"
              label="船名"
              width="150px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="portName"
              label="放货港口"
              width="150px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="totalPreviewTonnage"
              label="已预开总吨位"
              width="120px"
              align="center"
            >
             <template slot-scope="scope" v-if="scope.row.totalPreviewTonnage">
                {{(scope.row.totalPreviewTonnage).toFixed(2)}}
              </template>
            </el-table-column>
             <el-table-column
              prop="totalPreviewFee"
              label="已预开总金额"
              width="120px"
              align="center"
            >
              <template slot-scope="scope" v-if="scope.row.totalPreviewFee">
                {{(scope.row.totalPreviewFee).toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="totalEnTonnage"
              label="开票总吨位"
              width="100px"
              align="center"
            >
            <template slot-scope="scope" v-if="scope.row.totalEnTonnage">
                {{(scope.row.totalEnTonnage).toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="statementTotalAmount"
              label="开票总金额"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="resultOutPortTime"
              label="离港日期"
              width="200px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="loadTonnage"
              label="装船吨位"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="loadingProportion"
              label="装船比例"
              width="100px"
              align="center"
            >
              <template slot-scope="scope">
                {{(scope.row.loadingProportion*100).toFixed(2)}}%
              </template>
            </el-table-column>
              <el-table-column
              prop="inspectionFees"
              label="水分检测费"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="realTonnage"
              label="结算吨位"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="unitPrice"
              label="合同单价"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="fee"
              label="金额(元)"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="previewTonnage"
              label="已预开票吨位"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="previewFee"
              label="已预开票金额"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="makeTonnage"
              label="实际开票吨位"
              width="100px"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="feeMake"
              label="实际开票金额"
              width="100px"
              align="center"
            >
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>
import { getCookie } from "@/utils/util.js";
import { sjTime } from "@/utils/sharedJsFile";
import BigNumber, {bigNumber} from "bignumber.js"
export default {
  data() {
    return {
      totalWillTonageedValue: 0,
      totalWillTonageedMoney: 0,
      totalActuallyTonageedMoney: 0,
      totalActuallyTonageedValue: 0,
      shipName: null,
      tableData: [],
      tableData1: [],
      spanArr: [],
      spanArr1: [],
      pos: null,
      mergeList: [
        "index",
        "carrierName",
        "portName",
        "resultForeignShipName",
        "materialName",
        "totalEnTonnage",
        "operate",
        "statementTotalAmount",
        "makeTonnageTotal",
        "monthLoadTonnage",
        "monthLoadingProportion",
        "monthRealTonnage",
        "totalPreviewTonnage",
        "monthMakeTonnage",
        "totalPreviewFee"
      ],
      activeName: "first",
      tableTitle: "结算账单报表",
      startTime: null,
      endTime: null
    };
  },
  watch: {
    tableData: {
      handler(newVal) {
        console.log("执行一次汇总函数");
        this.computedTableData(newVal);
      },
      deep: true,
      immediate: false
    },
    tableData1: {
      handler(newVal) {
        //console.log("执行一次汇总函数");
        //this.computedTableData1(newVal);
      },
      deep: true,
      immediate: false
    }
  },
  methods: {
    //结算
    settlement(row) {
      console.log("row:",row);
      //遍历tableData,找出相同批次的行数
      let arr = this.tableData.filter(e => {
        return e.batchId == row.batchId && e.noticeTime==row.noticeTime && row.unitPriceId == e.unitPriceId;
      });
      let map = {
        list: arr,
        statementType: 3,
        totalEnTonnage: row.monthMakeTonnage.toFixed(2),
        statementTotalAmount: row.statementTotalAmount.toFixed(2),
        totalPreviewFee:row.totalPreviewFee.toFixed(2),
        totalPreviewTonnage:row.totalPreviewTonnage.toFixed(2),
        userID: getCookie("userId"),
        statementStatus:1
      };
      console.log("map:",map);
      this.axios
        .post("/api/v1/bms/addShipFeeStatement", map)
        .then(res => {
          if (res.data.code == "200") {
            this.getNoDetailsStament();
            this.$message.success("结算成功");
          }
        })
        .catch(() => {
          this.$message.error("结算失败");
        });
    },
    //预开保存
    operate(row) {
      console.log("row:",row);
      //遍历tableData,找出相同批次的行数
      let arr = this.tableData.filter(e => {
        return e.batchId == row.batchId && e.noticeTime==row.noticeTime && row.unitPriceId == e.unitPriceId;
      });
      let map = {
        list: arr,
        statementType: 3,
        totalEnTonnage: row.monthMakeTonnage.toFixed(2),
        statementTotalAmount: row.statementTotalAmount.toFixed(2),
        totalPreviewFee:row.totalPreviewFee.toFixed(2),
        totalPreviewTonnage:row.totalPreviewTonnage.toFixed(2),
        userID: getCookie("userId"),
        statementStatus:0
      };
      console.log("map:",map);
      this.axios
        .post("/api/v1/bms/addShipFeeStatement", map)
        .then(res => {
          if (res.data.code == "200") {
            this.getNoDetailsStament();
            this.$message.success("预开成功");
          }
        })
        .catch(() => {
          this.$message.error("预开失败");
        });
    },
    //处理表格数据
    computedTableData(data) {
      data.forEach((item, index) => {
        if (index == 0) {
        } else if (item.batchId == data[index - 1].batchId && item.noticeTime == data[index - 1].noticeTime && item.unitPriceId == data[index - 1].unitPriceId) {
          item.totalEnTonnage = data[index - 1].totalEnTonnage;
          item.totalPreviewTonnage= data[index - 1].totalPreviewTonnage;
        }
        //总计预开票金额
        item.totalPreviewFee=item.totalPreviewTonnage*item.unitPrice;
        //预开吨位
        item.previewTonnage=item.totalPreviewTonnage*(item.loadTonnage/item.monthLoadTonnage);
        //预开金额
        item.previewFee = (item.unitPrice * item.previewTonnage);
        //结算吨位
        item.realTonnage = (
          item.totalEnTonnage * item.loadingProportion
        );
         //金额
        item.fee = (item.realTonnage * item.unitPrice);
        //开票吨位
        item.makeTonnage = (item.realTonnage - item.previewTonnage);
        //实际开票金额
        item.actuallyMoney = (item.makeTonnage * item.unitPrice-item.inspectionFees);
        //月份结算吨位/
        item.monthRealTonnage = item.totalEnTonnage*item.monthLoadingProportion;
        //月份开票吨位
        item.monthMakeTonnage = item.monthRealTonnage-item.totalPreviewTonnage;
      });
      this.computedTotal(data);
      this.getSpanArr(this.tableData);
    },
    //遍历，汇总
    computedTotal(data){
      data.forEach((item, index) => {
        let arr = data.filter(e => {
          return e.batchId == item.batchId && e.noticeTime==item.noticeTime && e.unitPriceId==item.unitPriceId;
        });
        let inspectionFees=arr.reduce((pre, item1) => {
          if(item1.inspectionFees)
            return pre.plus(new BigNumber(item1.inspectionFees));
          else
            return pre.plus(0.0);
        }, new BigNumber(0.0));
        console.log("inspectionFees:",inspectionFees.toNumber());
        if(item.monthMakeTonnage){
          item.statementTotalAmount=(item.monthMakeTonnage.toFixed(2)*item.unitPrice-inspectionFees.toNumber()).toFixed(2);
        }
      });
    },
    //根据表格据汇总顶部展示
    getTotalArr(data) {
      this.totalWillTonageedValue = data.reduce((pre, item) => {
        return pre + item.willTonanged;
      }, 0);
      this.totalWillTonageedMoney = data.reduce((pre, item) => {
        return pre + item.willMoneyed;
      });
      this.totalActuallyTonageedValue = data.reduce((pre, item) => {
        return pre + item.actuallyMoney;
      });
      this.totalActuallyTonageedMoney = data.reduce((pre, item) => {
        return pre + item.actuallyMonthMoney;
      });
    },
    handleClick() {
      console.log("我正在进行账单");
    },
    onClick() {
      if(this.activeName=='first'){
        this.getNoDetailsStament();
      }else if(this.activeName=='second'){
        this.getDetailsStamented();
      }
    },
    //获取未结算账单数据
    getNoDetailsStament() {
      let startTime = null;
      let endTime = null;
      let map={con:this.shipName};
      // if (this.startTime) {
      //   startTime = sjTime(this.startTime);
      // }
      // if (this.endTime) {
      //   endTime = sjTime(this.endTime);
      // }
      // if(startTime && endTime && startTime < endTime){
      //     map.startTime=startTime;
      //     map.endTime=endTime;
      // }
      this.axios.post("/api/v1/bms/getShipFeeStatement",map).then(res => {
        console.log(res.data.data);
        this.tableData = res.data.data;
        this.computedTableData(this.tableData);
      });
    },
    //已结算账单数据
    getDetailsStamented() {
       let startTime = null;
      let endTime = null;
      let map={con:this.shipName};
      if (this.startTime) {
        startTime = sjTime(this.startTime);
      }
      if (this.endTime) {
        endTime = sjTime(this.endTime);
      }
      if(startTime && endTime && startTime < endTime){
          map.startTime=startTime;
          map.endTime=endTime;
      }
      this.axios.post("/api/v1/bms/getShipFeeStatemented",map).then(res => {
        console.log(res.data.data);
        this.tableData1 = res.data.data;
        this.getSpanArr1(this.tableData1);
      });
    },
    //合并表格数据
    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].batchId === data[i - 1].batchId && data[i].unitPriceId==data[i-1].unitPriceId) {
            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;
          }
        }
      }
    },
    //合并表格数据
    getSpanArr1(data) {
      //每次调用方法初始化
      this.spanArr1 = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr1.push(1);
          data[i].group = i;
          this.pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].statementId === data[i - 1].statementId) {
            this.spanArr1[this.pos] += 1;
            data[i].group = data[i - 1].group;
            this.spanArr1.push(0);
          } else {
            this.spanArr1.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
        };
      }
    },
    objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
      if (this.mergeList.includes(column.property)) {
        const _row = this.spanArr1[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    //导出账单数据
    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 = [];
      let data = [];
      if (this.activeName == "first") {
        data = this.$refs.tableRef.$children;
      } else {
        data = this.$refs.tableRef1.$children;
      }
      data.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();
    }
  },
  mounted() {
    this.getNoDetailsStament();
    this.getDetailsStamented();
  }
};
</script>
<style lang="scss" scoped>
#detailsStatement {
  .top {
    margin-left: 10px;
    margin-top: 10px;
  }
  .main {
    margin-left: 10px;
    ::-webkit-scrollbar {
      // width: 20px;
      height: 20px;
      background-color: transparent;
    }
  }
}
</style>
