<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <SearchBar :formConfigs="searchBarFormConfig" ref="search-bar" @headBtnClick="handleSearchBarBtnClick" />

    <!-- 列表 -->
    <base-table :table-props="tableProps" :page="queryParams.pageNo" :limit="queryParams.pageSize" :table-data="list"
      @emitFun="handleEmitFun">
      <!-- <method-btn v-if="tableBtn.length" slot="handleBtn" label="操作" :width="120" :method-list="tableBtn"
        @clickBtn="handleTableBtnClick" /> -->
    </base-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 对话框(添加 / 修改) -->
  </div>
</template>

<script>
import moment from 'moment';

import {
  getPdList,
} from '@/api/core/monitoring/auto';
import { getFactoryPage } from '@/api/core/base/factory';
import basicPageMixin from '@/mixins/lb/basicPageMixin';
import { getDefectAnalysis } from '@/api/monitoring/defectSummary';
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'
export default {
  name: 'QualityInspectionType',
  mixins: [basicPageMixin],
  data() {
    return {
      // tableBtn: [
      //   this.$auth.hasPermi('base:quality-inspection-type:update')
      //     ? {
      //       type: 'edit',
      //       btnName: '修改',
      //     }
      //     : undefined,
      //   this.$auth.hasPermi('base:quality-inspection-type:delete')
      //     ? {
      //       type: 'delete',
      //       btnName: '删除',
      //     }
      //     : undefined,
      // ].filter((v) => v),
      tableProps: [
        // {
        //   prop: 'createTime',
        //   label: '添加时间',
        //   fixed: true,
        //   width: 180,
        //   filter: (val) => moment(val).format('yyyy-MM-DD HH:mm:ss'),
        // },
        { prop: 'factoryName', label: '工厂' },
        { prop: 'lineName', label: '产线' },
        { prop: 'remark', label: '玻璃编号' },
        {
          prop: 'checkTime',
          label: '检测时间',
          fixed: true,
          width: 180,
          filter: (val) => moment(val).format('yyyy-MM-DD HH:mm:ss'),
        },
        { prop: 'checkNum', label: '缺陷数' },
        {
          prop: 'glassGrade',
          label: '等级',
          filter: (val) => val === 0 ? '合格' : val === 1 ? '提示' : val === 2 ? '返修' : val === 3 ? '报废' : ''
        },
        { prop: 'reason', label: '判等原因' },
        { prop: 'specifications', label: '规格' },


        // {
        // 	label: '操作',
        // 	alignt: 'center',
        // 	subcomponent: {
        // 		render: function (h) {
        // 			return h('div', null, [
        // 				h(
        // 					'el-button',
        // 					{
        // 						props: {
        // 							icon: 'el-icon-edit',
        // 							size: 'mini',
        // 							type: 'text',
        // 						},
        // 					},
        // 					' 修改'
        // 				),
        // 				h(
        // 					'el-button',
        // 					{
        // 						props: {
        // 							icon: 'el-icon-edit',
        // 							size: 'mini',
        // 							type: 'text',
        // 						},
        // 					},
        // 					' 修改'
        // 				),
        // 			]);
        // 		},
        // 	},
        // },
      ],
      //
      searchBarFormConfig: [
        {
          type: 'select',
          label: '工厂',
          selectOptions: [],
          param: 'factoryId',
        },
        {
          type: 'select',
          label: '产线',
          selectOptions: [],
          multiple: true,
          param: 'lineId',
        },
        {
          type: 'input',
          label: '缺陷数>',
          // selectOptions: [],
          param: 'checkNum',
        },
        {
          type: 'datePicker',
          label: '时间范围',
          dateType: 'datetimerange',
          format: 'yyyy-MM-dd HH:mm:ss',
          // valueFormat: 'timestamp',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          rangeSeparator: '-',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          param: 'timeVal',
          width: 350
        },
        {
          type: 'button',
          btnName: '查询',
          name: 'search',
          color: 'primary',
        },
        // {
        // 	type: 'button',
        // 	btnName: '重置',
        // 	name: 'reset',
        // },
        {
          type: 'separate',
        },
        // {
        //   type: this.$auth.hasPermi('base:quality-inspection-type:create')
        //     ? 'button'
        //     : '',
        //   btnName: '新增',
        //   name: 'add',
        //   plain: true,
        //   color: 'success',
        // },
        {
          type: this.$auth.hasPermi('base:quality-inspection-type:export')
            ? 'button'
            : '',
          btnName: '导出',
          name: 'export',
          color: 'warning',
        },
      ],
      // 表单配置
      // formRows: [
      // 	[
      // 		{
      // 			input: true,
      // 			label: '检测类型名称',
      // 			prop: 'name',
      // 			rules: [{ required: true, message: '不能为空', trigger: 'blur' }],
      // 			// bind: {
      // 			// 	disabled: true, // some condition, like detail mode...
      // 			// }
      // 		},
      // 	],
      // 	[{ input: true, label: '检测类型编码', prop: 'code' }],
      // 	[{ input: true, label: '备注', prop: 'remark' }],
      // ],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        lineId: undefined,
        factoryId: undefined,
        checkNum: undefined,
        startTime: undefined,
        endTime: undefined,
      },
      // 表单参数
      form: {},
    };
  },
  // watch: {
  // 	form: {
  // 		handler: (val) => {
  // 			console.log('form changed', val);
  // 		},
  // 		deep: true
  // 	},
  // },
  created() {
    this.getList();
    this.getDict()
  },
  methods: {
    getDict() {
      getPdList().then(res => {
        this.searchBarFormConfig[1].selectOptions = res.data || [];
      });

      getFactoryPage({ pageSize: 100, pageNo: 1 }).then(res => {
        this.searchBarFormConfig[0].selectOptions = res.data.list || [];
      });
    },
    /** base table related */
    handleTableBtnClick({ data, type }) {
      switch (type) {
        case 'edit':
          this.handleUpdate(data);
          break;
        case 'delete':
          this.handleDelete(data);
          break;
      }
    },
    /** search bar related */
    handleSearchBarBtnClick(btn) {
      // const keys = ['name'];
      switch (btn.btnName) {
        case 'search':
          this.queryParams.lineId = btn.lineId ? btn.lineId : undefined
          this.queryParams.factoryId = btn.factoryId ? btn.factoryId : undefined
          this.queryParams.startTime = btn.timeVal ? btn.timeVal[0] : undefined
          this.queryParams.endTime = btn.timeVal ? btn.timeVal[1] : undefined
          this.queryParams.checkNum = btn.checkNum ? btn.checkNum : undefined


          // keys.forEach((key) => {
          //   this.queryParams[key] = btn[key] || null;
          // });
          this.getList();
          break;
        case 'add':
          this.handleAdd();
          break;
        case 'export':
          this.handleExport();
          break;
        // case 'reset':
        //   this.$refs['search-bar'].resetForm();
        //   this.resetQuery();
        //   break;
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getDefectAnalysis(this.queryParams).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    handleExport() {
      // 处理查询参数
      let tables = document.querySelector('.el-table').cloneNode(true)
      const fix = tables.querySelector('.el-table__fixed')
      const fixRight = tables.querySelector('.el-table__fixed-right')
      if (fix) {
        tables.removeChild(tables.querySelector('.el-table__fixed'))
      }
      if (fixRight) {
        tables.removeChild(tables.querySelector('.el-table__fixed-right'))
      }
      let exportTable = XLSX.utils.table_to_book(tables)

      var exportTableOut = XLSX.write(exportTable, {
        bookType: 'xlsx', bookSST: true, type: 'array'
      })
      // sheetjs.xlsx为导出表格的标题名称
      try {
        FileSaver.saveAs(new Blob([exportTableOut], {
          type: 'application/octet-stream'
        }),'缺陷分析.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, exportTableOut)
      }
      return exportTableOut
    },
  },
};
</script>
