<template>
  <div class="cobalt-month-wrap">
    <el-form
      :model="searchForm"
      :inline="true"
      label-width="75px"
      :rules="searchRules"
    >
      <el-form-item label="统计月份">
        <el-date-picker
          type="month"
          size="mini"
          v-model="searchForm.selectedMonth"
          @change="monthChange"
          style="width: 150px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="dataCollect"
          >采集</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="dataSearch"
          >重新查询</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="mini"
          @click="dataSave"
          :loading="saveFlag"
          >保存</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="mini"
          @click="printData"
          :loading="printFlag"
          >打印</el-button
        >
      </el-form-item>
    </el-form>
    <div class="data-wrap" id="colbat-data-wrap">
      <el-table
        id="excelTable"
        v-loading="dataLoading"
        ref="dataTable"
        border
        show-summary
        :summary-method="getSum"
        :data="productGroupData"
        highlight-current-row
      >
        <!-- <el-table-column
          type="index"
          label="NO"
          align="center"
        ></el-table-column> -->
        <el-table-column
          :show-overflow-tooltip="true"
          sortable
          prop="productName"
          label="产品名称"
          align="center"
        >
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          sortable
          prop="productNum"
          label="桶数"
          align="center"
        >
          <template slot-scope="{ row, $index }">
            <p
              v-show="!row.bucketFlag"
              @click="cellClick('bucketFlag', row, true, 'bucket' + $index)"
            >
              {{ row.productNum }}
            </p>
            <el-input
              v-show="row.bucketFlag"
              type="text"
              size="mini"
              v-focus
              :ref="'bucket' + $index"
              @keyup.enter.native="cellClick('bucketFlag', row, false)"
              @blur="cellClick('bucketFlag', row, false)"
              v-model="row.productNum"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          sortable
          prop="productWgt"
          label="重量/t"
          align="center"
        >
          <template slot-scope="{ row, $index }">
            <p
              v-show="!row.productFlag"
              @click="cellClick('productFlag', row, true, 'product' + $index)"
            >
              {{ row.productWgt }}
            </p>
            <el-input
              v-show="row.productFlag"
              type="text"
              size="mini"
              v-focus
              :ref="'product' + $index"
              @keyup.enter.native="cellClick('productFlag', row, false)"
              @blur="cellClick('productFlag', row, false)"
              v-model="row.productWgt"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-input
          type="textarea"
          :rows="3"
          style="width: 100%"
          v-model="dataMemo"
        ></el-input>
      </div>
      <div style="text-align:right; maring-right: 100px;">
        <p>计量员：{{userName}}</p>
      </div>
    </div>
  </div>
</template>
<script>
import { formatDate, getCookie } from '@/utils/util.js';
import moment from 'moment'
import {cookieUserId, cookieUserName} from '@/config/config.js'

