<!--
 * @Author: zhp
 * @Date: 2024-04-18 15:07:53
 * @LastEditTime: 2024-04-25 13:41:27
 * @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" border id="exportTable" :data="tableData" style="width: 100%" :span-method="objectSpanMethod">
      <el-table-column :width="item.width" v-for="item in tableProps" :prop="item.prop" :label="item.label"
        align="center">
      </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 {
  getCuttingtData,
  getOriginalLineDataList
} from '@/api/report/qcReport';
import tableHeightMixin from '@/mixins/lb/tableHeightMixin';
import FileSaver from 'file-saver'
// import { getList, } from "@/api/base/qualityScrapType";
const tableProps = [
  // {
  //   prop: 'createTime',
  //   label: '添加时间',
  //   filter: parseTime
  // },
  {
    prop: 'lineName',
    label: '产线',
    width:'150',
  },
  {
    prop: 'dataType',
    label: '',
    width: '150',
  },
  {
    prop: 'type',
    label: '类别'
  },
  {
    prop: 'pieces',
    label: '片数'
  },
  {
    prop: 'area',
    label: '面积'
  },
  {
    prop: 'rate',
    label: '占比%',
    // filter: (val) => val == false ? '不合格' : '合格',
  },
  // {
  //   prop: 'checkerName',
  //   label: '检测人员'
  // },
  // {
  //   prop: 'checkTime',
  //   label: '检测时间',
  //   filter: parseTime
  // },
];

export default {
  mixins: [ tableHeightMixin],
  data() {
    return {
      urlOptions: {
        getDataListURL: getCuttingtData,
        // deleteURL: deleteQualityHotMaterial,
        // exportURL: exportFactoryExcel,
      },
      tableProps,
      tableData: [],
      mergeArr: [],//记录合并行数
      pos: 0,
      listQuery: {
        startTime: undefined,
        endTime: undefined,
        lineId:undefined
      },
      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: [new Date(new Date(Date.now()).setHours(7, 0, 0, 0)).getTime(), new Date(new Date(Date.now()).setHours(6, 59, 59)).getTime() + 24 * 60 * 60 * 1000],
          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: 'primary',
          plain: true
        },
      ],
    };
  },
  components: {
    // AddOrUpdate,
  },
  created() { },
  mounted() {
    // this.formConfig[1].defaultSelect[]
    this.listQuery.startTime = new Date(new Date(Date.now()).setHours(7, 0, 0, 0)).getTime()
    this.listQuery.endTime = new Date(new Date(Date.now()).setHours(6, 59, 59)).getTime() + 24 * 60 * 60 * 1000
    // 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
    },
    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);
          spanTwoArr.push(1);
        } else {
          //第一列需合并相同内容的判断条件
          if (item.lineName === this.tableData[index - 1].lineName) {
            spanOneArr[concatOne] += 1;
            spanOneArr.push(0);
          } else {
            spanOneArr.push(1);
            concatOne = index;
          };
          if (item.dataType === this.tableData[index - 1].dataType) {
            spanTwoArr[concatTwo] += 1;
            spanTwoArr.push(0);
          } else {
            spanTwoArr.push(1);
            concatTwo = index;
          };
        }
      });

      if (columnIndex === 0) {
        const _row = spanOneArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        }
      }
      if (columnIndex === 1) {
        const _row = spanTwoArr[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 = '1706144404000';
      // this.listQuery.endTime = '1706230804000';
      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 {
            dataType: ele.dataType == 1 ? '成品' : ele.dataType == 2 ? '取样' : '废版',
            code: ele.code,
            putNum: ele.putNum,
            lineName: ele.lineName,
            type: ele.type,
            pieces: ele.pieces,
            area: ele.area,
            rate: (ele.rate * 100).toFixed(2)
            // useNum: ele.useNum,
            // num: ele.num,
            // size: typeof (ele.size)
            // size: ele.size.match(/\[(.+?)\]/g) ? ele.size.substring(1, ele.size.length - 1) : ele.size
          }
        })
        // 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 ? new Date(new Date(val.checkTime[0]).setHours(7, 0, 0, 0)).getTime() : undefined;
          this.listQuery.endTime = val.checkTime ? new Date(new Date(val.checkTime[1]).setHours(6, 59, 59)).getTime() + 24 * 60 * 60 * 1000 : 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>
