<!--
 * @Author: zhp
 * @Date: 2024-04-15 10:49:13
 * @LastEditTime: 2024-04-17 16:12:20
 * @LastEditors: zhp
 * @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;">
      <ButtonNav :menus="['碲化镉工厂', '铜铟镓硒工厂']" :button-mode="true" @change="currentMenu = $event">
      </ButtonNav>
      <el-form :model="listQuery" :inline="true" ref="dataForm" class="blueTip">
        <el-form-item label="时间维度" prop="reportTime">
          <el-select clearable v-model="timeSelect" 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="timeSelect === 'day'" label="时间范围" prop="reportTime">
          <el-date-picker v-model="listQuery.reportTime" type="datetimerange" range-separator="至"
            start-placeholder="开始日期" value-format="yyyy-MM-dd HH:mm:ss" @change="changeDayTime" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item v-show="timeSelect === 'week'" label="时间范围" prop="reportTime">
          <el-date-picker v-model="listQuery.reportTime[0]" type="week" format="yyyy 第 WW 周" placeholder="选择周"
            style="width: 180px" @change="onValueChange">
          </el-date-picker>
          至
          <el-date-picker v-model="listQuery.reportTime[1]" type="week" format="yyyy 第 WW 周" placeholder="选择周"
            style="width: 180px" @change="onValueChange">
          </el-date-picker>
          <span v-if="listQuery.reportTime[0] && listQuery.reportTime[1]" style="margin-left: 10px">
            {{ date1 }} 至 {{ date2 }}，共 {{ weekNum }} 周
          </span>
        </el-form-item> -->
        <el-form-item v-show="timeSelect === 'month'" label="时间范围" prop="reportTime">
          <el-date-picker 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="timeSelect === 'year'" 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="factoryId">
          <el-select v-model="listQuery.factoryId" placeholder="请选择工厂名称" multiple="true" clearable>
            <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 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>
      <!-- <search-bar :formConfigs="formConfig" ref="searchBarForm" @headBtnClick="buttonClick" /> -->
      <base-table :table-props="tableProps" :page="listQuery.pageNo" :limit="listQuery.pageSize"
        :table-data="tableData">
        <method-btn v-if="tableBtn.length" slot="handleBtn" label="操作" :width="120" fixed="right"
          :method-list="tableBtn" @clickBtn="handleClick" />
      </base-table>
      <add-or-update v-if="detailOrUpdateVisible" ref="detailOrUpdate" @refreshDataList="successSubmit" />

      <!-- <el-row :gutter="24"> -->
      <!-- <el-col :span="12" v-for="item in  dataList" :key="item.id"> -->
      <!-- <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> -->
      </el-row>
    </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 '../../core/mixins/code-filter';
