<template>
  <div class="app-container">
    <div>
      <el-form :model="listQuery" :inline="true" ref="dataForm" class="blueTip">
        <el-form-item label="年" prop="reportTime">
          <el-date-picker v-model="reportTime" type="year" size="small" @change="changeTime"
            :picker-options="{firstDayOfWeek: 1}" :format="'yyyy 年' + '\u3000' + startTimeStamp + '-' + endTimeStamp"
            style="width: 350px" placeholder="选择年">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button v-if="this.$auth.hasPermi('report:glass-year:query')" type="primary" size="small"
            @click="getDataList">查询</el-button>
          <el-button v-if="this.$auth.hasPermi('report:glass-year:export')" type="primary" size="small" plain
            @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <inputTable :date="date" :data="tableData" :time="[startTimeStamp, endTimeStamp]" :sum="all"
      :type="listQuery.reportType" @refreshDataList="getDataList" />
  </div>
</template>

<script>
import { parseTime } from '../../core/mixins/code-filter';
import { getGlassPage, exportGlasscExcel } from '@/api/report/glass';
import inputTable from './inputTable.vue';
import { getCorePLList } from '@/api/base/coreProductionLine';
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
export default {
	components: { inputTable },
	data() {
		return {
			urlOptions: {
				getDataListURL: getGlassPage,
				exportURL: exportGlasscExcel
			},
			listQuery: {
				pageSize: 10,
				pageNo: 1,
				total: 0,
				reportType: 5,
				reportTime: []
      },
      date: '许昌安彩年原片生产汇总',
			reportTime: '',
			startTimeStamp: '',
			endTimeStamp: '',
			tableData: [],
			proLineList: [],
			all: {},
		};
	},
  created() {
		// this.getDict()
  },
  mounted () {
    this.getCurrentYearFirst()
    this.getDataList()
      ;
  },
  methods: {
    getCurrentYearFirst() {
      let date = new Date();
      date.setDate(1);
      date.setMonth(0);
      this.reportTime = date;
      this.startTimeStamp = this.timeFun(new Date(new Date().getFullYear(), 0, 1,7,0,1).getTime()); //开始时间
      this.endTimeStamp = this.timeFun(new Date(new Date().getFullYear(), 11, 31, 7, 0, 0).getTime()); //结束时间
      this.listQuery.reportTime[0] = parseTime(new Date(new Date().getFullYear(), 0, 1, 7, 0, 1).getTime()) //+ ' 00:00:00' //new Date(this.startTimeStamp + ' 00:00:00').getTime() / 1000
      this.listQuery.reportTime[1] = parseTime(new Date(new Date().getFullYear(), 11, 31, 7, 0, 0).getTime()) //+ ' 23:59:59' //new Date(this.endTimeStamp + ' 23:59:59').getTime() / 100
    },
		async getDict() {
			// 产线列表
			const res = await getCorePLList();
			this.proLineList = res.data;
    },
    multipliedByHundred(str) {
      if (str) {
        let floatVal = parseFloat(str);
        if (isNaN(floatVal)) {
          return 0;
        }
        floatVal = Math.round(str * 10000) / 100;
        let strVal = floatVal.toString();
        let searchVal = strVal.indexOf('.');
        if (searchVal < 0) {
          searchVal = strVal.length;
          strVal += '.';
        }
        while (strVal.length <= searchVal + 2) {
          strVal += '0';
        }
        return parseFloat(strVal);
      }

    },
		// 获取数据列表
    async getDataList() {
      const res = await getCorePLList()
      this.proLineList = res.data;
      this.dataListLoading = true;
      if (this.listQuery.reportTime.length == 0) {
        this.$message({
          message: '请选择时间',
          type: 'warning'
        })
        return false
      }
      await this.urlOptions.getDataListURL(this.listQuery).then(res => {
        res.data.forEach((ele, index) => {
          if (ele.det === false) {
            res.data[index].lineName = '合计'
            this.remark = res.data[index].remark
            res.data[index].dailyOutputTrend = res.data[index].dailyOutputTrend && res.data[index].dailyOutputTrend != 0 ? this.multipliedByHundred(res.data[index].dailyOutputTrend) + '%' : res.data[index].dailyOutputTrend == 0 ? 0 : null
            res.data[index].originalGlassStatisticsTrend = res.data[index].dailyOutputTrend && res.data[index].originalGlassStatisticsTrend != 0 ? this.multipliedByHundred(res.data[index].originalGlassStatisticsTrend) + '%' : res.data[index].originalGlassStatisticsTrend == 0 ? 0 : null
            res.data[index].actualProductTrend = res.data[index].dailyOutputTrend && res.data[index].actualProductTrend != 0 ? this.multipliedByHundred(res.data[index].actualProductTrend) + '%' : res.data[index].actualProductTrend == 0 ? 0 : null
            res.data[index].originalGlassPassTrend = res.data[index].dailyOutputTrend && res.data[index].originalGlassPassTrend != 0 ? this.multipliedByHundred(res.data[index].originalGlassPassTrend) + '%' : res.data[index].originalGlassPassTrend == 0 ? 0 : null
          }
        })
        res.data.forEach(item => {
          this.proLineList.forEach(it => {
            if (item.lineId === it.id) {
              console.log(item)
              item.lineName = it.name
              console.log(item.originalGlassStatisticsTrend);
              // if (!item.dailyOutputTrend) {
              //   item.dailyOutputTrend = this.multipliedByHundred(item.dailyOutputTrend) + '%'
              // } else {
              //   item.dailyOutputTrend = null
              // }
              item.dailyOutputTrend = item.dailyOutputTrend && item.dailyOutputTrend != 0 ? this.multipliedByHundred(item.dailyOutputTrend) + '%' : item.dailyOutputTrend == 0 ? 0 : null
              item.originalGlassStatisticsTrend = item.originalGlassStatisticsTrend && item.originalGlassStatisticsTrend != 0 ? this.multipliedByHundred(item.originalGlassStatisticsTrend) + '%' : item.originalGlassStatisticsTrend == 0 ? 0 : null
              item.actualProductTrend = item.actualProductTrend && item.actualProductTrend != 0 ? this.multipliedByHundred(item.actualProductTrend) + '%' : item.actualProductTrend == 0 ? 0 : null
              item.originalGlassPassTrend = item.originalGlassPassTrend && item.originalGlassPassTrend != 0 ? this.multipliedByHundred(item.originalGlassPassTrend) + '%' : item.originalGlassPassTrend == 0 ? 0 : null
            }
          })
        })
        this.tableData = res.data
        // this.tableData = response.data.filter(item => {
        // 	this.proLineList.forEach(it => {
        //     if (item.lineId === it.id) {
        //       item.lineName = it.name

        // 		}
        // 	})
        // if (item.det === false) {
        // 	this.all = {
        // 		id: item.id,
        // 		remark: item.remark
        // 	}
        // }
        // return item.det === true
        // });
        this.listQuery.total = res.data.length;
        this.dataListLoading = false;
      });
    },
		changeTime(val) {
			if(val) {
					// let timeStamp = val.getTime(); //标准时间转为时间戳,毫秒级别
        this.startTimeStamp = this.timeFun(new Date(val.getFullYear(), 0, 1, 7, 0, 1).getTime()); //开始时间
        this.endTimeStamp = this.timeFun(new Date(val.getFullYear(), 11, 31, 7, 0, 0).getTime()); //结束时间
        this.listQuery.reportTime[0] = parseTime(new Date(val.getFullYear(), 0, 1, 7, 0, 1).getTime()) //+ ' 00:00:00' //new Date(this.startTimeStamp + ' 00:00:00').getTime() / 1000
        this.listQuery.reportTime[1] = parseTime(new Date(val.getFullYear(), 11, 31, 7, 0, 0).getTime()) //+ ' 23:59:59' //new Date(this.endTimeStamp + ' 23:59:59').getTime() / 1000
			} else {
					this.listQuery.reportTime = []
			}
		},

		//时间戳转为yy-mm-dd hh:mm:ss
		timeFun(unixtimestamp) {
				var unixtimestamp = new Date(unixtimestamp);
				var year = 1900 + unixtimestamp.getYear();
				var month = "0" + (unixtimestamp.getMonth() + 1);
				var date = "0" + unixtimestamp.getDate();
				return year + "-" + month.substring(month.length - 2, month.length) + "-" + date.substring(date.length - 2, date.length)
		},
		buttonClick(val) {
			this.listQuery.reportTime = val.reportTime ? val.reportTime : undefined;
			switch (val.btnName) {
				case 'search':
					this.listQuery.pageNo = 1;
					this.listQuery.pageSize = 10;
					this.getDataList();
					break;
				case 'export':
					this.handleExport();
					break;
				default:
					console.log(val);
			}
		},
		/** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      var xlsxParam = { raw: true };
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(
        document.querySelector("#exportTable"),
        xlsxParam
      );
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "许昌安彩年原片生产汇总.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    }
	},
};
</script>

<style scoped>
/* .blueTip { */
	/* padding-bottom: 10px; */
/* } */
.blueTip::before{
  display: inline-block;
  content: '';
  width: 4px;
  height: 18px;
  background: #0B58FF;
  border-radius: 1px;
  margin-right: 8PX;
  margin-top: 8px;
}
</style>