<!--
 * @Author: zhp
 * @Date: 2024-04-15 10:49:13
 * @LastEditTime: 2024-05-22 15:25:11
 * @LastEditors: DY
 * @Description:
-->
<template>
  <div style="display: flex; flex-direction: column; min-height: calc(100vh - 96px - 31px)">
    <div class="app-container" style="padding: 16px 24px 0;height: auto; flex-grow: 1;">
      <el-form :model="listQuery" :inline="true" ref="dataForm" class="blueTip">
        <el-form-item label="时间维度" prop="date">
          <el-select size="small" clearable v-model="listQuery.date" 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.date === 0 || listQuery.date === ''" label="时间范围" prop="reportTime">
          <el-date-picker size="small" clearable v-model="listQuery.reportTime" type="datetimerange" range-separator="至"
            start-placeholder="开始日期" value-format="timestamp" @change="changeDayTime" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-show="listQuery.date === 1" label="时间范围" prop="reportTime">
          <el-date-picker size="small" clearable v-model="listQuery.start" type="week" format="yyyy 第 WW 周" placeholder="选择周"
            style="width: 180px" @change="onValueChange">
          </el-date-picker>
          至
          <el-date-picker size="small" clearable v-model="listQuery.end" type="week" format="yyyy 第 WW 周" placeholder="选择周"
            style="width: 180px" @change="onValueChange">
          </el-date-picker>
          <span v-if="listQuery.start && listQuery.end" style="margin-left: 10px">
            {{ date1 }} 至 {{ date2 }},共 {{ weekNum }} 周
          </span>
        </el-form-item>
        <el-form-item v-show="listQuery.date === 2" label="时间范围" prop="reportTime">
          <el-date-picker size="small" clearable v-model="listQuery.reportTime" type="monthrange" value-format="timestamp" range-separator="至"
            start-placeholder="开始月份" end-placeholder="结束月份" @change="changeTime">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-show="listQuery.date === 3" label="时间范围" prop="reportTime">
          <el-date-picker size="small" clearable v-model="listQuery.start" format="yyyy-MM-dd" value-format="timestamp" type="year"
            placeholder="开始时间">
          </el-date-picker>
          ~
          <el-date-picker size="small" clearable v-model="listQuery.end" format="yyyy-MM-dd" value-format="timestamp" type="year" placeholder="结束时间"
            @change="getYear">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="工厂名称" prop="factorys">
          <el-select size="small" 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 label="玻璃类型" prop="type">
          <el-select size="small" clearable 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>
    </div>
    <div class="app-container" style="margin-top: 8px;padding: 16px; height: auto; flex-grow: 1;">
      <!-- <el-row :gutter="24"> -->
      <!-- <el-col :span="12" v-for="item in  dataList" :key="item.id"> -->
      <search-bar :formConfigs="formConfig1" ref="searchBarForm1" style="margin-bottom: 0" />
      <line-chart class="yearChart" ref="lineChart" style="height: 40vh;width: 100%"></line-chart>
      <!-- </el-col> -->
      <!-- <el-col :span="12">
            <line-chart :id=" 'second' " class="yearChart" ref="lineChart" style="height: 40vh;width: 100%"></line-chart>
          </el-col> -->
    </div>
    <div class="app-container" style="margin-top: 8px;flex-grow: 1; height: auto; padding: 16px;">
      <search-bar :formConfigs="formConfig" ref="searchBarForm" @headBtnClick="buttonClick" style="margin-bottom: 0" />
      <base-table :table-props="tableProps" :page="listQuery.current" :limit="listQuery.size"
        :table-data="tableData">
        <method-btn v-if="tableBtn.length" slot="handleBtn" label="操作" :width="120" fixed="right"
          :method-list="tableBtn" @clickBtn="handleClick" />
      </base-table>
      <pagination
        :limit.sync="listQuery.size"
        :page.sync="listQuery.current"
        :total="listQuery.total"
        @pagination="getDataList"
      />
    </div>
    <add-or-update v-if="detailOrUpdateVisible" ref="detailOrUpdate" :date="listQuery.date" @refreshDataList="successSubmit" @destroy="detailOrUpdateVisible = false" />
    <!-- <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 '../../core/mixins/code-filter';
import { getProduceDataPage, exportOutPutExcel } from '@/api/produceData';
// import inputTable from './inputTable.vue';
import lineChart from './lineChart';
import moment from 'moment'
import ButtonNav from '@/components/ButtonNav'
import basicPage from '@/mixins/basic-page'
import AddOrUpdate from './add-or-updata';

