<template>
  <div>
    <div class="shipReport">
      <div class="title">船舶动态表</div>
      <div class="top">
        <el-date-picker
          v-model="endTime"
          @change="DateChange"
          type="datetime"
          placeholder="选择截止时间">
        </el-date-picker>
        <!-- <el-button type="primary" class="btn" @click="onclick">
          <i class="el-icon-search"></i>查询
        </el-button> -->
        <!-- <el-button type="primary" class="btn" @click="reflush">
          <i class="el-icon-search"></i>刷新
        </el-button> -->
        <el-button type="primary" class="btn" @click="getPdfs()">
          <i class="el-icon-download"></i>下载PDF
        </el-button>
        <el-button type="primary" class="btn" @click="getExcel('船舶动态')">
          <i class="el-icon-download"></i>下载Excel
        </el-button>
      </div>
      <table-item ref="ship" v-bind.sync="option" id="pdfDom">
      </table-item>
    </div>
  </div>
</template>
<script>
import tableItem from './tableItem'
import FileSaver from 'file-saver'
import XLSXStyle from 'xlsx-style'
import { isNumber } from '@/utils/sharedJsFile'
export default {
  name: 'TableView',
  components: {
    tableItem
  },
  data() {
    return {
      endTime:null,
      option:{
        endTime:null,
        deadline:null,
           // 树型结构表头数据
        col: [
          {
            prop: 'materialType',
            label: '矿种'
          },
          {
            prop: 'pm',
            label: '品名'
          },
          {
            prop: 'portName',
            label: '港口名称'
          },
          {
            prop: 'tonnage',
            label: '下游港口吨位'
          },
          {
            label: '未到闸船舶',
            children: [
              {
                prop: 'capacity1',
                label: '船名'
              },
              {
                prop: 'capacityNumber1',
                label: '吨位'
              },
              {
                prop: 'locationValue1',
                label: '位置'
              },
              {
                prop: 'outPortTime1',
                label: '离港时间'
              }
            ]
          },
          {
            label: '等闸船舶',
            children: [
              {
                prop: 'capacity2',
                label: '船名'
              },
              {
                prop: 'capacityNumber2',
                label: '吨位'
              },
              {
                prop: 'locationValue2',
                label: '位置'
              },
              {
                prop: 'outPortTime2',
                label: '离港时间'
              }
            ]
          },
          {
            label: '已过闸船舶',
            children: [
              {
                prop: 'capacity3',
                label: '船名'
              },
              {
                prop: 'capacityNumber3',
                label: '吨位'
              },
              {
                prop: 'locationValue3',
                label: '位置'
              },
              {
                prop: 'outPortTime3',
                label: '离港时间'
              }
            ]
          },
          {
            label: '到港待卸船舶',
            children: [
              {
                prop: 'capacity4',
                label: '船名'
              },
              {
                prop: 'capacityNumber4',
                label: '吨位'
              },
              {
                prop: 'locationValue4',
                label: '位置'
              },
              {
                prop: 'outPortTime4',
                label: '离港时间'
              },
              {
                prop: 'dgsj',
                label: '到港时间'
              }
            ]
          }
        ],
        // 表格数据
        tableData: [],
      },
      htmlTitle: '船舶动态表',
      input: '',
      //万州港库存信息
      stockString: null,
      downStockString: null,
      runStockString: null,
      stockStringArr: [],
      downStockStringArr: [],
      runStockStringArr: [],
      loadTable: []
    }
  },
  created() {
    this.initialDate();
  },
  mounted() {
    this.initialization()
    this.getStockString()
    this.getDownStockString()
    this.getRunStockList()
    this.searchLoadData()
    // console.log(this.$refs.excelDom);
  },
  methods: {
    reflush() {
      this.$router.go(0)
    },
    initialDate(){
      let now=new Date();
      now.setMinutes(0);
      now.setSeconds(0);
      if(now.getHours() >=8 && now.getHours() < 18){
        now.setHours(8);
      }else if(now.getHours() >= 18){
        now.setHours(18)
      }else if(now.getHours() < 8 ){
        now = new Date(now.getTime()-1000*60*60*24);
        now.setHours(18)
      }
      this.endTime=now;
      this.DateChange();
    },
    DateChange(){
      this.option.deadline=this.endTime.getFullYear()+'年'+(this.endTime.getMonth()+1)+'月'+this.endTime.getDate()+'日（数据截止于'+this.endTime.getHours()+':'+this.perfix(this.endTime.getMinutes())+'）';
      this.option.endTime=this.endTime.getTime();
      this.onclick();
    },
    perfix(num){
      let arr=new Array(2).fill('0');
      return (arr.join()+num).slice(-2);
    },
    onclick() {
      let map={
        oneDate:this.endTime.getTime()
      }
      this.axios
        .post('/api/v1/tms/selectAllShipDynamaics?con=' + this.input,map)
        .then(res => {
          if (res.data.code == '200') {
            this.option.tableData = res.data.data
            console.log('aaad' + res.data.data)
          } else if (res.data.data == '暂时没有船舶动态') {
            this.option.tableData = []
          }
        })
    },
    bta(s) {
      var buf = new ArrayBuffer(s.length)
      var view = new Uint8Array(buf)
      for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
      return buf
    },
    getExcel(tableTitle) {
      //let tables = this.$refs.ship;//此处是拿表格document元素,也可以取父div的ref
      let tables = document.getElementById('pdfDom')
      let table_book = XLSX.utils.table_to_book(tables)
      console.log('table_book:', table_book)
      console.log('sheet:', table_book.Sheets.Sheet1)
      //限制单元格样式范围
      let rangeList = [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        ,
        'R',
        'S',
        'T',
        'U'
      ]
      //得到自定义过滤数组
      let filterList = this.exportFilter(table_book.Sheets.Sheet1)
      console.log('filterList:', filterList)
      let flag = true
      //这里遍历单元格给单元格对象设置属性,s为控制样式的属性
      Object.keys(table_book.Sheets.Sheet1).forEach(key => {
        if (
          key.indexOf('!') < 0 &&
          rangeList.indexOf(this.getCol(key)) >= 0 &&
          filterList.indexOf(key) < 0
        ) {
          table_book.Sheets.Sheet1[key].s = {
            font: {
              name: '宋体',
              sz: 10
            },
            alignment: {
              //对齐方式
              horizontal: 'center', //水平居中
              vertical: 'center', //竖直居中
              wrapText: true //自动换行
            },
            border: {
              // 设置边框
              top: { style: 'thin' },
              bottom: { style: 'thin' },
              left: { style: 'thin' },
              right: { style: 'thin' }
            }
          }
          //更改数字格式
          if (flag && table_book.Sheets.Sheet1[key].t == 'n') {
            table_book.Sheets.Sheet1[key].s.numFmt = '0.00'
          }
          //库存三列特殊对待
          if (
            table_book.Sheets.Sheet1[key].t == 's' &&
            table_book.Sheets.Sheet1[key].v &&
            (table_book.Sheets.Sheet1[key].v.includes('下游港口库存') ||
              table_book.Sheets.Sheet1[key].v.includes('万港库存') ||
              table_book.Sheets.Sheet1[key].v.includes('在途货物'))
          ) {
            flag = false //标识为不允许更改数字格式
            table_book.Sheets.Sheet1[key].s = {
              font: {
                name: '宋体',
                sz: 10
              },
              alignment: {
                vertical: 'center',
                wrapText: true
              },
              border: {
                top: { style: 'thin' },
                bottom: { style: 'thin' },
                left: { style: 'thin' },
                right: { style: 'thin' }
              }
            }
          }
        }
      })
      //表头字体重新设置
      table_book.Sheets.Sheet1['A1'].s.font = {
        name: '宋体',
        sz: 16,
        bold: true
      }
      //画一个简报
      this.drawExcel(table_book.Sheets.Sheet1)
      //处理合并行样式
      this.addRangeBorder(
        table_book.Sheets.Sheet1['!merges'],
        table_book.Sheets.Sheet1
      )
      console.log('sheet:', table_book.Sheets.Sheet1)
      //导出
      let table_write = XLSXStyle.write(table_book, {
        type: 'binary',
        bookType: 'xlsx'
      })
      try {
        FileSaver.saveAs(
          new Blob([this.bta(table_write)], {
            type: 'application/octet-stream'
          }),
          tableTitle + '.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, table_write)
      }
      return table_write
    },
    drawExcel(sheet) {
      //画一个进口矿水联运情况简报
      let style = {
        font: {
          name: '宋体',
          sz: 10
        },
        alignment: {
          //对齐方式
          horizontal: 'center', //水平居中
          vertical: 'center', //竖直居中
          wrapText: true //自动换行
        },
        border: {
          // 设置边框
          top: { style: 'thin' },
          bottom: { style: 'thin' },
          left: { style: 'thin' },
          right: { style: 'thin' }
        }
      }
      Object.keys(sheet).forEach(key => {
        if (key.indexOf('!') < 0 && sheet[key].v == '万州港发货信息') {
          let row = this.getRow(key)
          console.log('万州港发货信息：', row)
          //第一行表头
          sheet['I' + row] = {
            t: 's',
            v: '进口矿水联运情况简报',
            s: style
          }
          for (let i = row + 1; i < this.loadTable.length + row + 3; i++) {
            sheet['I' + i] = {
              t: 's',
              v: '',
              s: style
            }
          }
          //表格合并
          for (let i = row - 1; i < this.loadTable.length + row + 2; i++) {
            sheet['!merges'].push({
              s: {
                r: i,
                c: 8
              },
              e: {
                r: i,
                c: 15
              }
            })
          }
          return
        }
      })
    },
    exportFilter(sheet) {
      //导出过滤方法
      let keys = []
      Object.keys(sheet).forEach(key => {
        if (key.indexOf('!') < 0 && sheet[key].v == '万州港发货信息') {
          let row = this.getRow(key)
          console.log('万州港发货信息：', row)
          for (let i = row; i < this.loadTable.length + row + 3; i++) {
            keys.push('F' + i)
          }
        } else if (
          key.indexOf('!') < 0 &&
          sheet[key].v == '控制线等闸船舶动态'
        ) {
          let row = this.getRow(key)
          console.log('控制线等闸船舶动态：', row)
          for (let i = row; i < row + 2; i++) {
            keys.push('Q' + i)
          }
        }
      })
      return keys
    },
    addRangeBorder(range, ws) {
      let cols = [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V'
      ]
      range.forEach(item => {
        let style = {
          s: {
            border: {
              top: { style: 'thin' },
              left: { style: 'thin' },
              bottom: { style: 'thin' },
              right: { style: 'thin' }
            }
          }
        }
        // 处理合并行
        for (let i = item.s.c; i <= item.e.c; i++) {
          ws[`${cols[i]}${Number(item.e.r) + 1}`] =
            ws[`${cols[i]}${Number(item.e.r) + 1}`] || style
          // 处理合并列
          for (let k = item.s.r + 2; k <= item.e.r + 1; k++) {
            ws[cols[i] + k] = ws[cols[k] + item.e.r] || style
          }
        }
      })
      return ws
    },
    getRow(key) {
      return parseInt(key.replace(/[^0-9]/gi, ''))
    },
    getCol(key) {
      let row = key.replace(/[^0-9]/gi, '')
      return key.replace(row, '')
    },
    appendOne(Sheet, row) {
      //从后面新增1行，并行合并
      let seArr = Sheet['!fullref'].split(':')
      let length = parseInt(seArr[1].replace(/[^0-9]/gi, ''))
      let endCol = seArr[1].replace(length, '')
      //新增行
      length++
      Sheet['A' + length] = {
        t: 's',
        v: row
      }
      Sheet['!fullref'] = seArr[0] + ':' + endCol + length
      Sheet['!ref'] = seArr[0] + ':' + endCol + length
      //行合并
      Sheet['!merges'].push({
        s: {
          c: 0,
          r: length - 1
        },
        e: {
          c: 21,
          r: length - 1
        }
      })
      return Sheet
    },
    initialization() {
      this.axios.post('/api/v1/tms/selectAllShipDynamaics').then(res => {
        if (res.data.code == '200') {
          this.option.tableData = res.data.data
          console.log('this.option.tableData:', this.option.tableData)
          this.option.tableData.forEach(item => {
            try {
              item.tonnage = item.tonnage.toFixed(2)
            } catch (error) {}
            try {
              if (item.capacityNumber1 || item.capacityNumber1 == 0) {
                item.capacityNumber1 = parseFloat(item.capacityNumber1).toFixed(
                  2
                )
              }
            } catch (error) {}
            try {
              if (item.capacityNumber2 || item.capacityNumber2 == 0) {
                item.capacityNumber2 = parseFloat(item.capacityNumber2).toFixed(
                  2
                )
              }
            } catch (error) {}
            try {
              if (item.capacityNumber3 || item.capacityNumber3 == 0) {
                item.capacityNumber3 = parseFloat(item.capacityNumber3).toFixed(
                  2
                )
              }
            } catch (error) {}
            try {
              if (item.capacityNumber4 || item.capacityNumber4 == 0) {
                item.capacityNumber4 = parseFloat(item.capacityNumber4).toFixed(
                  2
                )
              }
            } catch (error) {}
            try {
              if (isNumber(item.capacity1)) {
                item.capacity1 = parseFloat(item.capacity1).toFixed(2)
              }
            } catch (error) {}
          })
          console.log(this.option.tableData)
        } else {
          this.$message({
            type: 'warning',
            message: res.data.data
          })
        }
      })
    },
    getStockString() {
      let that = this
      this.axios
        .post(
          '/api/v1/wmsh/getLoadPortStockList?apiId=158&pageSize=1000&pageNum=1'
        )
        .then(res => {
          console.log(res)
          if (res.status == '200') {
            let resultActualInstallations = 0
            res.data.data.list.forEach(e => {
              resultActualInstallations =
                resultActualInstallations + e.gmTonnage
            })

            this.stockString +=
              '万港库存' + resultActualInstallations.toFixed(2) + '吨：'
            this.stockStringArr.push({
              class: 'normal',
              value: '万港库存' + resultActualInstallations.toFixed(2) + '吨：'
            })

            let materialName = res.data.data.list[0].materialName
            this.stockStringArr.push({
              class: 'black',
              value: materialName + res.data.data.list[0].totalTonnage + '吨：'
            })
            this.stockString +=
              materialName + res.data.data.list[0].totalTonnage + '吨 '

            res.data.data.list.forEach(e => {
              if (e.materialName == materialName) {
                this.stockString +=
                  ' “' + e.resultForeignShipName + '”' + e.gmTonnage + '吨 '
                this.stockStringArr.push({
                  class: 'normal',
                  value:
                    ' “' + e.resultForeignShipName + '”' + e.gmTonnage + '吨 '
                })
              } else {
                materialName = e.materialName
                this.stockString +=
                  materialName + res.data.data.list[0].totalTonnage + '吨 '
                this.stockString +=
                  '；' +
                  materialName +
                  e.totalTonnage +
                  '吨：' +
                  ' “' +
                  e.resultForeignShipName +
                  '”' +
                  e.gmTonnage +
                  '吨 '
                this.stockStringArr.push({
                  class: 'black',
                  value: '；' + materialName + e.totalTonnage + '吨：'
                })
                this.stockString +=
                  '；' +
                  materialName +
                  e.totalTonnage +
                  '吨：' +
                  ' “' +
                  e.resultForeignShipName +
                  '”' +
                  e.gmTonnage +
                  '吨 '
                this.stockStringArr.push({
                  class: 'normal',
                  value:
                    ' “' + e.resultForeignShipName + '”' + e.gmTonnage + '吨 '
                })
              }
            })
            this.stockString = ''
            this.stockStringArr.forEach(item => {
              this.stockString += item.value
            })
            console.log('this.stockString:', this.stockString)
          } else {
          }
        })
    },
    getDownStockString() {
      let that = this
      this.axios.post('/api/v1/wmsh/getDownPortStockList').then(res => {
        console.log(res)
        if (res.status == '200') {
          let resultActualInstallations = 0
          res.data.data.forEach(e => {
            resultActualInstallations = resultActualInstallations + e.gmTonnage
          })

          this.downStockStringArr.push({
            class: 'normalFirst',
            value:
              '下游港口库存' + resultActualInstallations.toFixed(2) + '吨：'
          })

          let materialName = res.data.data[0].materialName
          this.downStockStringArr.push({
            class: 'black',
            value: materialName + res.data.data[0].totalTonnage + '吨：'
          })

          res.data.data.forEach(e => {
            if (e.materialName == materialName) {
              this.downStockStringArr.push({
                class: 'normal',
                value:
                  ' “' + e.resultForeignShipName + '”' + e.gmTonnage + '吨 '
              })
            } else {
              materialName = e.materialName
              this.downStockStringArr.push({
                class: 'black',
                value: '；' + materialName + e.totalTonnage + '吨：'
              })
              this.downStockStringArr.push({
                class: 'normal',
                value:
                  ' “' + e.resultForeignShipName + '”' + e.gmTonnage + '吨 '
              })
            }
          })
          this.downStockString = ''
          this.downStockStringArr.forEach(item => {
            this.downStockString += item.value
          })
          console.log('this.downStockString:', this.downStockString)
        }
      })
    },
    getRunStockList() {
      let that = this
      this.axios.post('/api/v1/wmsh/getRunStockList').then(res => {
        console.log(res)
        if (res.status == '200') {
          let resultActualInstallations = 0
          res.data.data.forEach(e => {
            resultActualInstallations = resultActualInstallations + e.gmTonnage
          })

          this.runStockStringArr.push({
            class: 'normalFirst',
            value: '在途库存' + resultActualInstallations.toFixed(2) + '吨：'
          })

          let materialName = res.data.data[0].materialName
          this.runStockStringArr.push({
            class: 'black',
            value: materialName + res.data.data[0].totalTonnage + '吨：'
          })

          res.data.data.forEach(e => {
            if (e.materialName == materialName) {
              this.runStockStringArr.push({
                class: 'normal',
                value:
                  ' “' + e.resultForeignShipName + '”' + e.gmTonnage + '吨 '
              })
            } else {
              materialName = e.materialName
              this.runStockStringArr.push({
                class: 'black',
                value: '；' + materialName + e.totalTonnage + '吨：'
              })
              this.runStockStringArr.push({
                class: 'normal',
                value:
                  ' “' + e.resultForeignShipName + '”' + e.gmTonnage + '吨 '
              })
            }
          })
          this.runStockString = ''
          this.runStockStringArr.forEach(item => {
            this.runStockString += item.value
          })
          console.log('this.runStockString:', this.runStockString)
        }
      })
    },
    //查询装车数据
    searchLoadData() {
      let map = {}
      this.axios.post('/api/v1/tms/getLoadData', map).then(res => {
        if (res.data.code == '200') {
          this.loadTable = res.data.data
        } else {
          this.$message({
            type: 'error',
            message: res.data.data
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.shipReport {
  margin-top: 20px;
  margin-left: 20px;
  .top {
    padding: 1.25rem 0.375rem;
    .el-input {
      width: 20%;
      margin-right: 1.25rem;
    }
  }
  .title {
    display: flex;
    justify-content: center;
    font-size: 20px;
    font-weight: 700;
  }
  .black {
    font-weight: 1000;
  }
}
</style>