// import { getGlassPage, exportGlasscExcel } from '@/api/report/glass';
// 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: {
        pageSize: 10,
        pageNo: 1,
        factoryId: null,
        total: 0,
        type: null,
        // reportType: 2,
        reportTime: []
      },
      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
      },
      mainFormConfig: [
      	{
          type: 'select',
          label: '工单',
          placeholder: '请选择工单',
          param: 'workOrderId',
          selectOptions: [],
        },
        // {
        // 	type: 'select',
        // 	label: '产线',
        // 	placeholder: '请选择产线',
        // 	param: 'lineId',
        // 	selectOptions: [],
        // },
        // 选项切换
        // {
        // 	type: 'select',
        // 	label: '时间类型',
        // 	param: 'dateFilterType',
        // 	defaultSelect: 0,
        // 	selectOptions: [
        // 		{ id: 0, name: '按时间段' },
        // 		{ id: 1, name: '按日期' },
        // 	],
        // 	index: 2,
        // 	extraOptions: [
        {
          // parent: 'dateFilterType',
          // 时间段选择
          type: 'datePicker',
          label: '时间段',
          // dateType: 'datetimerange',
          dateType: 'datetimerange',
          format: 'yyyy-MM-dd HH:mm:ss',
          valueFormat: 'yyyy-MM-ddTHH:mm:ss',
          rangeSeparator: '-',
          rangeSeparator: '-',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          param: 'recordTime',
        },
        // 		{
        // 			parent: 'dateFilterType',
        // 			// 日期选择
        // 			type: 'datePicker',
        // 			// label: '日期',
        // 			dateType: 'date',
        // 			placeholder: '选择日期',
        // 			format: 'yyyy-MM-dd',
        // 			valueFormat: 'yyyy-MM-dd',
        // 			param: 'timeday',
        // 		},
        // 	],
        // },
        {
          type:'button',
          btnName: '查询',
          name: 'search',
          color: 'primary',
        },
         {
          type:'separate'
        },
        // {
        //   type: this.$auth.hasPermi(
        //     'analysis:equipment:export'
        //   )
        //     ? 'separate'
        //     : '',
        // },
        {
          type:'button',
          btnName: '导出',
          name: 'export',
          color: 'warning',
        },
      ],
      formConfig: [
        {
          type: 'title',
          label: '成本管理',
        },
      ],
      timeList: [
        // {
        //   value: 'day',
        //   label: '日'
        // },
        // {
        //   value: 'week',
        //   label: '周'
        // },
        {
          value: 'month',
          label:'月'
        },
        {
          value: 'year',
          label: '年'
        }
      ],
      factoryList: [
        {
          name: '测试',
          id:1
        },
        {
          name: '测试2',
          id: 2
        }
      ],
      tableProps: [
        // {
        // 	prop: 'createTime',
        // 	label: '添加时间',
        // 	fixed: true,
        // 	width: 180,
        // 	filter: (val) => moment(val).format('yyyy-MM-DD HH:mm:ss'),
        // },
        {
          prop: 'userName',
          label: '日期',
        },
        {
          prop: 'nickName',
          label: '工厂名称',
        },
        {
          prop: 'type',
          label: '玻璃类型',
        },
        {
          prop: 'inNum',
          label: '投入数量',
        },
        {
          prop: 'putNum',
          label: '产出数量',
        },
        {
          prop: 'goodNum',
          label: '良品数量',
        },
        {
          prop: 'goodYelid',
          label: '良品率%',
        },
      ],
      timeSelect:'month',
      startTimeStamp:null, //开始时间
      endTimeStamp:null, //结束时间
      // date:'凯盛玻璃控股成员企业2024生产数据',
			// reportTime: '',
			startTimeStamp: '',
			endTimeStamp: '',
      tableData: [
        {
          userName: 'userName',
          nickName: '用户名',
          datas:'111111'
        },
        {
          userName: 'userName',
          nickName: '用户名',
          datas: '111111'
        },
        {
          userName: 'userName',
          nickName: '用户名',
          datas: '111111'
          // subcomponent: row
        }
      ],
			// proLineList: [],
			// all: {}
		};
  },
  computed: {
    weekNum() {
      return Math.round((this.listQuery.reportTime[1] - this.listQuery.reportTime[0]) / (24 * 60 * 60 * 1000 * 7)) + 1
    },
  },
	mounted() {
    this.getDict()
    // this.getCurrentYearFirst()
    // 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.reportTime[0] && e - this.listQuery.reportTime[0] > 10) {
        this.$message({
          message: '年份起止时间不能超过十年',
          type: 'warning'
        });
        // console.log();
      }
      // console.log(e);
    },
    onValueChange(picker, k) { // 选中近k周后触发的操作
      if (this.listQuery.reportTime[0] && this.listQuery.reportTime[1]) {
        console.log(this.listQuery.reportTime[0].getTime() - 24 * 60 * 60 * 1000)
        this.date1 = moment(this.listQuery.reportTime[0].getTime() - 24 * 60 * 60 * 1000).format('YYYY-MM-DD HH:mm:ss')
        // this.onValueChange()   // 这里为我们希望value改变时触发的方法
        this.date2 = moment(this.listQuery.reportTime[1].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'
          });
          // this.onValueChange()
        }
    }
    },
    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 = (new Date(this.listQuery.reportTime[1]).getTime() - new Date(this.listQuery.reportTime[0]).getTime()) / (24 * 3600 * 1000); if (numDays > 30) {
          this.$message({
            message: '时间范围不能超过30天',
            type: 'warning'
          });
          this.listQuery.reportTime = [];
        }
      } else {
      }
    },
    changeTime(value) {
      if (this.listQuery.reportTime) {
        const timeStamp = this.listQuery.reportTime[1].getMonth(); //标准时间转为时间戳，毫秒级别
        const fullyear = this.listQuery.reportTime[1].getFullYear()
        let days = 0
        switch (timeStamp) {
          case 0:
          case 2:
          case 4:
          case 6:
          case 7:
          case 9:
          case 11:
            days = 31
            break
          case 3:
          case 4:
          case 8:
          case 10:
            days = 30
            break
          case 1:
            if ((fullyear % 400 === 0) || (fullyear % 4 === 0 && fullyear % 100 !== 0)) {
              days = 29
            } else {
              days = 28
            }
            break
        }
        let startTime = moment(new Date(this.listQuery.reportTime[0]).setDate(1, 0, 0, 0)).format('YYYY-MM-DD HH:mm:ss')
        // this.startTimeStamp = this.timeFun(new Date(fullyear, timeStamp, 1, 7, 0, 1).getTime()); //开始时间
        let endTime = this.timeFun(new Date(fullyear, timeStamp, days).getTime()) + ' 23:59:59'; //结束时间
        // console.log(endTimeStamp);
        // let endTime = moment(this.listQuery.reportTime[1]).month(monthNum - 1).date(1).endOf("month").format("YYYY-MM-DD");
        // console.log(endTime);
        // console.log(moment(new Date(this.listQuery.reportTime[1]).setDate(31, 23, 59, 59)).format('YYYY-MM-DD HH:mm:ss'))
        // console.log(moment(new Date(this.listQuery.reportTime[1]).getTime()).format('YYYY-MM-DD HH:mm:ss'))

        // 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(endTime).getTime() - new Date(startTime).getTime()) / (24 * 3600 * 1000); if (numDays > 730) {
          this.$message({
            message: '时间范围不能超过24个月',
            type: 'warning'
          });
          this.listQuery.reportTime = [];
        } else {
          this.listQuery.reportTime[0] = startTime
          this.listQuery.reportTime[1] = endTime
        }
      } else {
        console.log(this.listQuery.reportTime[0])
      }
    },
    // handleTime() {
    //   this.$forceUpdate()
    //   // this.$nextTick(() => [

    //   // ])
    // },
    // 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
    // },
    // changeTime(val) {
    //   if (val) {
    //     // let timeStamp = val.getTime(); //标准时间转为时间戳，毫秒级别
    //     // this.endTimeStamp = this.timeFun(new Date(val.getFullYear(), 11, 31, 7, 0, 0).getTime()); //开始时间
    //     // this.startTimeStamp = this.timeFun(new Date(val.getFullYear(), 0, 1, 7, 0, 1).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 = []
    //   }
    // },
    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() {
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    format(shijianchuo) {
      //shijianchuo是整数，否则要parseInt转换
      var time = moment(new Date(shijianchuo)).format('YYYY-MM-DD HH:mm:ss')
      // console.log(time)
      // var y = time.getFullYear();
      // var m = time.getMonth() + 1;
      // var d = time.getDate();
      // var h = time.getHours();
      // var mm = time.getMinutes();
      // var s = time.getSeconds();
      return time
    },
		//时间戳转为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 };
      // /* 从表生成工作簿对象 */
      // 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: calc(100vh - 134px);
  overflow: auto;
}
</style>