// import FileSaver from 'file-saver'
// import * as XLSX from 'xlsx'
export default {
  components: { lineChart, ButtonNav, AddOrUpdate },
  mixins: [basicPage],
	data() {
    return {
      listQuery: {
        size: 20,
        current: 1,
        factorys: [],
        total: 0,
        date: 1,
        type:undefined,
        // reportType: 2,
        beginTime: undefined,
        endTime:undefined,
        reportTime: [],
        start: undefined,
        end: undefined
      },
      detailOrUpdateVisible:false,
      date1: undefined,
      date2: undefined,
      tableBtn: [
          {
            type: 'detail',
            btnName: '详情',
        },
        // {
        //     type: 'delete',
        //     btnName: '删除',
        //   },
      ].filter((v) => v),
      typeList: [
        {
          name: '芯片',
          id: 0,
        },
        {
          name: '标准组件',
          id: 1,
        },
        {
          name: 'BIPV产品',
          id: 2,
        },
      ],
      // weekNum: undefined,
      dataList: [
        {
          id:'first',
        },
         {
          id: 'second',
        },
         {
          id: 'third',
        },
         {
          id: 'fourth',
        },
         {
          id: 'fifth',
        },
         {
          id: 'sixth',
        },
      ],
			urlOptions: {
				// getDataListURL: getGlassPage,
				// exportURL: exportGlasscExcel
      },
      formConfig: [
        {
          type: 'title',
          label: '工厂信息',
        },
      ],
      formConfig1: [
        {
          type: 'title',
          label: '良品数量',
        },
      ],
      timeList: [
        {
          value: 0,
          label: '日'
        },
        {
          value: 1,
          label: '周'
        },
        {
          value: 2,
          label:'月'
        },
        {
          value: 3,
          label: '年'
        }
      ],
      factoryList: [
        {
          name: '瑞昌中建材光电材料有限公司',
          id: 0
        },
        {
          name: '邯郸中建材光电材料有限公司',
          id: 1
        },
        {
          name: '中建材株洲光电材料有限公司',
          id: 2
        },
        {
          name:  '佳木斯中建材光电材料有限公司',
          id: 3
        },
        {
          name:  '成都中建材光电材料有限公司',
          id: 4
        },
        {
          name:  '凯盛光伏材料有限公司',
          id: 5
        },
        {
          name:  '蚌埠兴科玻璃有限公司',
          id: 6
        }
      ],
      tableProps: [
        {
          prop: 'tableTime',
          label: '日期',
          minWidth: 100,
          showOverflowtooltip: true
        },
        {
          prop: 'factory',
          label: '工厂名称',
          filter: (val) => ['瑞昌中建材光电材料有限公司', '邯郸中建材光电材料有限公司', '中建材株洲光电材料有限公司', '佳木斯中建材光电材料有限公司', '成都中建材光电材料有限公司', '凯盛光伏材料有限公司', '蚌埠兴科玻璃有限公司'][val],
          minWidth: 200,
          showOverflowtooltip: true
        },
        {
          prop: 'glassType',
          label: '玻璃类型',
          filter: (val) => ['玻璃芯片', '标准组件', 'BIPV', '定制组件'][val]
        },
        {
          prop: 'inputNumber',
          label: '投入数量',
        },
        {
          prop: 'outputNumber',
          label: '产出数量',
        },
        {
          prop: 'goodNumber',
          label: '良品数量',
        },
        {
          prop: 'yieldRate',
          label: '良品率%',
        },
      ],
      tableData: [],
      xAxis: []
			// proLineList: [],
			// all: {}
		};
  },
  computed: {
    weekNum() {
      return Math.round((this.listQuery.end - this.listQuery.start) / (24 * 60 * 60 * 1000 * 7)) + 1
    },
  },
	mounted() {
    this.getDataList()
	},
  methods: {
    otherMethods(val) {
      this.detailOrUpdateVisible = true;
      this.addOrEditTitle = "详情";
      this.$nextTick(() => {
        this.$refs.detailOrUpdate.init(val.data.id);
      });
    },
    // buttonClick() {

    // },
    getYear(e) {
      if (this.listQuery.end - this.listQuery.start > 10*365*24*60*60*1000) {
        this.$message({
          message: '年份起止时间不能超过十年',
          type: 'warning'
        });
        this.listQuery.reportTime = []
        this.listQuery.start = undefined
        this.listQuery.end = undefined
        // console.log();
      } else {
        this.listQuery.beginTime = this.listQuery.start
        this.listQuery.endTime = this.listQuery.end
      }
      // console.log(e);
    },
    onValueChange(picker, k) { // 选中近k周后触发的操作
      // console.log(this.listQuery.reportTime[0], this.listQuery.reportTime[1])
      if (this.listQuery.start && this.listQuery.end) {
        console.log(this.listQuery.reportTime)
        this.date1 = moment(this.listQuery.start.getTime() - 24 * 60 * 60 * 1000).format('YYYY-MM-DD HH:mm:ss')
        this.date2 = moment(this.listQuery.end.getTime() + 5 * 24 * 60 * 60 * 1000).format('YYYY-MM-DD HH:mm:ss')
        const numDays = (new Date(this.date2).getTime() - new Date(this.date1).getTime()) / (24 * 3600 * 1000);
        if (numDays > 168) {
          console.log(numDays)
          this.$message({
            message: '周范围不能超过24周',
            type: 'warning'
          });
        } else {
          this.listQuery.beginTime = this.listQuery.start.getTime() - 24 * 60 * 60 * 1000
          this.listQuery.endTime = this.listQuery.end.getTime() + 5 * 24 * 60 * 60 * 1000
        }
      }
    },
    changeDayTime() {
      if (this.listQuery.reportTime) {
        // 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');
        console.log(this.listQuery.reportTime[1])
        const numDays = (this.listQuery.reportTime[1] - this.listQuery.reportTime[0]) / (24 * 3600 * 1000);
        if (numDays > 30) {
          this.$message({
            message: '时间范围不能超过30天',
            type: 'warning'
          });
          this.listQuery.reportTime = [];
        } else {
          this.listQuery.beginTime = this.listQuery.reportTime[0]
          this.listQuery.endTime = this.listQuery.reportTime[1]
        }
      } else {
      }
    },
    changeTime(value) {
      if (this.listQuery.reportTime) {
        const numDays = this.listQuery.reportTime[1] - this.listQuery.reportTime[0];
        if (numDays > 2*365*24*60*60*1000) {
          this.$message({
            message: '时间范围不能超过24个月',
            type: 'warning'
          });
          this.listQuery.reportTime = [];
        } else {
          this.listQuery.beginTime = this.listQuery.reportTime[0]
          this.listQuery.endTime = this.listQuery.reportTime[1]
        }
      } else {
        console.log(this.listQuery.reportTime[0])
      }
    },
    // async getDict() {
			// 产线列表
			// 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() {
      const res = await getProduceDataPage(this.listQuery)
      console.log(res)
      this.tableData = res.data.records
      this.tableData.forEach(item => {
        item.tableTime = item?.reportDate?.length > 0 ? item.reportDate[0] + '-' + item.reportDate[1] + '-' + item.reportDate[2] : '--'
      })
      this.listQuery.total = res.data.total
      this.buildChart(this.tableData)
    },
    buildChart(list) {
      const chartList = Object.groupBy(list, (item) => item.tableTime)
      this.xAxis = []
      this.seriesList = []
      for (const keyIndex in chartList) {
        // X坐标轴数据
        this.xAxis.push(keyIndex)
      }
      // y轴数据
      for (const y of this.factoryList) {
        // y: {name: , id: }
        const seriesItem = {
          name: y.name,
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
          data: Array(this.xAxis.length).fill(0)
        }
        for (const a in chartList) {
          for (const z of chartList[a]) {
            this.xAxis.forEach((item, index) => {
              if (z.factory === y.id && a === item) {
                seriesItem.data[index] = z.goodNumber
              }
            })
          }
        }
        this.seriesList.push(seriesItem)
      }
      this.$refs.lineChart.initChart(this.xAxis, this.seriesList)
    },
		buttonClick(val) {
			this.listQuery.reportTime = val.reportTime ? val.reportTime : undefined;
			switch (val.btnName) {
				case 'search':
					this.listQuery.current = 1;
					this.listQuery.size = 20;
					this.getDataList();
					break;
				case 'export':
					this.handleExport();
					break;
				default:
					console.log(val);
			}
		},
		/** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出生产数据?').then(() => {
        // 处理查询参数
        let params = {...this.listQuery};
        params.current = 1;
        params.size = 999;
        this.exportLoading = true;
        return exportOutPutExcel(params);
      }).then(response => {
        this.$download.excel(response, '生产数据.xls');
        this.exportLoading = false;
      }).catch(() => {});
      // 处理查询参数
      // 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 0px 0;
  background-color: #fff;
  border-radius: 4px;
  padding: 16px 16px 0;
  height: calc(100vh - 134px);
  overflow: auto;
}
</style>