<!--
 * @Author: zhp
 * @Date: 2024-04-15 10:49:13
 * @LastEditTime: 2024-07-01 11:49:38
 * @LastEditors: zhp
 * @Description:
-->
<template>
  <div style="display: flex; flex-direction: column; min-height: calc(100vh - 96px - 35px)">
    <div class="" style="height: auto;">
      <ButtonNav style="padding: 0;" :menus="['邯郸', '瑞昌']" :button-mode="true" @change="currentMenu = $event">
      </ButtonNav>
    </div>
    <div class="app-container" style="margin-top: 8px;flex-grow: 1; height: auto;">
      <el-form :model="listQuery" :inline="true" ref="dataForm" class="blueTip">
        <el-form-item label="时间维度" prop="type">
          <el-select size="small" clearable v-model="listQuery.type" placeholder="请选择" @change="handleChange">
            <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.type === 0 || listQuery.type === ''" label="时间范围" prop="reportTime">
          <el-date-picker size="small" clearable v-model="listQuery.reportTime" type="datetimerange" range-separator="至"
            start-placeholder="开始日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd" @change="changeDayTime"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-show="listQuery.type === 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" :picker-options="{'firstDayOfWeek': 1}">
          </el-date-picker>
          至
          <el-date-picker size="small" clearable v-model="listQuery.end" type="week" format="yyyy 第 WW 周"
            placeholder="选择周" style="width: 180px" @change="onValueChange" :picker-options="{'firstDayOfWeek': 1}">
          </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.type === 2" label="时间范围" prop="reportTime">
          <el-date-picker size="small" clearable v-model="listQuery.reportTime" type="monthrange"
            value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始月份" end-placeholder="结束月份"
            @change="changeTime">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-show="listQuery.type === 3" label="时间范围" prop="reportTime">
          <el-date-picker size="small" clearable v-model="listQuery.start" value-format="yyyy-MM-dd" type="year"
            placeholder="开始时间">
          </el-date-picker>
          ~
          <el-date-picker size="small" clearable v-model="listQuery.end" value-format="yyyy-MM-dd" type="year"
            placeholder="结束时间" @change="getYear">
          </el-date-picker>
        </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>
      <base-table :span-method="objectSpanMethod" :table-props="tableProps" :page="listQuery.pageNo"
        :limit="listQuery.pageSize" :table-data="tableData" :max-height="tableH">
      </base-table>
    </div>
  </div>
</template>

<script>
// import { parseTime } from '../../core/mixins/code-filter';
import { getComprehensiveDataPage, exportComprehensiveDataPage } from '@/api/report';
// import { getWorkOrderPage, exportExcel, getOverView } from '@/components/buttonNav'
// 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 { factoryList, factoryArray } from "@/utils/constants";
import { publicFormatter } from "@/utils/dict";

