<template>
  <basic-container style="max-height: 800px; overflow: hidden">
    <avue-crud :option="option" :table-loading="loading" :data="data" :search.sync="searchForm" :page.sync="page"
      ref="crud" v-model="form" :permission="permissionList" :before-open="beforeOpen" :before-close="beforeClose"
      @search-change="searchChange" @search-reset="searchReset" @current-change="currentChange"
      @size-change="sizeChange" @refresh-change="refreshChange" @selection-change="selectionChange">
      <template slot-scope="{row}" slot="produceTime">
        {{ row.produceTime.substring(0, 10) }}
      </template>
      <template slot-scope="{ row }" slot="status">
        <el-tag size="small" :type="row.status == 0
          ? 'warning'
          : row.status == 1
            ? ''
            : ''
          ">
          {{
            row.status == 0
              ? "待确认"
              : row.status == 1
                ? "已确认"
                : ""
          }}
        </el-tag>
      </template>
      <template slot-scope="{ row }" slot="runStatus">
        <el-tag size="small" :type="row.runStatus == 0
          ? 'info'
          : row.runStatus == 1
            ? 'success'
            : row.runStatus == 2
              ? 'danger'
              : ''
          ">
          {{
            row.runStatus == 0
              ? ""
              : row.runStatus == 1
                ? "运行中"
                : row.runStatus == 2
                  ? '故障中'
                  : ""
          }}
        </el-tag>
      </template>
      <template slot-scope="scope" slot="menuLeft">
        <el-button v-show="permission.deviceAdd" size="small" @click="handleAdd" type="primary">新 增</el-button>
        <el-button v-show="permission.deviceAdd" size="small" @click="handleImport" type="success">导 入</el-button>
        <el-button type="warning" size="small" @click="handleExport">导 出</el-button>
        <!-- <el-button
          type="primary"
          size="small"
          @click="addOperation"
          >需求提报</el-button
        > -->
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button v-show="permission.deviceView" @click="handleView(row)">查看</el-button>
        <el-button v-show="permission.deviceEdit" @click="handleEdit(row)">编辑</el-button>
        <!-- <el-button v-show="permission.deviceSubmit" @click="addOperation(row)">需求提报</el-button> -->
        <el-button v-show="row.qrcode == '' && permission.createQrcode" @click="handleQrcode(row)">生成二维码</el-button>
        <!--  -->
        <el-button v-show="permission.deviceCopy" @click="handleCopy(row)">复制</el-button>
        <el-button v-show="row.qrcode != '' && permission.qrcodeView" @click="lookQrcode(row)">查看二维码</el-button>
        <el-button v-show="permission.deviceDelete" @click="handleDelete(row)">删除</el-button>
      </template>
    </avue-crud>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :append-to-body="true" width="70%" :close-on-click-modal="false">
      <div class="details_tab_box">
        <el-radio-group v-model="detailsTab" size="mini">
          <el-radio-button label="1">设备详情</el-radio-button>
          <el-radio-button label="2">维修维保记录</el-radio-button>
        </el-radio-group>
      </div>
      <div style="height: 500px; overflow: auto" v-if="detailsTab == '1'">
        <el-form ref="form" :model="addForm" :rules="addRules" label-width="120px" label-position="left">
          <div>
            <div style="
                color: #101010;
                font-size: 18px;
                font-weight: 550;
                margin-bottom: 20px;
              ">
              基本信息
            </div>
            <!-- <el-form-item label="设备编号" prop="code">
              <el-input placeholder="请输入设备编号" style="width: 98%;" :readonly="viewType == 'view'" v-model="addForm.code"></el-input>
            </el-form-item> -->
            <el-form-item label="设备名称" prop="name">
              <el-input placeholder="请输入设备名称" style="width: 98%;" :disabled="viewType == 'view'"
                v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="型号" prop="model">
              <el-input placeholder="请输入型号" style="width: 98%;" :disabled="viewType == 'view'"
                v-model="addForm.model"></el-input>
            </el-form-item>
            <!-- <el-form-item label="设备位置">
              <SelectTree
                style="width: 98%;"
                ref="childTree"
                v-model="addForm.position"
                :disabled="viewType == 'view'"
                :tree-options="treeOptions"
                :default-value="addForm.position.node"
              ></SelectTree>
            </el-form-item> -->
            <el-form-item label="设备类型" prop="type">
              <el-select style="width:98%;" placeholder="请选择设备类型" :disabled="viewType == 'view'" v-model="addForm.type">
                <el-option v-for="item in typeList" :key="item.dictValue" :label="item.dictValue"
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供应商" prop="supplier">
              <el-input style="width: 98%;" :disabled="viewType == 'view'" placeholder="请输入供应商"
                v-model="addForm.supplier"></el-input>
            </el-form-item>
            <el-form-item label="品牌" prop="supplier">
              <el-input style="width: 98%;" :disabled="viewType == 'view'" placeholder="请输入品牌"
                v-model="addForm.brand"></el-input>
            </el-form-item>
            <el-form-item label="单位" prop="supplier">
              <el-input style="width: 98%;" :disabled="viewType == 'view'" placeholder="请输入单位"
                v-model="addForm.unit"></el-input>
            </el-form-item>
            <!-- <el-form-item label="生产时间" prop="produceTime">
              <el-date-picker :disabled="viewType == 'view'" style="width:98%;" v-model="addForm.produceTime"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder="请选择生产时间">
              </el-date-picker>
            </el-form-item> -->
            <el-form-item label="备注" prop="supplier">
              <el-input style="width: 98%;" :disabled="viewType == 'view'" placeholder="请输入备注"
                v-model="addForm.description"></el-input>
            </el-form-item>
            <el-form-item label="关联实验室" prop="lab">
              <el-cascader :props="labProps" style="width:98%;" v-model="addForm.lab"
                :disabled="viewType == 'view'"></el-cascader>
            </el-form-item>
            <!-- <el-form-item label="" prop="lab" v-if="role_id == '1839536982874193922'">
              <el-checkbox v-model="addForm.isWarran" :disabled="viewType == 'view'"> 是否在保</el-checkbox>
            </el-form-item> -->
          </div>
          <div>
            <div style="
                color: #101010;
                font-size: 18px;
                font-weight: 550;
                margin-bottom: 20px;
              ">
              附件
            </div>
            <el-form-item label="附件名称" prop="attachName">
              <el-input style="width: 98%;" :disabled="viewType == 'view'" placeholder="请输入附件名称"
                v-model="addForm.attachName"></el-input>
            </el-form-item>
            <el-form-item label="附件上传">
              <!--  :limit="3" -->
              <el-upload class="upload-demo" action="/api/blade-resource/oss/endpoint/put-file"
                :on-success="handleSuccess" :on-remove="handleRemove" multiple :disabled="viewType == 'view'"
                accept=".jpeg,.jpg,.png,.pdf" :on-exceed="handleExceed" :file-list="imgList" :headers="headers">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">支持上传jpeg、jpg、pdf文件，且不超过10M</div>
              </el-upload>
            </el-form-item>
          </div>
          <div>
            <div style="
                color: #101010;
                font-size: 18px;
                font-weight: 550;
                margin-bottom: 20px;
              ">
              巡检相关
            </div>
            <el-form-item label="巡检内容" prop="xjcontent">
              <template slot="label">巡检内容
                <el-tooltip class="item" effect="dark" placement="bottom">
                  <div slot="content">请输入中文；来作为分隔符，自动生成巡检列表！</div>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </template>
              <el-input style="width: 98%;" type="textarea" :disabled="viewType == 'view'" v-model="addForm.xjcontent"
                placeholder="请输入巡检内容" @change="changeContent"></el-input>
            </el-form-item>
            <!-- <el-form-item label="工艺要求" prop="requirement">
              <el-input style="width: 98%;" type="textarea" :disabled="viewType == 'view'" v-model="addForm.requirement"
                placeholder="请输入工艺要求"  @change="changeRequire"></el-input>
            </el-form-item> -->
            <el-form-item label="巡检周期" prop="cycle">
              <el-select v-model="addForm.cycle" :disabled="viewType == 'view'" placeholder="请选择巡检周期"
                style="width: 98%;" @change="changeCycle">
                <el-option v-for="item in periodArr" :key="item.dictKey" :label="item.dictValue"
                  :value="item.dictKey"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="addForm.startTime" :disabled="viewType == 'view'" placeholder="请选择开始时间"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 98%;" @change="changeTime"></el-date-picker>
            </el-form-item>
          </div>
        </el-form>
        <div v-if="tableData.length != 0">
          <el-table :data="tableData">
            <el-table-column label="巡检内容" prop="checkContent"></el-table-column>
            <el-table-column label="工艺要求" prop="craft">
              <template slot-scope="scope">
                <el-input v-model="scope.row.craft" placeholder="工艺要求" :disabled="viewType == 'view'"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="巡检周期" prop="period">
              <template slot-scope="scope">
                <el-select v-model="scope.row.period" placeholder="巡检周期" :disabled="viewType == 'view'">
                  <el-option v-for="item in periodArr" :key="item.dictKey" :label="item.dictValue"
                    :value="item.dictKey"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="开始时间" prop="startTime">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.startTime" placeholder="开始时间" :disabled="viewType == 'view'"
                  format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 98%;"></el-date-picker>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div style="height: 500px; overflow: auto" v-if="detailsTab == '2'">
        <el-collapse accordion>
          <el-collapse-item title="维修记录" name="1">
            <el-table :data="workOrderList" style="width: 100%">
              <el-table-column prop="requirementCode" label="需求单号" width="180">
              </el-table-column>
              <el-table-column prop="faultDescribe" label="故障描述" width="180">
              </el-table-column>
              <el-table-column prop="repairType" label="维修类型">
                <template slot-scope="scope">
                  <span v-if="scope.row.repairType < 0">-</span>
                  <span v-else>
                    <el-select placeholder="请选择维修类别" disabled v-model="scope.row.repairType" size="small">
                      <el-option v-for="item in repairTypeList" :key="item.dictKey" :label="item.dictValue"
                        :value="item.dictKey"></el-option>
                    </el-select>
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="customerOpinion" label="维修人员">
                <template slot-scope="scope">
                  <span v-if="scope.row.repairPerson == ''">-</span>
                  <span v-else>
                    <el-select placeholder="请选择维修人员" :disabled="true" v-model="scope.row.repairPerson" size="small">
                      <el-option v-for="item in repairPersonList" :key="item.id" :label="item.realName"
                        :value="item.id"></el-option>
                    </el-select>
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="提报时间">
              </el-table-column>
            </el-table>
          </el-collapse-item>
          <el-collapse-item title="维保记录" name="2">
            <el-table :data="maintenanceList" style="width: 100%">
              <el-table-column prop="taskCode" label="维保任务单号" width="150">
              </el-table-column>
              <!--  -->
              <el-table-column prop="floorName" label="楼层" width="130">
              </el-table-column>
              <el-table-column prop="deptName" label="房间" width="120">
              </el-table-column>

              <el-table-column prop="startTime" label="开始时间" width="180">
              </el-table-column>
              <el-table-column prop="checkContent" label="巡检内容">

              </el-table-column>
              <el-table-column prop="customerOpinion" label="巡检人员">
                <template slot-scope="scope">
                  <span v-if="scope.row.repairPerson == ''">-</span>
                  <span v-else>
                    <el-select placeholder="请选择维修人员" :disabled="true" v-model="scope.row.servicemanName" size="small">
                      <el-option v-for="item in repairPersonList" :key="item.id" :label="item.realName"
                        :value="item.id"></el-option>
                    </el-select>
                  </span>
                </template>
              </el-table-column>

            </el-table>
          </el-collapse-item>

        </el-collapse>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">关 闭</el-button>
        <!-- <el-button v-show="viewType != 'view'" @click="handleSave">保 存</el-button> -->
        <el-button v-show="viewType != 'view'" type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="需求填报" :visible.sync="requestVisible" :append-to-body="true" width="50%" :close-on-click-modal="false">
      <div style="height: 500px; overflow: auto">
        <requestSub @close="closeRequest" title="需求填报" :form="requestForm"></requestSub>
      </div>
    </el-dialog>
    <el-dialog title="导入设备" :visible.sync="importVisible" :append-to-body="true" width="30%" :close-on-click-modal="false">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <div id="qrcodePrint" style="width: 80%;margin-top: 10px;">
      <img :src="qrcodeUrl" alt="">
      <div>{{  printInfo.name }}</div>
      <div>{{  printInfo.code }}</div>
    </div>
  </basic-container>
