<!--
 * @Author: zhp
 * @Date: 2024-04-18 10:01:33
 * @LastEditTime: 2024-04-24 09:34:36
 * @LastEditors: zhp
 * @Description:
-->
<template>
  <div class="app-container">
    <search-bar :formConfigs="formConfig" ref="searchBarForm" @headBtnClick="buttonClick" />
    <el-table :header-cell-style="{
      background: '#F2F4F9',
      color: '#606266'
    }" class="baseTable" :max-height="tableH" id="exportTable" :data="tableData" style="width: 100%">
      <el-table-column v-for="item in tableProps" :prop="item.prop" :label="item.label" align="center">
        <el-table-column v-for="it in item.children" :prop="it.prop" :label="it.label" align="center">
        </el-table-column>
      </el-table-column>
    </el-table>
    <!-- <pagination :limit.sync="listQuery.pageSize" :page.sync="listQuery.pageNo" :total="listQuery.total"
      @pagination="getDataList" /> -->
    <!-- <base-dialog
			:dialogTitle="addOrEditTitle"
			:dialogVisible="addOrUpdateVisible"
			@cancel="handleCancel"
			@confirm="handleConfirm"
			:before-close="handleCancel"
			width="30%"> -->
    <!-- <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList" /> -->
    <!-- </base-dialog> -->
  </div>
</template>

<script>
// import AddOrUpdate from './add-or-updata';
// import basicPage from '../../../core/mixins/basic-page';
// import { parseTime } from '../../../core/mixins/code-filter';
import {
  getOriginalLineDataList,
  getCuttingReportDataList
} from '@/api/report/qcReport';
import tableHeightMixin from '@/mixins/lb/tableHeightMixin';
import FileSaver from 'file-saver'
import { parseTime } from '../../../core/mixins/code-filter';
// import { getList, } from "@/api/base/qualityScrapType";
const tableProps = [
  // {
  //   prop: 'createTime',
  //   label: '添加时间',
  //   filter: parseTime
  // },
  {
    prop: '',
    label: '切割堆垛日报',
    children:[
      {
        prop: 'lineName',
        label: '产线'
      },
      {
        prop: 'className',
        label: '班组'
      },
      {
        prop: 'groupName',
        label: '班次'
      },
      {
        prop: 'size',
        label: '规格 mm 长*宽'
      },
      {
        prop: 'thickness',
        label: '厚度mm'
      },
      {
        prop: 'glassCode',
        label: '周转编号',
      },
      {
        prop: 'stackingType',
        label: '堆垛方式',
        // filter: (val) =>
        //   val != null ? ['集装架', '堵头箱'][val] : '',
        // filter: ((val) => { val == 1 ? '集装架' : '堵头箱' }),
      },
      {
        prop: 'pieces',
        label: '片数',
      },
      {
        prop: 'originCode',
        label: '堆垛工位',
      },
      {
        prop: 'endTime',
        label: '堆垛时间',
      },
      {
        prop: 'dusting',
        label: '喷粉情况',
      },
      {
        prop: 'palletNumber',
        label: '集装架号',
      },
      {
        prop: 'remark',
        label: '备注',
      }
    ]
  }
];