// import FileSaver from 'file-saver'
// import * as XLSX from 'xlsx'
export default {
  components: { ButtonNav },
  // mixins: [basicPage],
  data() {
    return {
      factoryList,
      factoryArray,
      currentMenu:'邯郸',
      listQuery: {
        pageNo: 1,
        pageSize: 999,
        // size: 10,
        // current: 1,
        factory: undefined,
        // total: 0,
        type: 2,
        startDate: undefined,
        endDate: undefined,
        start: undefined,
        end: undefined,
        reportTime: []
      },
      tableH: this.tableHeight(269),
      timeList: [
        {
          value: 0,
          label: '日'
        },
        {
          value: 1,
          label: '周'
        },
        {
          value: 2,
          label: '月'
        },
        {
          value: 3,
          label: '年'
        }
      ],
      detailOrUpdateVisible: false,
      tableBtn: [
        {
          type: 'detail',
          btnName: '详情',
        },
        // {
        //     type: 'delete',
        //     btnName: '删除',
        //   },
      ].filter((v) => v),
      typeList: [
        {
          name: '芯片',
          id: 0,
        },
        {
          name: '标准组件',
          id: 1,
        },
        {
          name: 'BIPV产品',
          id: 2,
        },
      ],
      otherProps:[],
      tableData: [],
      xAxis: [],
      // currentMenu:null,
      lineData: {},
      data: {}
      // proLineList: [],
      // all: {}
    };
  },
  watch: {
    currentMenu() {
      this.getDataList()
    },
  },
  computed: {
    weekNum() {
      return Math.round((this.end - this.start) / (24 * 60 * 60 * 1000 * 7)) + 1
    },
    tableProps() {
      return [
        {
          prop: 'type',
          label: '玻璃类型',
          fixed: true,
          // filter: (val) => factoryList[val],
          // minWidth: 200,
          // showOverflowtooltip: true
        },
        {
          prop: 'item',
          label: '科目/日期',
          fixed: true,
          // filter: (val) => ['玻璃芯片', '标准组件', 'BIPV', '定制组件'][val]
        },
        {
          prop: 'unit',
          label: '单位',
          fixed: true,
          // filter: publicFormatter('workorder_status')
          // filter: (val) => ['', '芯片工单', '组件类型', 'bipv类型'][val],
        },
        ...this.otherProps
      ]
    },
  },
  // created() {
  //   const currentMonth = new Date()
  //   this.listQuery.reportTime = [moment(currentMonth).format('yyyy-MM-dd HH:mm:ss'), moment(currentMonth).format('yyyy-MM-dd HH:mm:ss')]
  //   this.changeTime()
  // },
  mounted() {
    this.tableH = this.tableHeight(269);
    // this.getOverView()
    const today = new Date()
    const sevenDaysAgo = new Date(today.getTime() - (7 * 24 * 60 * 60 * 1000))
    this.listQuery.startDate = moment(sevenDaysAgo).format('yyyy-MM-DD')
    this.listQuery.endDate = moment(today).format('yyyy-MM-DD')
    this.listQuery.reportTime = [this.listQuery.startDate, this.listQuery.endDate]
    this.getDataList()
  },
  methods: {
    handleChange() {
      this.listQuery.reportTime = []
      this.listQuery.end = null
      this.listQuery.start = null
      this.listQuery.startDate = null
      this.listQuery.endDate = null
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      let spanOneArr = [], concatOne = 0;
      // let spanTwoArr = [], concatTwo = 0;

      this.tableData.map((item, index) => {
        // console.log(inde);
        if (index === 0) {
          spanOneArr.push(1);
        } else {
          //第一列需合并相同内容的判断条件
          if (item.type === this.tableData[index - 1].type) {
            spanOneArr[concatOne] += 1;
            spanOneArr.push(0);
          } else {
            spanOneArr.push(1);
            concatOne = index;
          };
        }
      });

      if (columnIndex === 1) {
        const _row = spanOneArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    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.startDate = this.listQuery.start
        this.listQuery.endDate = this.listQuery.end
      }
      if (!this.listQuery.start && !this.listQuery.end) {
        this.listQuery.startDate = undefined
        this.listQuery.endDate = undefined
      }
      // 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.startDate = moment(this.listQuery.start.getTime() - 24 * 60 * 60 * 1000).format('YYYY-MM-DD')
          this.listQuery.endDate = moment(this.listQuery.end.getTime() + 5 * 24 * 60 * 60 * 1000).format('YYYY-MM-DD')
        }
      }
      if (!this.listQuery.start && !this.listQuery.end) {
        this.listQuery.startDate = undefined
        this.listQuery.endDate = undefined
      }
    },
    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.startDate = this.listQuery.reportTime[0]
          this.listQuery.endDate = this.listQuery.reportTime[1]
        }
      } else {
        this.listQuery.startDate = undefined
        this.listQuery.endDate = undefined
      }
    },
    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.startDate = this.listQuery.reportTime[0]
          this.listQuery.endDate = this.listQuery.reportTime[1]
        }
      } else {
        this.listQuery.startDate = undefined
        this.listQuery.endDate = undefined
      }
    },
    async getDataList() {
      if (!this.listQuery.startDate && !this.listQuery.endDate) {
        return this.$message('请选择起止时间')
      }
      if (!this.listQuery.type) {
        return this.$message('请选择时间维度')
      }
      this.otherProps = []
      let arr  = []
      this.currentMenu === '邯郸' ? arr.push(1) : arr.push(0)
      this.listQuery.factory = arr
      const res = await getComprehensiveDataPage(this.listQuery)
      // this.tableData = res.data.list
      let dataArr = [{
        type: '芯片',
        item: 'FTO投入',
        unit: '片'
      },
      {
        type: '芯片',
        item: '芯片产量',
        unit: '片'
        }, {
        type: '芯片',
          item: '芯片平均功率',
          unit: 'W'
        },
        {
          type: '芯片',
          item: '芯片良率',
          unit: '%'
        }, {
          type: '芯片',
          item: '芯片产量',
          unit: '片'
        }, {
          type: '芯片',
          item: '芯片总功率',
          unit: 'MW'
        }, {
          type: '芯片',
          item: 'CSS稼动率',
          unit: '%'
        }, {
          type: '芯片',
          item: '芯片段OEE',
          unit: '%'
        }, {
          type: '芯片',
          item: '芯片产能利用率',
          unit: '%'
        }, {
          type: '芯片',
          item: '芯片人均产量',
          unit: '片/人'
        }, {
          type: '芯片',
          item: '芯片BOM',
          unit: '元/片'
        }, {
          type: '标准组件',
          item: '标准组件产量',
          unit: '片'
        }, {
          type: '标准组件',
          item: '标准组件平均功率',
          unit: 'W'
        }, {
          type: '标准组件',
          item: '标准组件良率',
          unit: '%'
        }, {
          type: '标准组件',
          item: '标准组件总功率',
          unit: 'MW'
        }, {
          type: '标准组件',
          item: '封装线OEE',
          unit: '%'
        },
        {
          type: '标准组件',
          item: '封装线产能利用率',
          unit: '%'
        },
        {
          type: '标准组件',
          item: '标准组件人均产量',
          unit: '片/人'
        },
        {
          type: '标准组件',
          item: '封装BOM',
          unit: '元/片'
        },
        {
          type: 'BIPV',
          item: '芯片使用量',
          unit: '%'
        },
        {
          type: 'BIPV',
          item: 'BIPV产量',
          unit: 'm2'
        },
        {
          type: 'BIPV',
          item: '芯片使用率',
          unit: '%'
        },
          {
          type: 'BIPV',
          item: '人均产量',
          unit: 'm2/人'
        },
        {
          type: 'BIPV',
          item: 'OEM及委外材料成本',
          unit: '元/片'
        },
        {
          type: 'BIPV',
          item: '内部材料成本',
          unit: '元/片'
        },
        {
          type: 'BIPV',
          item: '综合材料成本',
          unit: '元/片'
        },
      ]
      res.data.forEach((ele, index) => {
        let i = index + 1
        // this.chartMsg.xData.push(ele.titleValue)
        this.otherProps.push({
          label: ele.titleValue,
          prop: 'value' + i
        })
      })
      console.log(this.otherProps)
      res.data.forEach((item, index) => {
        let i = index + 1
        let m = 'value' + i
        // ele.productYieldDataVOList.forEach((item) => {
         dataArr[0]['' + m + ''] = item.ftoInput
          // dataArr[0].factory = item.factory === 1 ? '邯郸' : '瑞昌'
          // dataArr[1].factory = item.factory === 1 ? '邯郸' : '瑞昌'
          // dataArr[2].factory = item.factory === 1 ? '邯郸' : '瑞昌'
        // dataArr[3].factory = item.factory === 1 ? '邯郸' : '瑞昌'
          dataArr[1]['' + m + ''] = item.chipInput
          dataArr[2]['' + m + ''] = item.chipYield
          dataArr[3]['' + m + ''] = item.chipYieldRate
          dataArr[4]['' + m + ''] = item.chipAveragePower
          dataArr[5]['' + m + ''] = item.chipTotalPower
          dataArr[6]['' + m + ''] = item.chipCssMarriageRate
          dataArr[7]['' + m + ''] = item.chipOee
          dataArr[8]['' + m + ''] = item.chipCapacityUtilizationRate
          dataArr[9]['' + m + ''] = item.chipAnnualAverageProduction
          dataArr[10]['' + m + ''] = item.chipBom
          dataArr[11]['' + m + ''] = item.componentYield
          dataArr[12]['' + m + ''] = item.componentAveragePower
          dataArr[13]['' + m + ''] = item.componentYieldRate
          dataArr[14]['' + m + ''] = item.componentTotalPower
          dataArr[15]['' + m + ''] = item.componentOee
          dataArr[16]['' + m + ''] = item.componentCapacityUtilizationRate
          dataArr[17]['' + m + ''] = item.componentAnnualAverageProduction
          dataArr[18]['' + m + ''] = item.componentBom
          dataArr[19]['' + m + ''] = item.bipvChipUsage
          dataArr[20]['' + m + ''] = item.bipvProductOutput
          dataArr[21]['' + m + ''] = item.bipvChipUtilizationRate
          dataArr[22]['' + m + ''] = item.bipvAnnualAverageProduction
          dataArr[23]['' + m + ''] = item.bipvOeeMaterialCost
          dataArr[24]['' + m + ''] = item.bipvInsideMaterialCost
          dataArr[25]['' + m + ''] = item.bipvComprehensiveMaterialCost

        // })
        // ele.titleValue
        // .push({
        //   label: ele.titleValue,
        //   props: 'value' + index + 1,
        // })
      })
      console.log(dataArr);
      if (res.data.length === 0) {
        this.tableData = []
      } else {
        if (this.currentMenu != '瑞昌') {
          this.tableData = dataArr
        } else {
          this.tableData = dataArr.filter(function (item) {
            return item.type !== "BIPV"
          });
        }
      }
    },
    buttonClick(val) {
      this.listQuery.factorys = val.factory?.length > 0 ? val.factory : undefined
      // this.listQuery.orderStatus = val.orderStatus?.length > 0 ? val.orderStatus : undefined
      // this.listQuery.time = val.timeSlot?.length > 0 ? val.timeSlot : undefined
      switch (val.btnName) {
        case 'search':
          // this.listQuery.pageNo = 1;
          // this.listQuery.pageSize = 20;
          if (this.listQuery.time) {
            // this.getDataList();
          } else {
            this.$message.warning('请选择时间范围！')
          }
          break;
        case 'export':
          if (this.listQuery.time) {
            this.handleExport();
          } else {
            this.$message.warning('请选择时间范围！')
          }
          break;
        default:
          console.log(val);
      }
    },
    /** 导出按钮操作 */
    handleExport() {

      let fileName = "综合数据.xls";
      exportComprehensiveDataPage(this.listQuery)
        .then((response) => {
          this.$download.excel(response, fileName);
          this.$message.success("导出成功");
        })
        .catch(() => { });
      // this.$modal.confirm('是否确认导出工单数据?').then(() => {
      //   // 处理查询参数
      //   // let params = {...this.listQuery};
      //   // params.current = 1;
      //   // params.size = 999;
      //   this.exportLoading = true;
      //   return exportExcel({
      //     factorys: this.listQuery.factorys,
      //     orderStatus: this.listQuery.orderStatus,
      //     time: this.listQuery.time
      //   });
      // }).then(response => {
      //   this.$download.excel(response, '工单数据.xls');
      //   this.exportLoading = false;
      // }).catch(() => { })
    },
  },
};
</script>

<style scoped>
/* .blueTip { */
/* padding-bottom: 10px; */
/* } */
/* .blueTi */
.view {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex: 1;
}

.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;
}
.noBack{
  background-color:black;
}
</style>
