<template>
  <div class="plan-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="170"
        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="centervisibleAdd"
      @cancel="handleCancelAdd"
      @confirm="handleConfirmAdd"
      :before-close="handleCancelAdd"
    >
      <planned-maintenance-add
        ref="plannedMaintenanceAdd"
        @successSubmit="successSubmitAdd"
      />
    </base-dialog>
    <!-- 确认&已派工的修改 -->
    <base-dialog
      :dialogTitle="sureAndEdit"
      :dialogVisible="centervisibleSure"
      @cancel="handleCancelSure"
      @confirm="handleConfirmSure"
      :before-close="handleCancelSure"
    >
      <planned-maintenance-edit
        ref="plannedMaintenanceEdit"
        @successSubmit="successSubmitEdit"
      />
    </base-dialog>
  </div>
</template>
<script>
import { tableHeight } from '@/utils/index'
import PlannedMaintenanceAdd from './plannedMaintenanceAdd'
import PlannedMaintenanceEdit from './plannedMaintenanceEdit'
import statusTag from './statusTag.vue'
import { getTreeData } from '@/api/app'
import {
  getMaintainManagePage,
  maintainManageDispatch,
  maintainManageExport,
  maintainManageDelete
} from '@/api/deviceManagement'
import { timeFormatter } from '@/utils'
const tableProps = [
  {
    prop: 'code',
    label: '维护工单号',
    minWidth: 150
  },
  {
    prop: 'status',
    label: '状态',
    width: 100,
    subcomponent: statusTag
  },
  {
    prop: 'remainTime',
    label: '剩余时间',
    minWidth: 150
  },
  {
    prop: 'planStartTime',
    label: '计划开始时间',
    filter: timeFormatter,
    minWidth: 160
  },
  {
    prop: 'planEndTime',
    label: '计划结束时间',
    filter: timeFormatter,
    minWidth: 160
  },
  {
    prop: 'proLineName',
    label: '产线',
    minWidth: 150
  },
  {
    prop: 'unitName',
    label: '单元',
    minWidth: 150
  },
  {
    prop: 'equName',
    label: '设备名称',
    minWidth: 150
  },
  {
    prop: 'sparePartName',
    label: '备件名称',
    width: 150
  },
  {
    prop: 'model',
    label: '备件型号',
    minWidth: 150
  },
  {
    prop: 'replaceNum',
    label: '更换数量',
    minWidth: 140
  },
  {
    prop: 'maintainContent',
    label: '维护内容',
    minWidth: 180
  },
  {
    prop: 'executeStaff',
    label: '执行人员',
    minWidth: 140
  },
  {
    prop: 'startTime',
    label: '实际开始时间',
    filter: timeFormatter,
    minWidth: 160
  },
  {
    prop: 'endTime',
    label: '实际结束时间',
    filter: timeFormatter,
    minWidth: 160
  },
  {
    prop: 'complete',
    label: '完成情况',
    minWidth: 140
  },
  {
    prop: 'creatorName',
    label: '创建人员',
    minWidth: 150
  },
  {
    prop: 'createTime',
    label: '创建时间',
    filter: timeFormatter,
    minWidth: 160
  }
]
const tableBtn = [
  {
    type: 'edit',
    btnName: '编辑',
    showParam: {
      type: '&',
      data: [
        {
          type: 'unequal',
          name: 'status',
          value: '未完成'
        }
      ]
    }
  },
  {
    type: 'dispatch',
    btnName: '派工',
    showParam: {
      type: '&',
      data: [
        {
          type: 'equal',
          name: 'status',
          value: '未派工'
        }
      ]
    }
  },
  {
    type: 'sure',
    btnName: '确认',
    showParam: {
      type: '&',
      data: [
        {
          type: 'unequal',
          name: 'status',
          value: '已完成'
        }
      ]
    }
  },
  {
    type: 'delete',
    btnName: '删除'
  }
]
export default {
  name: 'plannedMaintenance',
  components: { PlannedMaintenanceAdd, PlannedMaintenanceEdit },
  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: 'select',
          label: '状态',
          selectOptions: JSON.parse(localStorage.getItem('publicList'))
            .maintainStatusVoList,
          labelField: 'dataName',
          valueField: 'dataName',
          param: 'status',
          defaultSelect: '',
          width: 100
        },
        {
          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: 'export',
          color: 'primary',
          plain: true
        },
        {
          type: 'button',
          btnName: '新增',
          name: 'add',
          color: 'success',
          plain: true
        }
      ],
      tableProps,
      tableData: [],
      tableBtn,
      tableH: tableHeight(320),
      total: 0,
      listQuery: {
        current: 1,
        size: 20
      },
      addAndEdit: '',
      centervisibleAdd: false,
      sureAndEdit: '',
      centervisibleSure: false
    }
  },
  mounted() {
    window.addEventListener('resize', () => {
      this.tableH = tableHeight(320)
    })
    this.getTree()
    this.getList()
  },
  methods: {
    getTree() {
      getTreeData().then((res) => {
        this.formConfig[2].selectOptions = res.data
      })
    },
    getList() {
      getMaintainManagePage({ ...this.listQuery }).then((res) => {
        if (res.code === 0) {
          this.total = res.data.total
          this.tableData = res.data.records
        }
      })
    },
    handleClick(val) {
      console.log(val)
      switch (val.type) {
        case 'edit':
          if (val.data.status === '未派工') {
            this.addAndEdit = '编辑'
            this.centervisibleAdd = true
            this.$nextTick(() => {
              this.$refs.plannedMaintenanceAdd.init(val.data.id)
            })
          } else if (val.data.status === '已完成') {
            this.sureAndEdit = '编辑'
            this.centervisibleSure = true
            this.$nextTick(() => {
              let param = { id: val.data.id, type: 'edit' }
              this.$refs.plannedMaintenanceEdit.init(param)
            })
          }
          break
        case 'dispatch':
          this.$confirm('确认派工"' + val.data.code + '"吗？', {
            type: 'warning'
          })
            .then(() => {
              maintainManageDispatch({ id: val.data.id }).then((res) => {
                console.log(res)
                this.$message({
                  message: '派工成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {}
                })
                this.getList()
              })
            })
            .catch(() => {})
          break
        case 'sure':
          this.sureAndEdit = '确认'
          this.centervisibleSure = true
          this.$nextTick(() => {
            let param = { id: val.data.id, type: 'sure' }
            this.$refs.plannedMaintenanceEdit.init(param)
          })
          break
        default:
          this.$confirm('确认删除工单"' + val.data.code + '"吗？', {
            type: 'warning'
          })
            .then(() => {
              maintainManageDelete({ id: val.data.id }).then((res) => {
                console.log(res)
                this.$message({
                  message: '工单删除成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {}
                })
                this.listQuery.current = 1
                this.getList()
              })
            })
            .catch(() => {})
      }
    },
    buttonClick(val) {
      console.log(val)
      switch (val.btnName) {
        case 'search':
          this.listQuery.planStartTime = val.timeVal ? val.timeVal[0] : ''
          this.listQuery.planEndTime = val.timeVal ? val.timeVal[1] : ''
          this.listQuery.status = val.status
          this.listQuery.proLineName = val.keyword[0]
          this.listQuery.unitName = val.keyword[1]
          this.listQuery.equName = val.keyword[2]
          this.listQuery.code = val.code
          this.listQuery.current = 1
          this.getList()
          break
        case 'reset':
          this.$refs.searchBarForm.resetForm()
          this.listQuery.planStartTime = ''
          this.listQuery.planEndTime = ''
          this.listQuery.status = ''
          this.listQuery.proLineName = ''
          this.listQuery.unitName = ''
          this.listQuery.equName = ''
          this.listQuery.code = ''
          this.listQuery.current = 1
          this.getList()
          break
        case 'add':
          this.addAndEdit = '新增'
          this.centervisibleAdd = true
          this.$nextTick(() => {
            this.$refs.plannedMaintenanceAdd.init()
          })
          break
        default:
          maintainManageExport({ ...this.listQuery }).then((response) => {
            console.log(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)
            }
          })
      }
    },
    handleCancelAdd() {
      this.$refs.plannedMaintenanceAdd.formClear()
      this.addAndEdit = ''
      this.centervisibleAdd = false
    },
    handleConfirmAdd() {
      this.$refs.plannedMaintenanceAdd.submitForm()
    },
    successSubmitAdd() {
      this.handleCancelAdd()
      this.getList()
    },
    handleCancelSure() {
      this.$refs.plannedMaintenanceEdit.formClear()
      this.sureAndEdit = ''
      this.centervisibleSure = false
    },
    handleConfirmSure() {
      this.$refs.plannedMaintenanceEdit.submitForm()
    },
    successSubmitEdit() {
      this.handleCancelSure()
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.plan-maintenance {
  height: calc(100vh - 203px);
  padding: 12px 16px;
  margin: 0px 16px;
  border-radius: 8px;
  background-color: #fff;
}
</style>
