<!--
 * @Author: zhp
 * @Date: 2024-04-15 10:49:13
 * @LastEditTime: 2024-05-07 08:40:58
 * @LastEditors: zhp
 * @Description:
-->
<template>
  <div style="display: flex; flex-direction: column; min-height: calc(100vh - 96px - 31px)">
    <div ref="parentChartDiv" class="app-container" style="padding: 16px 24px 0;height;auto;flex-grow: 1;">
      <!-- <el-alert title="自定义 close-text" type="warning" close-text="知道了">
      </el-alert> -->
      <el-form :model="listQuery" :inline="true" ref="dataForm" class="blueTip">
        <el-form-item label="时间维度" prop="mode">
          <el-select clearable v-model="listQuery.mode" placeholder="请选择">
            <el-option v-for="item in timeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="listQuery.mode === 2" label="时间范围" prop="reportTime">
          <el-date-picker clearable v-model="listQuery.reportTime" type="monthrange" range-separator="至"
            start-placeholder="开始月份" end-placeholder="结束月份" @change="changeTime">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-show="listQuery.mode === 3" label="时间范围" prop="reportTime">
          <el-date-picker clearable v-model="listQuery.reportTime[0]" value-format="yyyy" type="year"
            placeholder="开始时间">
          </el-date-picker>
          ~
          <el-date-picker clearable v-model="listQuery.reportTime[1]" value-format="yyyy" type="year" placeholder="结束时间"
            @change="getYear">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="工厂名称" prop="factorys">
          <el-select clearable v-model="listQuery.factorys" placeholder="请选择工厂名称" multiple>
            <el-option v-for="item in factoryList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="玻璃类型" prop="type">
          <el-select v-model="listQuery.type" placeholder="请选择玻璃类型">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" size="small" @click="getDataList">查询</el-button>
          <el-button type="primary" size="small" plain @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
      <!-- <el-row style="height: 400px;"> -->
      <!-- <div style="height: auto;"> -->
      <line-chart class="epChart" ref="lineChart" style="width: 100%"></line-chart>
      <!-- </div> -->
      <!-- </el-row> -->
    </div>
    <div class="app-container" style="margin-top: 18px;flex-grow: 1; padding: 16px;">
      <search-bar :formConfigs="formConfig" ref="searchBarForm" @headBtnClick="buttonClick" />
      <base-table :table-props="tableProps" :page="listQuery.current" :limit="listQuery.size" :table-data="tableData">
      </base-table>
    </div>
    <!-- <inputTable :date="date" :data="tableData" :time="[startTimeStamp, endTimeStamp]" :sum="all"
      :type="listQuery.reportType" @refreshDataList="getDataList" /> -->
    <!-- <pagination
			:limit.sync="listQuery.pageSize"
			:page.sync="listQuery.pageNo"
			:total="listQuery.total"
			@pagination="getDataList" /> -->
  </div>
</template>