export default {
  mixins: [tableHeightMixin],
  data() {
    return {
      urlOptions: {
        getDataListURL: getCuttingReportDataList,
        // deleteURL: deleteQualityHotMaterial,
        // exportURL: exportFactoryExcel,
      },
      tableProps,
      tableData: [],
      mergeArr: [],//记录合并行数
      pos: 0,
      listQuery: {
        startTime: undefined,
        endTime: undefined,
        lineId: null,
      },
      formConfig: [
        // {
        // 	type: 'input',
        //   label: '报废原因',
        //   placeholder: '报废原因',
        //   param: 'content',
        // },
        // {
        //   type: 'select',
        //   label: '原料名称',
        //   selectOptions: [],
        //   labelField: 'name',
        //   valueField: 'id',
        //   param: 'materialId',
        //   filterable: true
        // },
        {
          type: 'datePicker',
          label: '时间段',
          dateType: 'daterange',
          format: 'yyyy-MM-dd HH:mm:ss',
          valueFormat: "timestamp",
          rangeSeparator: '-',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          param: 'checkTime',
          defaultSelect: [Date.now() - 24 * 60 * 60 - 1000, Date.now()],
          width: 350
        },
        {
          type: 'select',
          label: '产线',
          selectOptions: [],
          labelField: 'name',
          valueField: 'id',
          param: 'lineId',
          filterable: true
        },
        {
          type: 'button',
          btnName: '查询',
          name: 'search',
          color: 'primary',
        },
        // {
        //   type: this.$auth.hasPermi('base:quality-hot-material:create') ? 'separate' : '',
        //   // type: 'separate',
        // },
        {
          type: 'button',
          btnName: '导出',
          name: 'export',
          color: 'success',
          plain: true
        },
      ],
    };
  },
  components: {
    // AddOrUpdate,
  },
  created() { },
  mounted() {
    // this.formConfig[1].defaultSelect[]
    this.listQuery.startTime = this.formConfig[0].defaultSelect[0]
    this.listQuery.endTime = this.formConfig[0].defaultSelect[1]
    // this.formConfig[0].defaultSelect[0] = Date.now()-24*60*60-1000
    this.getDataList()
    this.getDict()
    // this.getSpanArr(this.tableData)
    // this.getDict();
  },
  methods: {
    async getDict() {
      const res = await getOriginalLineDataList()
      console.log(res)
      this.formConfig[1].selectOptions = res.data
    },
    // getSummaries(param) {
    //   console.log(columns)

    //   const { columns, data } = param;
    //   const sums = [];
    //   columns.forEach((column, index) => {
    //     if (index === 0) {
    //       sums[index] = '合计';
    //       return;
    //     }
    //     const values = data.map(item => Number(item[column.property]));
    //     // const data = data.map(item => !Number(item[column.property]));
    //     if (!values.every(value => isNaN(value))) {
    //       sums[index] = values.reduce((prev, curr) => {
    //         const value = Number(curr);
    //         if (!isNaN(value)) {
    //           return prev + curr;
    //         } else {
    //           return prev;
    //         }
    //       }, 0);
    //       sums[index] += ' ';
    //     } else {
    //       sums[index] = '-';
    //     }
    //   });

    //   return sums;
    // },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      let spanOneArr = [], concatOne = 0;
      this.tableData.map((item, index) => {
        if (index === 0) {
          spanOneArr.push(1);
        } else {
          //第一列需合并相同内容的判断条件
          if (item.lineName === this.tableData[index - 1].lineName) {
            spanOneArr[concatOne] += 1;
            spanOneArr.push(0);
          } else {
            spanOneArr.push(1);
            concatOne = index;
          };
        }
      });

      if (columnIndex === 0) {
        const _row = spanOneArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    handleExport() {
      // 处理查询参数
      console.log(this.$refs);
      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......
      })

    },
    // otherMethods(val) {
    //   if (val.type === 'detail') {
    //     this.addOrUpdateVisible = true;
    //     this.addOrEditTitle = "详情";
    //     this.$nextTick(() => {
    //       this.$refs.addOrUpdate.init(val.data.id, true);
    //     });
    //   }
    // },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      // this.listQuery.startTime = '1711095616000';
      // this.listQuery.endTime = '1711183743000';
      this.urlOptions.getDataListURL(this.listQuery).then(response => {
        // this.getSpanArr(this.tableData)
        // response.data.forEach((ele) => {
        //   console.log(ele.size.substring(2, ele.size.length - 2))
        //   // console.log(Object.prototype.toString.call(ele.size))
        //   // // if (Object.prototype.toString.call(ele.size) === Array) {
        //   //   console.log(11111)
        //   //   console.log();
        //   // }
        // })
        this.tableData = response.data.map((ele) => {
          return {
            lineName: ele.lineName,
            className: ele.className,
            groupName: ele.groupName,
            size: ele.size,
            thickness: ele.thickness,
            glassCode: ele.glassCode,
            stackingType: ele.stackingType == 1 ? '集装架' : '堵头箱',
            pieces: ele.pieces,
            originCode: ele.originCode,
            endTime: parseTime(ele.endTime),
            dusting: ele.dusting,
            palletNumber: ele.palletNumber,
            remark:ele.remark
          }
        })
        // let obj = {}
        // response.data.reduce((prev, curr) => {
        //   console.log(prev, curr)
        // })
        // this.tableData.forEach((ele) => {
        //   ele.size.substring(2, ele.size.length - 2)
        //   // console.log(Object.prototype.toString.call(ele.size))
        //   // // if (Object.prototype.toString.call(ele.size) === Array) {
        //   //   console.log(11111)
        //   //   console.log();
        //   // }
        // })
        // let obj = {}
        // this.tableData.forEach(ele => {
        //   obj.num += ele.num
        //   obj.area += ele.num
        //   obj.count += ele.num

        // })
        // console.log(obj);
        // this.listQuery.total = response.data.total;
        this.dataListLoading = false;
      });
    },
    // deleteHandle(id, name, index, data) {
    //   this.$confirm(`确认要删除序号${index}?`, "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(() => {
    //       this.urlOptions.deleteURL(id).then(({ data }) => {
    //         this.$message({
    //           message: "操作成功",
    //           type: "success",
    //           duration: 1500,
    //           onClose: () => {
    //             this.getDataList();
    //           },
    //         });
    //       });
    //     })
    //     .catch(() => { });
    // },
    // async getDict() {
    //   // 物料列表
    //   const res = await getHotMaterialAllList();
    //   this.formConfig[0].selectOptions = res.data;
    // },
    buttonClick(val) {
      switch (val.btnName) {
        case 'search':
          // this.listQuery.pageNo = 1;
          // this.listQuery.pageSize = 20;
          // this.listQuery.materialId = val.materialId ? val.materialId : undefined;
          // this.listQuery.startTime = '1706144404000';
          // this.listQuery.endTime = '1706230804000';
          this.listQuery.startTime = val.checkTime ? val.checkTime[0] : undefined;
          this.listQuery.endTime = val.checkTime ? val.checkTime[1] : undefined;
          this.listQuery.lineId = val.lineId ? val.lineId : undefined
          this.getDataList();
          break;
        // case 'reset':
        //   this.$refs.searchBarForm.resetForm();
        //   this.listQuery = {
        //     pageSize: 20,
        //     pageNo: 1,
        //     total: 1,
        //   };
        //   this.getDataList();
        //   break;
        // case 'add':
        //   this.addOrEditTitle = '新增';
        //   this.addOrUpdateVisible = true;
        //   this.addOrUpdateHandle();
        //   break;
        case 'export':
          this.handleExport();
          break;
        default:
          console.log(val);
      }
    },
  },
};
</script>
<style scoped>
::v-deep.baseTable .el-table__body tr.current-row>td.el-table__cell {
  background-color: #EAF1FC;
}

::v-deep .baseTable .el-table .el-table__cell {
  padding: 0;
  height: 35px;
}
</style>
