<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-form
          :inline="true"
          class="demo-form-inline"
          label-position="right"
          label-width="80px"
          label-suffix=":"
        >
          <el-form-item label="使用部门">
            <treeselect
              v-model="query.use_deptid"
              :options="depts"
              :load-options="loadDepts"
              clearable
              style="width: 300px"
              placeholder="选择部门"
            />
          </el-form-item>
          <el-form-item label="设备类别">
            <treeselect
              v-model="query.material_type_id"
              :options="classes"
              clearable
              :load-options="loadClass"
              style="width: 300px"
              placeholder="设备类别"
            />
          </el-form-item>
          <el-form-item label="设备属性">
            <el-select
              v-model="query.device_type"
              clearable
              style="width: 200px"
              placeholder="设备属性"
              class="filter-item"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in dict.device_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备编码">
            <el-input
              v-model="query.device_code"
              clearable
              style="width: 200px"
              placeholder="设备编码或名称"
              @keyup.enter.native="crud.toQuery"
            />
          </el-form-item>
          <el-form-item label="生产厂家">
            <el-input
              v-model="query.manufacturer"
              style="width: 200px"
              clearable
              placeholder="生产厂家"
              @keyup.enter.native="crud.toQuery"
            />
          </el-form-item>
          <el-form-item label="启用日期">
            <el-date-picker
              v-model="query.createTime"
              type="daterange"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @input="onInput()"
              :default-time="['00:00:00', '23:59:59']"
              @change="crud.toQuery"
            />
          </el-form-item>
          <el-form-item label="所属工序">
            <el-select
              v-model="query.workprocedure_id"
              clearable
              placeholder="所属工序"
              style="width: 200px"
              class="filter-item"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in workProcedureList"
                :key="item.workprocedure_id"
                :label="item.workprocedure_name"
                :value="item.workprocedure_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备状态">
            <el-select
              v-model="query.status"
              clearable
              style="width: 200px"
              placeholder="设备状态"
              class="filter-item"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in dict.device_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="生产用途">
            <el-select
              v-model="query.is_produceuse"
              clearable
              style="width: 200px"
              placeholder="生产用途"
              class="filter-item"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in dict.is_produceuse"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <rrOperation />
        </el-form>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <el-button
          slot="right"
          class="filter-item"
          type="success"
          icon="el-icon-position"
          size="mini"
          :disabled="sub_flag"
          @click="submit('10')"
        >
         启用
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          type="success"
          :disabled="dissub_flag"
          icon="el-icon-position"
          size="mini"
          @click="submit('11')"
        >
          停用
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          type="warning"
          :disabled="open_flag"
          icon="el-icon-check"
          size="mini"
          @click="openWork"
        >
         档案维护
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          type="warning"
          icon="el-icon-check"
          size="mini"
          @click="printCard"
        >
          打印
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          type="warning"
          icon="el-icon-position"
          size="mini"
          @click="downdtl()"
        >
          导出excel
        </el-button>
      </crudOperation>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        size="mini"
        :data="crud.data"
        style="width: 100%;"
        :highlight-current-row="true"
        @selection-change="mySelectionChange"
      >
        <el-table-column
          v-permission="['admin','equipmentfile:del','equipmentfile:edit']"
          min-width="130"
          label="操作"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
              :disabled-dle="canUd(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column :selectable="checkboxT" type="selection" width="55" />
        <el-table-column prop="设备代码" width="100" label="设备代码">
          <template slot-scope="scope">
            <el-link type="warning" @click="toView(scope.$index, scope.row)">{{ scope.row.device_code }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="device_name" min-width="150" label="设备名称"/>
        <el-table-column prop="extend_code" min-width="100" label="内部自编号"/>
        <el-table-column prop="device_model" min-width="130" label="设备型号"/>
        <el-table-column prop="device_spec" min-width="130" label="设备规格"/>
        <el-table-column prop="material_type_name" min-width="150" label="设备类别" />
        <el-table-column  :formatter="is_produceuseFormat" min-width="70" prop="is_produceuse" label="生产用途" />
        <el-table-column  :formatter="stateFormat" min-width="70" prop="status" label="设备状态" />
        <el-table-column prop="beginuse_date" min-width="90" label="启用日期"/>
        <el-table-column prop="use_deptname" min-width="130" label="使用部门"/>
        <el-table-column prop="use_groupname" min-width="130" label="使用班组"/>
        <el-table-column prop="supplier_name" min-width="180" label="供应商"/>
        <el-table-column prop="manufacturer" min-width="180" label="制造商"/>
        <el-table-column prop="country_manufactur" min-width="90" label="制造国别"/>
        <el-table-column prop="leavefactory_date" min-width="80" label="出厂日期"/>
        <el-table-column prop="leavefactory_number" min-width="130" label="出厂编号"/>
        <el-table-column prop="drawing_number" min-width="130" label="图号"/>
        <el-table-column prop="device_type" min-width="70" label="设备属性" :formatter="device_typeFormat"/>
        <el-table-column prop="workprocedure_id" min-width="70" label="工序" :formatter="seriesFormat2" />
        <el-table-column prop="assets_code" min-width="100" label="资产编码"/>
        <el-table-column prop="assets_name" min-width="150" label="资产名称"/>
        <el-table-column prop="create_name" min-width="90" label="生成人"/>
        <el-table-column prop="create_time" min-width="140" label="生成时间"/>
        <el-table-column prop="update_optname" min-width="90" label="修改人"/>
        <el-table-column prop="update_time" min-width="140" label="修改时间"/>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <AddDialog @AddChanged="querytable" />
    <ViewDialog :dialog-show.sync="viewShow" :rowmst="mstrow" @AddChanged="querytable" />
    <ChangeDialog :dialog-show.sync="changeShow" :rowmst="mstrow" @AddChanged="querytable" />
  </div>
</template>

<script>
import equipmentfile from '@/api/wms/basedata/em/equipmentfile'
import CRUD, { crud, header, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import AddDialog from '@/views/wms/basedata/em/equipmentfile/AddDialog'
import ViewDialog from '@/views/wms/basedata/em/equipmentfile/ViewDialog'
import ChangeDialog from '@/views/wms/basedata/em/equipmentfile/ChangeDialog'
import { getLodop } from '@/assets/js/lodop/LodopFuncs'
import crudWorkProcedure from '@/api/wms/basedata/pdm/workProcedure'
import Date from '@/utils/datetime'
import Treeselect, { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getDepts } from '@/api/system/dept'
import crudClassstandard from '@/api/wms/basedata/master/classstandard'
import crudMaterialbase from '@/api/wms/basedata/master/materialbase'
import { download } from '@/api/data'
import { downloadFile } from '@/utils'

export default {
  name: 'equipmentfile',
  components: { Treeselect, ChangeDialog, ViewDialog, AddDialog, crudOperation, rrOperation, udOperation, pagination },
  cruds() {
    return CRUD({ title: '设备档案', idField: 'devicerecord_id', url: 'api/equipmentfile', crudMethod: { ...equipmentfile },
      optShow: {
        add: true,
        edit: false,
        del: false,
        reset: true,
        download: false
      },
      query: {}})
  },
  mixins: [presenter(), header(), crud()],
  // 数据字典
  dicts: ['workorder_status', 'workorder_type', 'product_series', 'device_type', 'is_produceuse', 'device_status'],
  data() {
    return {
      height: document.documentElement.clientHeight - 180 + 'px;',
      permission: {},
      divShow: false,
      sub_flag: true,
      dissub_flag: true,
      open_flag: true,
      class_idStr: null,
      mstrow: {},
      XLList: [],
      depts: [],
      classes: [],
      workProcedureList: [],
      viewShow: false,
      changeShow: false,
      currentRow: null,
      checkrows: []
    }
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  created() {
    crudWorkProcedure.downSelect().then(res => {
      this.workProcedureList = res
    })
    const param = {
      'materOpt_code': '23'
    }
    crudMaterialbase.getMaterOptType(param).then(res => {
      this.class_idStr = res.class_idStr
      this.queryClassId()
    })
    this.getDepts()
  },
  methods: {
    canUd(row) {
      return row.status !== '00'
    },
    seriesFormat2(row) {
      for (const item of this.workProcedureList) {
        if (item.workprocedure_id === row.workprocedure_id) {
          return item.workprocedure_name
        }
      }
    },
    [CRUD.HOOK.beforeRefresh]() {
      this.handleCurrentChange()
    },
    toView(index, row) {
      this.mstrow = row
      this.viewShow = true
    },
    queryClassId() {
      const param = {
        'class_idStr': this.class_idStr
      }
      crudClassstandard.queryClassById(param).then(res => {
        this.classes = res.content.map(obj => {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    loadClass({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudClassstandard.getClass({ pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    getDepts() {
      getDepts({ enabled: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    mySelectionChange(rows) {
      this.buttonChange(rows)
    },
    buttonChange(rows) {
      if (rows.length !== 0) {
        this.sub_flag = false
        this.dissub_flag = false
        this.open_flag = false
        for (let i = 0; i < rows.length; i++) {
          if (!'00,11'.includes(rows[i].status)) {
            this.sub_flag = true
          }
          if (!'10'.includes(rows[i].status)) {
            this.dissub_flag = true
          }
          if (rows.length !== 1) {
            this.open_flag = true
          }
        }
      }else{
        this.handleCurrentChange()
      }
    },
    stateFormat(row) {
      return this.dict.label.device_status[row.status]
    },
    device_typeFormat(row) {
      return this.dict.label.device_type[row.device_type]
    },
    is_produceuseFormat(row) {
      return this.dict.label.is_produceuse[row.is_produceuse]
    },
    handleCurrentChange() {
      this.checkrows = []
      this.mstrow = {}
      this.sub_flag = true
      this.dissub_flag = true
      this.open_flag = true
    },
    onInput() {
      this.$forceUpdate()
    },
    checkboxT(row) {
      return row.status !== '99'
    },
    submit(status) {
      this.checkrows = this.$refs.table.selection
      if(this.checkrows.length === 0 ){
        this.crud.notify('请勾选需要操作的记录！')
        return false
      }
      equipmentfile.submit({ 'status': status, rows: this.checkrows}).then(res => {
        this.crud.notify('操作成功！')
        this.querytable()
      })
    },
    openWork(row) {
      this.checkrows = this.$refs.table.selection
      if(this.checkrows.length === 0 ){
        this.crud.notify('请勾选一条需要操作的记录！')
        return false
      }
      this.mstrow = this.checkrows[0]
      this.changeShow = true
    },
    querytable() {
      this.crud.toQuery()
      this.handleCurrentChange()
    },
    downdtl() {
      crud.downloadLoading = true
      download('/api/equipmentfile/download', this.crud.query).then(result => {
        downloadFile(result, '设备档案', 'xlsx')
        crud.downloadLoading = false
      }).catch(() => {
        crud.downloadLoading = false
      })
    },
    printCard() {
      const _selectData = this.$refs.table.selection
      if (_selectData.length > 1 || _selectData.length === 0) {
        return this.crud.notify('请选择一条记录', CRUD.NOTIFICATION_TYPE.INFO)
      }
      const data = _selectData[0]
      const LODOP = getLodop()

      LODOP.SET_SHOW_MODE('HIDE_DISBUTTIN_SETUP', 1)// 隐藏那些无效按钮
      // 打印纸张大小设置https://www.it610.com/article/2094844.html
      LODOP.PRINT_INIT('')
      LODOP.SET_PRINT_PAGESIZE(1, '80mm', '60mm', '')
      LODOP.ADD_PRINT_RECT('1mm', '3mm', '74mm', '54mm', 0, 1)
      LODOP.SET_PRINT_STYLE('FontSize', 12)
      LODOP.SET_PRINT_STYLE('Bold', 1)
      LODOP.ADD_PRINT_BARCODE('10mm', '12mm', '60mm', '20mm', '128A', data.device_code)
      LODOP.ADD_PRINT_TEXT('34mm', '12mm', '80mm', '15mm', '设备编码：' + data.device_code + '')
      LODOP.ADD_PRINT_TEXT('42mm', '12mm', '80mm', '15mm', '设备名称：' + data.device_name + '')
      LODOP.ADD_PRINT_TEXT('49mm', '12mm', '80mm', '15mm', '设备型号：' + data.device_model + '')
      LODOP.PRINT()// 打印
      this.crud.notify('打印成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.crud.toQuery()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-dialog__body {
  padding-top: 10px;
}
</style>