<script>
import { parseTime } from '@/mixins/code-filter';
import { getEpPage } from '@/api/greenest/index';
// import inputTable from './inputTable.vue';
import lineChart from './lineChart';
import moment from 'moment'
// import FileSaver from 'file-saver'
// import * as XLSX from 'xlsx'
export default {
  components: { lineChart },
	data() {
    return {
      listQuery: {
        current: 1,
        size: 10,
        factorys: [],
        mode: 2,
        beginTime: undefined,
        endTime: undefined,
        // total: 0,
        // type: null,
        // reportType: 2,
        reportTime: []
      },
      dynamicProps: [],
			urlOptions: {
				// getDataListURL: getGlassPage,
				// exportURL: exportGlasscExcel
      },
      formConfig: [
        {
          type: 'title',
          label: '环保管理',
        },
      ],
      timeList: [
        {
          value: 2,
          label:'月'
        },
        {
          value: 3,
          label: '年'
        }
      ],
      factoryList: [
        {
          id: 0,
          name: '瑞昌中建材光电材料有限公司'
        },
        {
          id: 1,
          name: '邯郸中建材光电材料有限公司'
        },
        {
          id: 2,
          name: '中建材株洲光电材料有限公司'
        },
        {
          id: 3,
          name: '佳木斯中建材光电材料有限公司'
        },
        {
          id: 4,
          name: '成都中建材光电材料有限公司'
        },
        {
          id: 5,
          name: '凯盛光伏材料有限公司'
        },
        {
          id: 6,
          name: '蚌埠兴科玻璃有限公司'
        },
      ],
      typeList: [
        {
          name: '芯片',
          id:0,
        },
        {
          name: '标准组件',
          id: 1,
        },
        {
          name: 'BIPV产品',
          id: 2,
        },
      ],
      tableProps: [],
      // startTimeStamp:null, //开始时间
      // endTimeStamp:null, //结束时间
      // date:'凯盛玻璃控股成员企业2024生产数据',
			// reportTime: '',
			// startTimeStamp: '',
			// endTimeStamp: '',
      tableData: [],
			// proLineList: [],
			// all: {}
		};
	},
	mounted() {
    this.getDict()
    // this.getCurrentYearFirst()
    // this.getDataList()
  },
  // computed: {
  //   tableProps() {
  //     return [
  //       {
  //         prop: 'createTime',
  //         label: '日期',
  //         filter: parseTime
  //       },
  //       ...this.dynamicProps,
  //     ];
  //   },
  // },
  methods: {
    buttonClick() {

    },
    getYear(e) {
      this.listQuery.beginTime = this.listQuery.reportTime ? new Date(new Date(new Date(this.listQuery.reportTime[0]).setMonth(0, 1)).setHours(0, 0, 0)).getTime() : undefined
      this.listQuery.endTime = this.listQuery.reportTime ? new Date(new Date(new Date(this.listQuery.reportTime[1]).setMonth(11, 31)).setHours(23,59,59)).getTime() : undefined
      if (this.listQuery.reportTime[0] && e - this.listQuery.reportTime[0] > 10) {
        this.$message({
          message: '年份起止时间不能超过十年',
          type: 'warning'
        });
        // console.log();
      }
      // console.log(e);
    },
    changeTime() {
      if (this.listQuery.reportTime) {
        this.listQuery.beginTime = this.listQuery.reportTime ? new Date(this.listQuery.reportTime[0]).getTime() : undefined
        this.listQuery.endTime = this.listQuery.reportTime ? new Date(this.listQuery.reportTime[1]).getTime() : undefined
        // this.createStartDate = moment(new Date(this.listQuery.reportTime[0]), 'yyyy-MM-dd hh:mm:ss');
        // this.createEndDate = moment(new Date(this.listQuery.reportTime[1]), 'yyyy-MM-dd hh:mm:ss');
        const numDays = (new Date(this.listQuery.reportTime[1]).getTime() - new Date(this.listQuery.reportTime[0]).getTime()) / (24 * 3600 * 1000); if (numDays > 730) {
          this.$message({
            message: '时间范围不能超过24个月',
            type: 'warning'
          });
          this.listQuery.reportTime = [];
          // this.createStartDate = '';
          // this.createEndDate = '';
        }
      } else {
        // this.createStartDate = '';
        // this.createEndDate = '';
      }
    },
    async getDict() {
      this.$refs.lineChart.initChart()
			// 产线列表
			// const res = await getCorePLList();
			// this.proLineList = res.data;
		},
    // 获取数据列表
    multipliedByHundred(str) {
      console.log(str);
      // console.log(str)
      if ( str != 0) {
        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() {
      // this.tableData = []
      // this.tabl

      const res = await getEpPage(this.listQuery)
      let arr =[
        {
          prop: 'createTime',
          label: '日期',
          // filter: parseTime
        },
        {
          prop: 'factory',
          label: '工厂名称',
          filter: (val) => ['瑞昌中建材光电材料有限公司', '邯郸中建材光电材料有限公司', '中建材株洲光电材料有限公司', '佳木斯中建材光电材料有限公司', '成都中建材光电材料有限公司', '凯盛光伏材料有限公司', '蚌埠兴科玻璃有限公司'][val]
        }
      ]
      // console.log(dataArr);
      // for (let i = 0; i < res.data.list.length-1; i++) {
      //   if (r[i].createTime != r[i + 1].createTime ) {
      //     this.data.a.push(r[i])
      //   }
      // }
      // console.log(res.data);
      // this.dynamicProps = []
      const dateList = []
      const processList = []
      const factoryList = []

      res.data.records.forEach(ele => {
        // 表头
        dateList.push(ele.environmentalProtectionName)
        // 列数
        processList.push(ele.createTime)
        factoryList.push(ele.factory)
      })
      this.dateProps = Array.from(new Set(dateList))
      // this.processArray = Array.from(new Set(processList))
      // this.factoryArray = Array.from(new Set(factoryList))
      // this.factoryArray.forEach(item => {
      //   const props =
      //   arr.push(props)
      // })
      // res.data.records.forEach(ele => {
      //   if (this.factoryArray.some(ele.factory) && this.factoryArray.some(ele.createTime)) {
      //     arr.push({

      //     })
      //   }
      //   // 表头
      //   // dateList.push(ele.environmentalProtectionName)
      //   // 列数
      //   // processList.push(ele.createTime)
      //   // factoryList.push(ele.factory)
      // })
      this.dateProps.forEach(item => {
        const props = {
          'prop': item,
          'label': item
        }
        arr.push(props)
      })
      this.tableProps = arr
      this.tableData = this.mergeGrade(res.data.records)
      console.log(this.tableData)
      // // 构造表格数据
      // this.total = this.processArray.length
      // this.processArray.forEach(process => {
      //   const listData = {
      //     'createTime': process,
      //     'factory':null
      //   }
      //   res.data.records.forEach((r,index) => {
      //     if (process === r.createTime) {
      //       // const temp = Object.keys(r).filter(keys => keys !== 'reportDate' && keys !== 'factory' && keys !== 'environmentalProtectionName' && keys !== 'id' && keys !== 'createTime')
      //       // const item = Object.keys(r).filter(keys => keys !== 'reportDate' && keys !== 'environmentalProtectionValue' && keys !== 'environmentalProtectionName' && keys !== 'id' && keys !== 'createTime')
      //       // console.log(r[item[0]]);
      //       listData[r.environmentalProtectionName] = r.environmentalProtectionValue
      //       listData.factory = r.factory
      //     }
      //   })
      //   console.log(listData);
      //   this.tableData.push(listData)
      // })
    },

   mergeGrade(grade) {
        if (!Array.isArray(grade)) return []
        const newGrade = []
        grade.forEach(item => {
          const index = newGrade.findIndex(subItem => subItem.factory === item.factory && subItem.createTime === item.createTime)
            if (index > -1) {
              newGrade[index][item.environmentalProtectionName] = item.environmentalProtectionValue
            } else {
                newGrade.push({
                  factory: item.factory,
                  createTime: item.groupTime,
                  [item.environmentalProtectionName]: item.environmentalProtectionValue
                    // grades: { [item.class]: item.grade }
                })
            }
        })
        return newGrade
    },
		/** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      // var xlsxParam = { raw: true };
      // /* 从表生成工作簿对象 */
      // import('xlsx').then(excel => {
      //   var wb = excel.utils.table_to_book(
      //     document.querySelector("#exportTable"),
      //     xlsxParam
      //   );
      //   /* 获取二进制字符串作为输出 */
      //   var wbout = excel.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;
      //   //do something......
      // })

    },
	},
};
</script>

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