<template>
  <!-- 万州港装船作业报表 -->
  <div style="width:100%;">
    <div style="height:100%;width:100%">
      <div 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="date"
          placeholder="起始日期"
        ></el-date-picker>
        <el-button
          type="primary"
          class="btn"
          @click="search"
          style="margin: 10px;"
        >
          <i class="el-icon-search"></i>查询
        </el-button>
        <el-button
          type="primary"
          class="btn"
          @click="exportToExcel('钢材欠运力报表.xlsx')"
          style="margin: 10px;"
        >
          <i class="el-icon-download"></i>导出excel
        </el-button>
      </div>
      <!-- 装车出库详情 -->
      <div
        ref="yawnReport"
        style="width:100%;height:500px;float:left;margin-left:5px"
      >
        <table class="title">
          <th>{{ titleTXT }}钢材欠运力统计表</th>
        </table>
        <div class="table">
          <el-table
            ref="yawnReportData"
            highlight-current-row
            border
            fit
            :data="yawnReportData"
            :span-method="objectSpanMethod"
            :row-style="{ height: '30px' }"
            :cell-style="returnClassName"
            height="680px"
            style="width: 100%;font-size: 18px"
          >
            <el-table-column
              align="center"
              prop="target"
              label="方向"
              width="120px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="carrierName"
              label="承运商"
              width="100px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="planNum"
              label="审核计划"
              width="80px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="quxiaoNum"
              label="取消计划"
              width="80px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="orderNum"
              label="已派计划"
              width="80px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="notSendNum"
              label="未派车"
              width="80px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="unReceiveNum"
              label="未接收"
              width="80px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="receivedNum"
              label="已接单"
              width="80px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="queueNum"
              label="排队中"
              width="80px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="enFactoryNum"
              label="已进厂"
              width="80px"
            >
            </el-table-column>
            <!-- <el-table-column
              align="center"
              prop="notEnNum"
              label="未进厂数"
              width="100px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="EnNum"
              label="进厂待装数"
              width="100px"
            >
            </el-table-column> -->
            <el-table-column
              align="center"
              prop="percent"
              label="派车率"
              width="110px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="numGong"
              label="工地"
              width="80px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="numCang"
              label="库房"
              width="80px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="totalNet"
              label="磅重"
              width="100px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="materialThoWeight"
              label="理重"
              width="110px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="unloadThoWeight"
              label="未装(理重)"
              width="110px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="trainWeight"
              label="车皮(磅重)"
              width="100px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="trainThoWeight"
              label="车皮(理重)"
              width="100px"
            >
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import PageTitle from '@/components/Page/Title'
import { sjTime } from '@/utils/sharedJsFile'
import { accAdd } from '@/utils/util.js'
import FileSaver from 'file-saver'
import BigNumber from 'bignumber.js'
export default {
  components: { PageTitle },
  data() {
    return {
      count: 0,
      yawnReportData: [],
      map: {
        input: '',
        startTime: null,
        endTime: null
      },
      spanArr: [], // 用于存放需要合并的行的个数
      spanIndex: 0, // 记录spanArr数组的下标
      titleTXT: '',
      startTime: new Date()
    }
  },
  created() {
    let endTime = new Date()
    endTime.setHours(8)
    endTime.setMinutes(0)
    endTime.setSeconds(0)
    let startTime = new Date(endTime.getTime())
    this.map.startTime = startTime
    this.map.endTime = endTime
    this.startTime = startTime
    this.titleTXT = `${this.startTime.getFullYear()}年${this.startTime.getMonth() +
      1}月${this.startTime.getDate()}日08:00 - ${new Date(
      sjTime(this.startTime) + 86400000
    ).getFullYear()}年${new Date(sjTime(this.startTime) + 86400000).getMonth() +
      1}月${new Date(sjTime(this.startTime) + 86400000).getDate()}日08:00`
  },
  mounted() {
    this.search()
  },
  watch: {
    startTime() {
      console.log(this.startTime, 'this.startTime')
      this.titleTXT = `${this.startTime.getFullYear()}年${this.startTime.getMonth() +
        1}月${this.startTime.getDate()}日08:00 - ${new Date(
        sjTime(this.startTime) + 86400000
      ).getFullYear()}年${new Date(
        sjTime(this.startTime) + 86400000
      ).getMonth() + 1}月${new Date(
        sjTime(this.startTime) + 86400000
      ).getDate()}日08:00`
    }
  },
  methods: {
    cellDbclick(row, column, cell, event) {
      let filterMap = {
        consigneeNameList: [],
        truckRemarkList: [],
        saleRemarkList: [],
        saleOrderStatusList: [],
        materialSpeList: [],
        addressPlaceList: [],
        orderStatusList: [],
        saleAreaList: [],
        materialNameList: [],
        carrierList: row.carrier ? [row.carrier] : [],
        capacityList: [],
        isContinueList: [],
        spellNumList: [],
        orderStatusActuallyList: [],
        startTime: this.startTime,
        endTime: this.startTime
        // steelTransFlag: 1
      }

      let page = this.$router.resolve({
        name: 'saleSteelReports',
        query: {
          str: JSON.stringify(filterMap)
        },
        meta: {
          title: '销售钢材报表'
        }
      })
      window.open(page.href, '_blank')
    },
    returnClassName({ row, column, rowIndex, columnIndex }) {
      if (row.flag == 1) {
        console.log(row.carrierName)
        return {
          fontWeight: '700 !important',
          backgroundColor: '#FFFF01'
        }
      }
      if (row.daySumFlag == 1) {
        return {
          fontWeight: '700 !important',
          backgroundColor: '#BFBFBF'
        }
      }
      if (row.monthFlag == 1) {
        return {
          fontWeight: '700 !important',
          backgroundColor: '#91D054'
        }
      }
      if (row.onlyRowFlag == 1 && column.label != '方向') {
        console.log(column.prop, 'BFBFBF')
        return {
          fontWeight: '700 !important',
          backgroundColor: '#FFFF01'
        }
      }
    },
    //查询装车数据
    search() {
      //时间校验
      if (this.map.startTime && this.map.endTime) {
        // if (this.map.startTime >= this.map.endTime) {
        //   this.$message({
        //     message: '结束日期必须大于起始日期!',
        //     type: 'warning',
        //     duration: 2000
        //   })
        //   return
        // }
        this.startTime = this.map.startTime
        this.map.startTime = sjTime(this.map.startTime)
        this.map.endTime = sjTime(this.map.endTime)
      } else {
        this.$message({
          message: '起止日期错误!',
          type: 'warning',
          duration: 2000
        })
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '正在获取数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.axios.post('/api/v1/tms/yawnReport', this.map).then(res => {
        if (res.data.code == '200') {
          let countRow = {
            EnNum: 0,
            carrierName: '',
            no: -1,
            notEnNum: 0,
            notSendNum: 0,
            numCang: 0,
            numGong: 0,
            orderNum: 0,
            percent: '',
            planNum: 0,
            quxiaoNum: 0,
            unReceiveNum: 0,
            receivedNum: 0,
            queueNum: 0,
            enFactoryNum: 0,
            totalNet: 0,
            materialThoWeight: 0,
            trainWeight: 0,
            trainThoWeight: 0,
            unloadThoWeight: 0,
            target: '合计'
          }
          res.data.data.forEach(item => {
            if (item.target != '月合计') {
              countRow.EnNum += item.EnNum
              countRow.notEnNum += item.notEnNum
              countRow.notSendNum += item.notSendNum
              countRow.numCang += item.numCang
              countRow.numGong += item.numGong
              countRow.orderNum += item.orderNum
              countRow.planNum += item.planNum
              countRow.quxiaoNum += item.quxiaoNum
              countRow.unReceiveNum += item.unReceiveNum
              countRow.receivedNum += item.receivedNum
              countRow.queueNum += item.queueNum
              countRow.enFactoryNum += item.enFactoryNum
              // countRow.totalNet =
              //   (countRow.totalNet * 10000 + item.totalNet * 10000) / 10000
              // countRow.materialThoWeight =
              //   (countRow.materialThoWeight * 10000 +
              //     item.materialThoWeight * 10000) /
              //   10000
              countRow.totalNet = accAdd(countRow.totalNet, item.totalNet)
              countRow.materialThoWeight = accAdd(
                countRow.materialThoWeight,
                item.materialThoWeight
              )
              countRow.unloadThoWeight = accAdd(
                countRow.unloadThoWeight,
                item.unloadThoWeight
              )
              countRow.trainWeight = accAdd(
                countRow.trainWeight,
                item.trainWeight
              )
              countRow.trainThoWeight = accAdd(
                countRow.trainThoWeight,
                item.trainThoWeight
              )
              // countRow.unloadThoWeight =
              //   (countRow.unloadThoWeight * 10000 +
              //     item.unloadThoWeight * 10000) /
              //   10000
              // countRow.trainWeight =
              //   (item.trainWeight * 10000 + countRow.trainWeight * 10000) /
              //   10000
              // countRow.trainThoWeight =
              //   (item.trainThoWeight * 10000 +
              //     countRow.trainThoWeight * 10000) /
              //   10000
            }
          })
          if (countRow.planNum) {
            countRow.percent =
              (
                (countRow.orderNum / (countRow.planNum - countRow.quxiaoNum)) *
                100
              ).toFixed(2) + '%'
          } else {
            countRow.percent = 'NAL'
          }
          countRow.daySumFlag = 1
          res.data.data.splice(res.data.data.length - 1, 0, countRow)
          res.data.data[res.data.data.length - 1].monthFlag = 1
          const map1 = res.data.data.reduce((result, item) => {
            result[item.target] = result[item.target] || []
            result[item.target].push(item)
            return result
          }, {})
          let result = Object.values(map1)
          result.forEach(arrayList => {
            if (arrayList.length > 1) {
              let countRow1 = {
                EnNum: 0,
                carrierName: '',
                no: -1,
                notEnNum: 0,
                notSendNum: 0,
                numCang: 0,
                numGong: 0,
                orderNum: 0,
                percent: '',
                planNum: 0,
                quxiaoNum: 0,
                unReceiveNum: 0,
                receivedNum: 0,
                queueNum: 0,
                enFactoryNum: 0,
                totalNet: 0,
                materialThoWeight: 0,
                trainWeight: 0,
                trainThoWeight: 0,
                unloadThoWeight: 0,
                carrierName: '合计',
                target: arrayList[0].target,
                flag: 1
              }
              arrayList.forEach(item => {
                if (!item.target.includes('合计')) {
                  countRow1.EnNum += item.EnNum
                  countRow1.notEnNum += item.notEnNum
                  countRow1.notSendNum += item.notSendNum
                  countRow1.numCang += item.numCang
                  countRow1.numGong += item.numGong
                  countRow1.orderNum += item.orderNum
                  countRow1.planNum += item.planNum
                  countRow1.quxiaoNum += item.quxiaoNum
                  countRow1.unReceiveNum += item.unReceiveNum
                  countRow1.receivedNum += item.receivedNum
                  countRow1.queueNum += item.queueNum
                  countRow1.enFactoryNum += item.enFactoryNum
                  // countRow1.totalNet =
                  //   (countRow1.totalNet * 1000 + item.totalNet * 1000) / 1000
                  // countRow1.materialThoWeight =
                  //   (countRow1.materialThoWeight * 1000 +
                  //     item.materialThoWeight * 1000) /
                  //   1000
                  // countRow1.unloadThoWeight =
                  //   (countRow1.unloadThoWeight * 1000 +
                  //     item.unloadThoWeight * 1000) /
                  //   1000
                  countRow1.totalNet = accAdd(countRow1.totalNet, item.totalNet)
                  countRow1.materialThoWeight = accAdd(
                    countRow1.materialThoWeight,
                    item.materialThoWeight
                  )
                  countRow1.unloadThoWeight = accAdd(
                    countRow1.unloadThoWeight,
                    item.unloadThoWeight
                  )
                  countRow1.trainWeight = accAdd(
                    countRow1.trainWeight,
                    item.trainWeight
                  )
                  countRow1.trainThoWeight = accAdd(
                    countRow1.trainThoWeight,
                    item.trainThoWeight
                  )
                  // countRow1.trainWeight += item.trainWeight
                  // countRow1.trainThoWeight += item.trainThoWeight
                }
              })
              countRow1.percent =
                (
                  (countRow1.orderNum /
                    (countRow1.planNum - countRow1.quxiaoNum)) *
                  100
                ).toFixed(2) + '%'
              arrayList.push(countRow1)
            } else {
              arrayList[0].onlyRowFlag = 1
            }
          })
          // console.log(result, 'result')
          res.data.data = result.flat(1)
          // res.data.data.push(countRow)
          this.getSpanArr(res.data.data)
          this.yawnReportData = res.data.data
          loading.close()
        } else {
          this.$message({
            type: 'error',
            message: res.data.data
          })
          loading.close()
        }
      })
    },
    //处理数据,得到合并数组
    getSpanArr(data) {
      this.spanArr = []
      for (let i = 0; i < data.length; i++) {
        if (i == 0) {
          this.spanArr.push(1)
          this.spanIndex = 0
        } else {
          // 判断当前行与前一行内容是否相同
          if (data[i].target == data[i - 1].target) {
            this.spanArr[this.spanIndex] += 1 // 相同的话，当前下标所代表的值加一，例如：第一列的前三行可合并
            this.spanArr.push(0) // 记录完毕后，再往数组里添加一个元素0，作为下一次合并的初始值
          } else {
            this.spanArr.push(1) // 否则，依旧是一行
            this.spanIndex = i
          }
        }
      }
    },
    //合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex] // 行数
        const _col = _row > 0 ? 1 : 0 // 列数
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    exportToExcel(tableTitle) {
      let tables = this.$refs.yawnReport
      let table_book = XLSX.utils.table_to_book(tables)
      var table_write = XLSX.write(table_book, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([table_write], { type: 'application/octet-stream' }),
          tableTitle
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, table_write)
      }
      return table_write
    }
  }
}
</script>
<style lang="scss" scoped>
.table {
  /deep/ .el-table__row > td {
    // overflow-y: auto;
    // position: absolute !important;

    border: 1px, solid, #000 !important;
  }
}
.title {
  display: flex;
  justify-content: left;
  align-items: center;
  margin-left: 40px;
  font-size: 30px;
  font-weight: 700;
  color: #000;
}
</style>