export default {
  created () {
    this.userName = getCookie(cookieUserName)
    console.log(moment(formatDate(new Date(), 'yyyy-MM')).isSame('2021-08'))
    this.init();
  },
  mounted () {

  },
  data () {
    return {
      searchForm: {
        selectedMonth: formatDate(new Date(), 'yyyy-MM')
      },
      dataMemo: '',
      productGroupData: [],
      dataLoading: false,
      searchRules: {
        selectedMonth: [{ required: true, message: '统计月份不能为空', trigger: 'blur' }]
      },
      saveFlag: false,
      userName: '',
      printFlag: false,
      startDate: '',
      endDate: ''
    }
  },
  methods: {
    // 初始化
    init () {
      this.dataCollect();
    },
    // 汇总数据查询
    async dataCollect () {
      let startTime = ''
      let endTime = ''
      // 汇总查询时间段是否为空
      if (this.searchForm.selectedMonth === '') {
        return this.$message.error('统计月份不能为空')
      }
      let dateList = this.searchForm.selectedMonth.split('-')
      // 汇总查询时间段是否为特殊月份
      if (dateList[1] === '01') {
        // 汇总日期为1号到25号
        this.startDate = '1月1日'
        this.endDate = '1月25日'
        startTime = dateList[0] + '-01-01 00:00:00'
        endTime = dateList[0] + '-01-25 23:59:59'
      } else if (dateList[1] === '12') {
        this.startDate = '11月26'
        this.endDate = '12月31'
        // 汇总日期为11月26号到12月31日
        startTime = dateList[0] + '-11-26 00:00:00'
        endTime = dateList[0] + '-12-31 23:59:59'
      } else {
        this.startDate = dateList[1] - 0 - 1 + '' + '月' + '26日'
        this.endDate = dateList[1] + '' + '月' + '25日'
        // 汇总时间为上个月26到这个月25号
        startTime = dateList[0] + '-' + (/^0.*$/.test(dateList[1]) ? '0' : '') + (dateList[1] - 0 - 1 + '' + '-26 00:00:00')
        endTime = dateList[0] + '-' + dateList[1] + '-25 23:59:59'
      }
      const data = await this.axios.get(`pass/systemBase/v1/productreportmonthdatas/selectSumInfo?createTime1=${startTime}&createTime2=${endTime}`)
      console.log(data, '明细表汇总查询结果')
      if (data.status === 'succeed' && data.data.list) {
        // 将数据中的重量批量转换为吨
        data.data.list.forEach(item => {
          item.productWgt = this.floatComputed1(item.productWgt, 1000, '/') - 0
        })
        this.productGroupData = [...data.data.list]
        if (data.data.list[0]) {
          this.dataMemo = data.data.list[0].memo
        }
      } else {
        this.productGroupData = []
        this.$message.error(data.message)
      }
    },
    // 重新查询汇总表里面的数据
    async dataSearch () {
      // productreportmonthdatas
      const data = await this.axios.get(`pass/systemBase/v1/productreportmonthdatas/?reportDate=${this.searchForm.selectedMonth}`)
      if (data.status === 'succeed' && data.data.list) {
        // 将数据中的重量批量转换为吨
        data.data.list.forEach(item => {
          item.productWgt = this.floatComputed1(item.productWgt, 1000, '/') - 0
        })
        this.productGroupData = [...data.data.list]
        if (data.data.list[0]) {
          this.dataMemo = data.data.list[0].memo
        }
      } else {
        this.productGroupData = []
        this.$message.error(data.message)
      }
      console.log(data, '汇总表数据查询结果')
    },
    // 数据保存
    async dataSave () {
      this.saveFlag = true
      // 将表格中的数据组成参数传入
      console.log(this.productGroupData, '修改之后的数据')
      let paramList = [...this.productGroupData]
      // 循环添加备注
      paramList.forEach(item => {
        item.memo = this.dataMemo
        item.reportDate = this.searchForm.selectedMonth
        // 将数据中的重量转换成千克
        item.productWgt = this.floatComputed1(item.productWgt, 1000, '*') - 0
      })
      const data = await this.axios.post('pass/systemBase/v1/productreportmonthdatas/insertAndUpdateMonthData', [...paramList], { individualType: 'json' })
      if (data.status === 'succeed') {
        this.saveFlag = false
        this.dataSearch()
      } else {
        this.$message.error(data.message)
      }
    },
    monthChange (val) {
      if (val) {
        this.searchForm.selectedMonth = formatDate(val, 'yyyy-MM')
      }
    },
    cellClick (flag, row, val, refName) {
      this.$set(row, flag, val)
      // row[flag] = val
      console.log(row[flag])
      this.$nextTick(() => {
        if (refName && refName !== '') {
          let el = this.$refs[refName].$el.querySelector('input')
          this.$refs[refName].$el.querySelector('input').focus();
          this.$refs[refName].focus()
          el.focus();
        }
      })
    },
    floatComputed1 (arg1, arg2, sign) {
      if (!arg1) {
        arg1 = 0;
      }
      if (!arg2) {
        arg2 = 0;
      }
      let val1 = arg1 + '';
      let val2 = arg2 + '';
      let rate = 1;
      let rate1 = 1;
      let rate2 = 1;
      if (val1.indexOf('.') < 0) {
        rate1 = 0;
      } else {
        rate1 = val1.length - val1.indexOf('.') - 1;
      }
      if (val2.indexOf('.') < 0) {
        rate2 = 0;
      } else {
        rate2 = val2.length - val2.indexOf('.') - 1;
      }
      rate = rate2;
      val2 = val2.replace('.', '');
      val1 = val1.replace('.', '');
      if (rate1 > rate2) {
        rate = rate1;
        for (let i = 0; i < rate1 - rate2; i++) {
          val2 = val2 + '0'
        }
      } else {
        for (let i = 0; i <rate2 - rate1; i++) {
          val1 = val1 + '0';
        }
      }
      let rateNum = Math.pow(10, rate);
      if (sign === '-') {
        return (Number(val1) - Number(val2)) / rateNum
      }
      if (sign === '+') {
        return (Number(val1) + Number(val2)) / rateNum
      }
      if (sign === '*') {
        return (Number(val1) * Number(val2)) / (rateNum * rateNum)
      }
      if (sign === '/') { // 默认保留4位
        let num = 0;
        if (Number(val1) - 0 !== 0 && Number(val2) - 0 !== 0) {
          num = (Number(val1) / Number(val2)) + '';
          if (num.split('.').length > 0) {
            if (num[1].length > 4) {
              num = num.toFixed(8);
            }
          }
        }
        return num;
      }
      return null;
    },
    getSum ({ columns, data }) {
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          if (column.property === 'productWgt' | column.property === 'productNum') {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value) && value - 0 !== 0) {
                return this.floatComputed1(prev, curr, '+');
              } else {
                return prev;
              }
            }, 0);
          }
        }
      });
      return sums;
    },
    // 打印
    async printData () {
      this.printFlag = true
      let allWgt = 0, allNum = 0
      let year = new Date().getFullYear() + '年'
      // 表头
      let title = `<div style="text-align: center;padding-top: 10px;border: 1px solid #000; border-bottom: none;">钴月报${year}${this.startDate}-${year}${this.endDate}</div>`
      // 动态拼接打印片段
      let baseStr = `<div style="padding: 20px;"><div style='maring-top: 30px;'>${title}<table border=1 cellspacing='0' cellpadding='0' style='width: 100%;border: 1px solid #000;border-top: none;text-align:center;'><tr style="border: none;"><td style='border:none;border-top: 1px solid #000;border-right: 1px solid #000;'>产品名称</td><td style='border:none;border-top: 1px solid #000;border-right: 1px solid #000;'>桶数</td><td style='border:none;border-top: 1px solid #000;'>重量(t)</td></tr>`
      this.productGroupData.forEach(item => {
        baseStr += `<tr style="border: none;"><td style='border:none;border-top: 1px solid #000;border-right: 1px solid #000;'>${item.productName}</td><td style='border:none;border-top: 1px solid #000;border-right: 1px solid #000;'>${item.productNum}</td><td style='border:none;border-top: 1px solid #000;'>${item.productWgt}</td></tr>`
        allWgt = this.floatComputed1(item.productWgt, allWgt, '+')
        allNum = this.floatComputed1(item.productNum, allNum, '+')
      })

      // 添加合计行
      baseStr = baseStr + `<tr style="border: none;"><td style='border:none;border-top: 1px solid #000;border-right: 1px solid #000;'>合计</td><td style='border:none;border-top: 1px solid #000;border-right: 1px solid #000;'>${allNum}</td><td style='border:none;border-top: 1px solid #000;'>${allWgt}</td></tr>`
      baseStr = baseStr + '</table></div>' + `<div>备注：${this.dataMemo ? this.dataMemo : ''}</div><div style="text-align:right; maring-right: 100px;"><p>计量员：${this.userName}</p></div>`
      var iframe = document.createElement('iframe');
      document.body.appendChild(iframe);
      var doc = iframe.contentWindow.document;
      doc.body.style = 'margin: 0mm;'
      doc.write(baseStr);
      doc.close();
      iframe.contentWindow.focus();
      await iframe.contentWindow.document.execCommand('print');
      document.body.removeChild(iframe);
      this.printFlag = false
    }
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector('input').focus()
      },
      update: function (el) {
        el.querySelector('input').focus()
      }
    }
  }
}
</script>
<style>
.cobalt-month-wrap {
  padding: 10px;
}
</style>