</template>

<script>
import website from '@/config/website';
import { getToken, removeToken, removeRefreshToken } from '@/util/auth';
import printJS from 'print-js'
import { mapGetters } from "vuex";
import requestSub from '../components/requestSub.vue'
import { getDeviceList, addDevice, getDetail, editDevice, deleteDevice, qrcode, importFile, getLabList, getWorkOrderList, getMaintenanceList } from '@/api/device/device'
import { getChildList } from '@/api/system/dictbiz'
import { getDeepData } from '@/api/labManagement/inspectionManagement'
import SelectTree from '../../components/selectTree/tree'
import { downloadXls } from "@/util/util";
import { exportBlob } from "@/api/common";
import { dateNow } from "@/util/date";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getRepairPeople } from '@/api/operation/hand'
export default {
  components: {
    requestSub,
    SelectTree
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
  },
  data() {
    return {
      qrcodeUrl: '',
      tableData: [],
      searchForm: {},
      selectionList: [],
      headers:{},
      option: {
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        dialogType: "dialog",
        dialogClickModal: false,
        searchEnter:true,
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        searchShowBtn: false,
        refreshBtn: false,
        columnBtn: false,
        menuWidth: 400,
        selection: true,
        column: [
          {
            label: "设备编码",
            labelWidth: 120,
            prop: "code",
            overHidden: true,
          },
          {
            label: "设备名称",
            labelWidth: 120,
            prop: "name",
            search: true,
            overHidden: true,
          },
          {
            label: "型号",
            labelWidth: 120,
            prop: "model",
            overHidden: true,
          },
          // {
          //   label: "设备位置",
          //   labelWidth: 120,
          //   prop: "position",
          //   type: 'tree',
          //   overHidden: true,
          //   // hide: true,
          //   search: true,
          //   // viewDisplay: false,
          //   dicUrl: '/api/blade-system/dict-biz/child-list?current=1&size=100&parentId=1846792623628001282',
          //   props: {
          //     label: "dictValue",
          //     value: "dictValue",
          //   },
          // },
          {
            label: "设备类型",
            labelWidth: 120,
            prop: "type",
            overHidden: true,
            type: "select",
            searchLabelWidth: 100,
            search: true,
            viewDisplay: false,
            dicUrl: '/api/blade-system/dict-biz/child-list?current=1&size=100&parentId=1846802246527463425',
            props: {
              label: "dictValue",
              value: "dictValue",
            },
          },
          {
            label: "供应商",
            labelWidth: 120,
            prop: "supplier",
            overHidden: true,
            search: true,
          },
          {
            label: "品牌",
            labelWidth: 120,
            prop: "brand",
            overHidden: true,
            search: true,
          },
          {
            label: "单位",
            labelWidth: 120,
            prop: "unit",
            overHidden: true,
            search: true,
          },
          // {
          //   label: "生产时间",
          //   labelWidth: 120,
          //   prop: "produceTime",
          //   slot: true,
          // },
          {
            label: "设备状态",
            labelWidth: 120,
            prop: "status",
            slot: true,
            formslot: true,
          },
          {
            label: "运行状态",
            labelWidth: 120,
            prop: "runStatus",
            slot: true,
            formslot: true,
            search: true,
            type: "select",
            dicData: [
              {
                label: "运行中",
                value: "1",
              },
              {
                label: "故障中",
                value: "2",
              }
            ]
          },
          {
            label: "附件",
            labelWidth: 120,
            prop: "attachName",
            overHidden: true,
            slot: true,
          },
        ],
      },
      importVisible: false,
      treeOptions: [],
      data: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      dialogTitle: '设备新增',
      dialogVisible: false,
      addForm: {
        type: '',
        unit: '',
        position: { node: undefined, data: {} }
      },
      addRules: {
        name: { required: true, message: '请输入设备名称', trigger: 'blur' },
        type: { required: true, message: '请选择设备类型', trigger: 'blur' },
      },
      typeList: [],
      fileList: [],
      imgList: [],
      requestVisible: false,
      requestForm: {},
      viewType: '',
      periodArr: [],
      labProps: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level, value } = node;
          if (level == 0) {
            getLabList().then(res => {
              let firstNode = []
              res.data.data.map(item => {
                firstNode.push({
                  value: item.id,
                  label: item.title,
                  leaf: level >= 2
                })
              })
              resolve(firstNode);
            })
          } else {
            getDeepData({ parentId: value }).then(res => {
              let otherNode = []
              res.data.data.map(item => {
                otherNode.push({
                  value: item.id,
                  label: item.deptName,
                  leaf: level >= 2
                })
              })
              resolve(otherNode);
            })
          }
        }
      },
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/device/import-device?isCovered=0"
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          }
        ]
      },
      role_id: '',//角色id
      detailsTab: '1',//详情tab数据
      workOrderList: [],//维修工单列表
      maintenanceList: [],//巡检工单列表
      repairTypeList: [],//维修类型
      repairPersonList: [],//维修人员列表
      printInfo:{},//打印数据
      dataTypes:null,//
    }
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
  },
  mounted() {
    this.dataTypes=this.userInfo.dataType
    if (this.$route.query.type) {
      this.searchForm = {
        ...this.searchForm,
        runStatus: this.$route.query.type
      }
    }
    this.role_id = this.userInfo.role_id
    getChildList(1, 99999, '1846792623628001282').then(res => {
      this.treeOptions = res.data.data
    })
    getChildList(1, 99999, '1846802246527463425').then(res => {
      this.typeList = res.data.data
    })
    getChildList(1, 99999, '1858710780677984257').then(res => {
      this.periodArr = res.data.data
    })
    // 维修类型
    getChildList(1, 99999, '1869925082102702082').then(res => {
      this.repairTypeList = res.data.data
      this.repairTypeList.forEach(item => {
        item.dictKey = Number(item.dictKey)
      })
    })
    // 维修人员列表
    getRepairPeople({ isRepair: this.role_id == '1839537055389515777' ? true : false }).then(res => {

      this.repairPersonList = res.data.data
    })
    this.headers = {
      "Authorization": `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`,
      'Blade-Auth': 'bearer ' + getToken(),
      'Blade-Requested-With': 'BladeHttpRequest'
    }
    this.onLoad()
  },
  methods: {
    // 获取 维修工单列表

    getWorkOrderList(id) {
      let query = {
        deviceId: id
      }
      getWorkOrderList(query).then(res => {
        this.workOrderList = res.data.data
      })
    },
    // 获取 巡检列表
    getMaintenanceList(id) {
      let query = {
        deviceId: id
      }
      getMaintenanceList(query).then(res => {
        this.maintenanceList = res.data.data
      })
    },
    // 巡检内容修改
    changeContent(val) {

      let arr = val.split('；')
      arr = arr.filter(item => item != '')
      if (this.tableData.length != 0) {
        let arr1 = JSON.parse(JSON.stringify(this.tableData))
        if (val == '' && this.addForm.requirement == '') {
          arr1 = []
        } else {
          if(arr.length == arr1.length){
            arr.map((item, index) => {
              // if(item != ''){
                arr1[index] = {
                  ...arr1[index],
                  checkContent: item,
                  craft: arr1[index] ? item === arr1[index].checkContent ? arr1[index].craft : '' : '',
                  period: arr1[index] ? arr1[index].period : this.addForm.cycle,
                  startTime: arr1[index] ? arr1[index].startTime : this.addForm.startTime
                }
              // }
            })
          }else{
            let arr2 = []
            arr.map((item,index) =>{
              arr2.push({
                checkContent: item,
                craft: arr1[index] ? item === arr1[index].checkContent ? arr1[index].craft : '' : '',
                period: arr1[index] ? arr1[index].period : this.addForm.cycle,
                startTime: arr1[index] ? arr1[index].startTime : this.addForm.startTime
              })
            })
            arr1 = arr2
          }
        }
        this.tableData = arr1
      } else {
        let arr1 = []
        arr.map(item => {
          if (item != '') {
            arr1.push({
              checkContent: item,
              craft:  '',
              period: '',
              startTime: ''
            })
          }
        })
        this.tableData = arr1
      }

      this.$forceUpdate()
    },
    // 工艺要求修改
    changeRequire(val) {
      let arr = val.split('；')
      if (this.tableData.length != 0) {
        let arr1 = JSON.parse(JSON.stringify(this.tableData))
        arr.map((item, index) => {
          if (item != '') {
            arr1[index] = {
              ...arr1[index],
              craft: item,
              period: arr1[index] ? arr1[index].period : this.addForm.period,
              startTime: arr1[index] ? arr1[index].startTime : this.addForm.startTime
            }
          }
        })
        this.tableData = arr1
      } else {
        let arr1 = []
        arr.map(item => {
          if (item != '') {
            arr1.push({
              craft: item,
            })
          }
        })
        this.tableData = arr1
      }
      this.$forceUpdate()
    },
    // 巡检周期修改
    changeCycle(val) {
      let arr = []
      if (this.tableData.length != 0) {
        this.tableData.map(item => {
          item.period = val
        })
        console.log('this.$forceUpdate()--------------->',this.tableData)
        this.$forceUpdate()
      }
    },
    // 巡检开始时间改变
    changeTime(val) {
      if (this.tableData.length != 0) {
        this.tableData.map(item => {
          item.startTime = val
        })
      }
    },
    beforeOpen(done, type) {
      done();
    },
    beforeClose(done) {
      done();
    },
    searchReset(params, done) {
      this.query = params;
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad()
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad()
    },
    selectionChange(list) {
      this.selectionList = list
    },
    addOperation(val) {
      if (val && val.code) {
        this.requestForm = {
          deviceId: val.id
        }
        this.requestVisible = true
      } else {
        this.selectionList.map(item => {

        })
        this.requestVisible = true
      }
    },
    // 生成二维码
    handleQrcode(row) {
      qrcode({ id: row.id }).then(res => {
        if (res.data.code == 200) {
          this.$message.success('二维码已生成')
          this.onLoad()
        }
      })
    },
    // 查看二维码
    lookQrcode(row) {
      this.qrcodeUrl = row.qrcode
      this.printInfo =row
      setTimeout(() => {
        // this.$refs.listPrint.print();
        const style = '@page {margin:0 10mm};' //打印时去掉眉页眉尾
        printJS({
          printable: 'qrcodePrint', // 标签元素id
          type: 'html',
          header: '',
          targetStyles: ['*'],
          scanStyles: true, //打印必须加上，不然页面上的css样式无效
          style
        });
      }, 200)
    },
    closeRequest() {
      this.requestVisible = false
    },
    // 点击新增按钮
    handleAdd() {
      this.dialogTitle = '设备新增'
      this.addForm = { position: { node: undefined, data: {} }, isWarran: false }
      this.viewType = 'add'
      this.tableData = []
      this.fileList = []
      this.imgList = []
      this.dialogVisible = true
      // this.$refs.childTree.resetNode()
    },
    // 点击查看按钮
    handleView(row) {
      this.imgList = []
      this.tableData = []
      getDetail({ id: row.id }).then(res => {
        this.viewType = 'view'
        this.addForm = res.data.data
        this.addForm.position = { node: res.data.data.position, data: {} }
        this.addForm.lab = res.data.data.limsId != -1 && res.data.data.floorId != -1 && res.data.data.roomId != -1 ? [res.data.data.limsId, res.data.data.floorId, res.data.data.roomId] : []
        res.data.data.attaches.map(item => {
          this.imgList.push({
            name: item.name,
            url: item.link
          })
        })
        res.data.data.maintenances.map(item => {
          this.tableData.push({ ...item, period: item.period + '' })
        })
        this.addForm.xjcontent = this.tableData.length > 0 ? this.tableData.map(item => item.checkContent).join('；') : ''
        this.addForm.requirement = this.tableData.length > 0 ? this.tableData.map(item => item.craft).join('；') : ''
        this.addForm.cycle = this.tableData.length > 0 ? this.tableData.find(item => item.period)?this.tableData.find(item => item.period).period+'':undefined : undefined
        this.addForm.startTime = this.tableData.length > 0 ? this.tableData.find(item => item.startTime)?this.tableData.find(item => item.startTime).startTime:'' : ''
        this.addForm.isWarran = this.addForm.isWarran == 0 ? true : false
        this.dialogTitle = '设备查看'
        this.dialogVisible = true
        this.addForm.isMaintain = res.data.data.isMaintain//是否在保
        this.getMaintenanceList(row.id) //维修列表
        this.getWorkOrderList(row.id) //巡检列表
      })
    },
    handleImport() {
      this.importVisible = true
    },
    handleExport() {
      this.$confirm("是否导出设备数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        NProgress.start();
        exportBlob(`/api/device/export-device`).then(res => {
          downloadXls(res.data, `设备数据表${dateNow()}.xlsx`);
          NProgress.done();
        })
      });
    },
    handleTemplate() {
      importFile().then(res => {
        downloadXls(res.data, "设备数据模板.xlsx");
      })
    },
    // 点击编辑按钮
    handleEdit(row) {
      this.fileList = []
      this.imgList = []
      this.tableData = []
      getDetail({ id: row.id }).then(res => {
        this.viewType = 'edit'
        this.addForm = res.data.data
        this.addForm.position = { node: res.data.data.position, data: {} }
        this.addForm.lab = res.data.data.limsId != -1 && res.data.data.floorId != -1 && res.data.data.roomId != -1 ? [res.data.data.limsId, res.data.data.floorId, res.data.data.roomId] : []
        res.data.data.attaches.map(item => {
          this.imgList.push({
            name: item.name,
            url: item.link
          })
          this.fileList.push({
            name: item.name,
            link: item.link
          })
        })
        res.data.data.maintenances.map(item => {
          this.tableData.push({ ...item, period: item.period?item.period+'':null })
        })
        this.addForm.xjcontent =
          this.addForm = {
            ...this.addForm,
            xjcontent: this.tableData.length > 0 ? this.tableData.map(item => item.checkContent).join('；') : '',
            requirement: this.tableData.length > 0 ? this.tableData.map(item => item.craft).join('；') : '',
            cycle: this.tableData.length > 0 ? this.tableData.find(item => item.period)?this.tableData.find(item => item.period).period+'':undefined  : undefined,
            startTime: this.tableData.length > 0 ? this.tableData.find(item => item.startTime)?this.tableData.find(item => item.startTime).startTime:'' : ''
          }
        this.addForm.isWarran = this.addForm.isWarran == 0 ? true : false
        this.dialogTitle = '设备编辑'
        this.dialogVisible = true
        this.getWorkOrderList(row.id)
        this.getMaintenanceList(row.id)
      })
    },
    // 点击复制按钮
    handleCopy(row) {
      this.fileList = []
      this.imgList = []
      this.tableData = []
      getDetail({ id: row.id }).then(res => {
        this.viewType = 'copy'
        this.addForm = res.data.data
        this.addForm.position = { node: res.data.data.position, data: {} }
        this.addForm.lab = res.data.data.limsId != -1 && res.data.data.floorId != -1 && res.data.data.roomId != -1 ? [res.data.data.limsId, res.data.data.floorId, res.data.data.roomId] : []
        res.data.data.attaches.map(item => {
          this.imgList.push({
            name: item.name,
            url: item.link
          })
          this.fileList.push({
            name: item.name,
            link: item.link
          })
        })
        res.data.data.maintenances.map(item => {
          this.tableData.push({ ...item, period: item.period  })
        })
        this.addForm.xjcontent =
          this.addForm = {
            ...this.addForm,
            xjcontent: this.tableData.length > 0 ? this.tableData.map(item => item.checkContent).join('；') : '',
            requirement: this.tableData.length > 0 ? this.tableData.map(item => item.craft).join('；') : '',
            cycle: this.tableData.length > 0 ? this.tableData.find(item => item.period)?this.tableData.find(item => item.period).period:undefined  : null,
            startTime: this.tableData.length > 0 ? this.tableData.find(item => item.startTime)?this.tableData.find(item => item.startTime).startTime:'' : ''
          }
        this.addForm.isWarran = this.addForm.isWarran == 0 ? true : false
        this.dialogTitle = '设备复制'
        this.dialogVisible = true
        // this.getWorkOrderList(row.id)
        // this.getMaintenanceList(row.id)
      })
    },
    // 点击删除按钮
    handleDelete(row) {
      this.$confirm('请确认是否删除该设备?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDevice(row.id).then(res => {
          if (res.data.code == 200) {
            this.onLoad()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }
        })
      }).catch(() => {
      });
    },
    // 点击新增弹窗关闭按钮
    handleClose() {
      this.dialogVisible = false
      this.tableData = []
      this.$refs['form'].resetFields()
      this.addForm = { position: { node: undefined, data: {} } }
    },
    // 点击新增弹窗保存按钮
    handleSave() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.fileList.length == 0) {
            this.$message.error('请至少上传一个附件')
          } else {
            let query = {
              name: this.addForm.name,
              model: this.addForm.model,
              type: this.addForm.type,
              position: this.addForm.position.node,
              supplier: this.addForm.supplier,
              produceTime: this.addForm.produceTime,
              attachName: this.addForm.attachName,
              runStatus: 1,
              attaches: this.fileList,
              unit: this.addForm.unit,
            }
            addDevice(query).then(res => {
            })
            // this.dialogVisible = false
          }
        }
      })
    },
    handleConfirm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let arr = []
          this.fileList.map(item => {
            arr.push({
              name: item.name, link: item.link
            })
          })
          let query = {
            id: this.viewType == 'edit' ? this.addForm.id : null,
            name: this.addForm.name ? this.addForm.name : null,
            model: this.addForm.model ? this.addForm.model : null,
            type: this.addForm.type ? this.addForm.type : null,
            position: this.addForm.position.node ? this.addForm.position.node : null,
            supplier: this.addForm.supplier ? this.addForm.supplier : null,
            produceTime: this.addForm.produceTime ? this.addForm.produceTime.length <= 10 ? this.addForm.produceTime + ' 00:00:00' : this.addForm.produceTime : null,
            attachName: this.addForm.attachName ? this.addForm.attachName : null,
            runStatus: this.addForm.runStatus,
            attaches: arr,
            maintenances: this.tableData,
            // limsId: this.addForm.lab[0],				//实验室id
            // floorId: this.addForm.lab[1],			//楼层id
            // roomId: this.addForm.lab[2],				//房间id
            brand: this.addForm.brand,//品牌
            isWarran: this.addForm.isWarran ? 0 : 1,
            unit: this.addForm.unit,
            description:this.addForm.description
          }
          if(this.addForm.lab&&this.addForm.lab.length>0){
            query.limsId = this.addForm.lab[0]
            query.floorId = this.addForm.lab[1]
            query.roomId = this.addForm.lab[2]
          }
          if (this.viewType == 'add') {
            addDevice(query).then(res => {
              if (res.data.code == 200) {
                this.$message.success('新增成功')
                this.dialogVisible = false
                this.onLoad()
              }
            })
          } else if (this.viewType == 'edit') {
            editDevice(query).then(res => {
              if (res.data.code == 200) {
                this.$message.success('修改成功!')
                this.dialogVisible = false
                this.onLoad()
              }
            })
          } else if (this.viewType == 'copy') {
            query.maintenances.forEach(item => {
              item.id = null
            })
            addDevice(query).then(res => {
              if (res.data.code == 200) {
                this.$message.success('复制成功')
                this.dialogVisible = false
                this.onLoad()
              }
            })
          }
        }
      })
    },
    // 附件上传成功
    handleSuccess(response, file, fileList) {
      this.fileList.push({ name: response.data.originalName, link: response.data.link })
    },
    // 附件删除
    handleRemove(file, fileList) {
      this.imgList = []
      this.fileList = []
      fileList.map(item => {
        this.fileList.push({ name: item.name, link: item.response ? item.response.data.link : item.url })
        this.imgList.push({ name: item.name, url: item.response ? item.response.data.link : item.url })
      })
    },
    onLoad(page, params = {}) {
      let query = {
        name: this.searchForm.name ? this.searchForm.name : '',
        position: this.searchForm.position ? this.searchForm.position : '',
        type: this.searchForm.type ? this.searchForm.type : '',
        current: this.page.currentPage,
        runStatus: this.searchForm.runStatus ? this.searchForm.runStatus : '',//运行状态
        supplier: this.searchForm.supplier ? this.searchForm.supplier : '',//供应商
        brand: this.searchForm.brand ? this.searchForm.brand : '',//品牌
        size: this.page.pageSize,
      }
      if(this.role_id=='1846419477876510721'){
        query.createUser=this.userInfo.user_id
      }
      getDeviceList(query).then(res => {
        this.data = res.data.data.records
        this.page.total = res.data.data.total
        this.loading = false
      })
    },
  }
}
</script>

<style lang="scss">
.el-dialog {
  .el-dialog__title {
    font-size: 22px;
    color: rgb(16, 16, 16);
    font-weight: 550;
  }

  .el-dialog__headerbtn {
    font-size: 20px;
  }

  .details_tab_box {
    margin-bottom: 16px;
  }
}
</style>
