<template>
  <div class="self-maintenance">
    <search-bar
      :formConfigs="formConfig"
      ref="searchBarForm"
      @headBtnClick="buttonClick"
    />
    <base-table
      :page="listQuery.current"
      :limit="listQuery.size"
      :table-props="tableProps"
      :table-data="tableData"
      :max-height="tableH"
    >
      <method-btn
        v-if="tableBtn.length"
        slot="handleBtn"
        :width="80"
        label="操作"
        fixed="right"
        :method-list="tableBtn"
        @clickBtn="handleClick"
      />
    </base-table>
    <pagination
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      :total="total"
      @pagination="getList()"
    />
    <!-- 新增 -->
    <base-dialog
      :dialogTitle="addAndEdit"
      :dialogVisible="centervisible"
      @cancel="handleCancel"
      @confirm="handleConfirm"
      :before-close="handleCancel"
    >
      <self-maintenance-add
        ref="selfMaintenanceAdd"
        @successSubmit="successSubmit"
      />
    </base-dialog>
  </div>
</template>
<script>
import { tableHeight } from '@/utils/index'
import SelfMaintenanceAdd from './selfMaintenanceAdd.vue'
import {
  getAutoMaintainPage,
  autoMaintainExport,
  autoMaintainDelete
} from '@/api/deviceManagement'
import { getTreeData } from '@/api/app'
import { timeFormatter } from '@/utils'
const tableProps = [
  {
    prop: 'code',
    label: '维护工单号',
    minWidth: 150
  },
  {
    prop: 'proLineName',
    label: '产线',
    minWidth: 120
  },
  {
    prop: 'unitName',
    label: '单元',
    minWidth: 150
  },
  {
    prop: 'equName',
    label: '设备名称',
    minWidth: 150
  },
  {
    prop: 'maintainStaff',
    label: '维护人员',
    minWidth: 140
  },
  {
    prop: 'sparePartName',
    label: '备件名称',
    minWidth: 150
  },
  {
    prop: 'model',
    label: '备件型号',
    minWidth: 150
  },
  {
    prop: 'replaceNum',
    label: '更换数量',
    minWidth: 140
  },
  {
    prop: 'complete',
    label: '完成情况',
    minWidth: 140
  },
  {
    prop: 'startTime',
    label: '开始时间',
    filter: timeFormatter,
    minWidth: 160
  },
  {
    prop: 'endTime',
    label: '结束时间',
    filter: timeFormatter,
    minWidth: 160
  },
  {
    prop: 'creatorName',
    label: '登记人',
    minWidth: 140
  },
  {
    prop: 'createTime',
    label: '登记时间',
    filter: timeFormatter,
    minWidth: 160
  }
]
const tableBtn = [
  {
    type: 'edit',
    btnName: '编辑'
  },
  {
    type: 'delete',
    btnName: '删除'
  }
]
export default {
  name: 'selfMaintenance',
  components: { SelfMaintenanceAdd },
  data() {
    return {
      formConfig: [
        {
          type: 'datePicker',
          label: '开始时间',
          dateType: 'datetimerange',
          format: 'yyyy-MM-dd HH:mm:ss',
          valueFormat: 'yyyy-MM-ddTHH:mm:ss',
          rangeSeparator: '-',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          param: 'timeVal',
          width: 350
        },
        {
          type: 'cascader',
          label: '产线/单元/设备',
          selectOptions: [],
          param: 'keyword',
          cascaderProps: { checkStrictly: true, value: 'name', label: 'name' },
          width: 250
        },
        {
          type: 'input',
          label: '维护工单号',
          placeholder: '维护工单号',
          param: 'code'
        },
        {
          type: 'button',
          btnName: '查询',
          name: 'search',
          color: 'primary'
        },
        {
          type: 'button',
          btnName: '重置',
          name: 'reset'
        },
        {
          type: 'separate'
        },
        {
          type: 'button',
          btnName: '新增',
          name: 'add',
          color: 'primary',
          plain: true
        },
        {
          type: 'button',
          btnName: '导出',
          name: 'export',
          color: 'primary',
          plain: true
        }
      ],
      tableProps,
      tableData: [],
      tableBtn,
      tableH: tableHeight(320),
      total: 0,
      listQuery: {
        current: 1,
        size: 20
      },
      addAndEdit: '',
      centervisible: false
    }
  },
  mounted() {
    window.addEventListener('resize', () => {
      this.tableH = tableHeight(320)
    })
    this.getTree()
    this.getList()
  },
  methods: {
    getTree() {
      getTreeData().then((res) => {
        this.formConfig[1].selectOptions = res.data
      })
    },
    getList() {
      getAutoMaintainPage({ ...this.listQuery }).then((res) => {
        if (res.code === 0) {
          this.total = res.data.total
          this.tableData = res.data.records
        }
      })
    },
    handleClick(val) {
      if (val.type === 'edit') {
        this.addAndEdit = '编辑'
        this.centervisible = true
        this.$nextTick(() => {
          this.$refs.selfMaintenanceAdd.init(val.data.id)
        })
      } else {
        this.$confirm('确认删除工单号"' + val.data.code + '"吗？', {
          type: 'warning'
        })
          .then(() => {
            autoMaintainDelete({ id: val.data.id }).then((res) => {
              console.log(res)
              this.$message({
                message: '工单删除成功',
                type: 'success'
              })
              this.listQuery.current = 1
              this.getList()
            })
          })
          .catch(() => {})
      }
    },
    buttonClick(val) {
      switch (val.btnName) {
        case 'search':
          this.listQuery.startTime = val.timeVal ? val.timeVal[0] : ''
          this.listQuery.endTime = val.timeVal ? val.timeVal[1] : ''
          this.listQuery.proLineName = val.keyword[0]
          this.listQuery.unitName = val.keyword[1]
          this.listQuery.equName = val.keyword[2]
          this.listQuery.code = val.code
          this.getList()
          break
        case 'reset':
          this.$refs.searchBarForm.resetForm()
          this.listQuery.startTime = ''
          this.listQuery.endTime = ''
          this.listQuery.proLineName = ''
          this.listQuery.unitName = ''
          this.listQuery.equName = ''
          this.listQuery.code = ''
          this.getList()
          break
        case 'add':
          this.addAndEdit = '新增'
          this.centervisible = true
          this.$nextTick(() => {
            this.$refs.selfMaintenanceAdd.init()
          })
          break
        default:
          autoMaintainExport({ ...this.listQuery }).then((response) => {
            let fileName = ''
            const contentDisposition = response.headers['content-disposition']
            if (contentDisposition) {
              fileName = decodeURIComponent(
                contentDisposition.slice(
                  contentDisposition.indexOf('filename=') + 9
                )
              )
            }
            const blob = new Blob([response.data])
            const reader = new FileReader()
            reader.readAsDataURL(blob)
            reader.onload = (e) => {
              const a = document.createElement('a')
              a.download = fileName
              a.href = e.target.result
              document.body.appendChild(a)
              a.click()
              document.body.removeChild(a)
            }
          })
      }
    },
    handleCancel() {
      this.$refs.selfMaintenanceAdd.formClear()
      this.addAndEdit = ''
      this.centervisible = false
    },
    handleConfirm() {
      this.$refs.selfMaintenanceAdd.submitForm()
    },
    successSubmit() {
      this.handleCancel()
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.self-maintenance {
  height: calc(100vh - 203px);
  padding: 12px 16px;
  margin: 0px 16px;
  border-radius: 8px;
  background-color: #fff;
}
</style>
