<template>
  <div class="app-container">
    <div>
      <el-button class="font-small" style="margin:0 10px 10px 0" type="primary" icon="el-icon-edit" @click="form_add"> 新增 </el-button>
      <el-button v-waves class="filter-item" type="info" icon="el-icon-tickets" style="margin:0 10px 10px 0" @click="handleDownloadTemp">模板</el-button>
      <el-upload style="display: inline-block;" :headers="headers" :data="uploadData" :action="uploadExcelUrl" :show-file-list="false" :before-upload="beforeImportExcel" :on-success="handleImportExcelSuccess">
        <el-button v-waves class="filter-item" type="warning" icon="el-icon-download">导入</el-button>
      </el-upload>
    </div>
    <el-table
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-style="rowStyle"
      :cell-style="cellStyle"
      class="elTable table-fixed"
      row-key="id"
      default-expand-all
      @sort-change="tableSort"
      :max-height="myHeight"
    >
      <el-table-column label="序号" align="center" type="index" width="50px" />
      <el-table-column label="名称" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.upkeepName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保养类型" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.upkeepType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保养级别" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.upkeepLevel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="周期(天)" min-width="100px" sortable prop="upkeepCycel" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.upkeepCycel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enable"
            :active-value="0"
            :inactive-value="1"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleEnableChange(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="400" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleMaintenanceContents(row)">保养内容</el-button>
          <el-button type="primary" size="mini" @click="handleSparePart(row)">备件</el-button>
          <el-button type="warning" size="mini" @click="handleCopy(row)">复制</el-button>
          <el-button type="success" size="mini" @click="form_edit(row)">编辑</el-button>
          <el-button v-if="row.status!='已删'" size="mini" type="danger" @click="form_delete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹出层新增or修改 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="50%">
      <div class="content-add">
        <el-form
          ref="createTemp"
          :rules="rules"
          :model="createTemp"
          label-position="right"
          label-width="100px"
          style="width: 90%; margin:0 auto;"
        >
          <el-row>
            <el-col :span="20">
              <el-form-item label="保养名称：" prop="upkeepName">
                <el-input ref="upkeepName" v-model="createTemp.upkeepName" type="text" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="保养类型：" prop="upkeepType">
                <el-select v-model="createTemp.upkeepType" placeholder="保养类型" class="filter-item" style="width:100%" @change="changeType">
                  <el-option
                    v-for="item in upkeepTypes"
                    :key="item.id"
                    :label="item.label"
                    :value="item.label"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="保养级别：" prop="upkeepLevel">
                <el-select v-model="createTemp.upkeepLevel" placeholder="保养级别" class="filter-item" style="width:100%">
                  <el-option
                    v-for="item in upkeepgrades"
                    :key="item.id"
                    :label="item.label"
                    :value="item.label"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="isDisplay">
            <el-col :span="20">
              <el-form-item label="保养周期：" prop="upkeepCycel">
                <el-input ref="upkeepCycel" v-model="createTemp.upkeepCycel" type="text" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="启用：" prop="enable">
                <el-switch
                  v-model="createTemp.enable"
                  :active-value="0"
                  :inactive-value="1"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogStatus==='create'" ref="createb" type="success" :disabled="isokDisable" @click="add_dialog_save_again()">保存并新增</el-button>
        <el-button type="primary" :disabled="isokDisable" @click="dialogStatus==='create'?add_dialog_save():edit_dialog_save()">保存并关闭</el-button>
        <el-button @click="dialogFormVisible = false;get_table_data()">取消并关闭</el-button>
      </div>
    </el-dialog>
    <!-- 保养内容 -->
    <el-dialog :title="textMap[dialogStatusMaintenanceContents]" :visible.sync="dialogFormVisibleMaintenanceContents" :close-on-click-modal="false">
      <div class="content-MaintenanceContents">
        <el-form ref="maintenanceTemp" :rules="rules" :model="maintenanceTemp" label-position="right" label-width="100px" style="width: 90%; margin:0 auto;">
          <el-row>
            <el-col :span="10">
              <el-form-item label="保养部位：" prop="partCode">
                <el-autocomplete
                  v-model="maintenanceTemp.positionName"
                  value-key="name"
                  class="inline-input"
                  :fetch-suggestions="maintenanceSearch"
                  placeholder="请输入备件编号或备件名称或备件规格"
                  style="width:550px"
                  @select="handleSelectMaintenance"
                >
                  <template slot-scope="{ item }">
                    <span class="addr">{{ item.positionName }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          element-loading-text="给我一点时间"
          :data="listMaintenance"
          border
          fit
          highlight-current-row
          style="width: 100%;margin-bottom:30px"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable"
        >
          <!-- table表格 -->
          <el-table-column label="序号" align="center" type="index" width="50px" />
          <el-table-column label="部位" min-width="90px" prop="positionName" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.positionName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="项目" valign="middle" min-width="80px" align="center">
            <template slot-scope="scope">
              <el-input ref="program" v-model="scope.row.program" />
            </template>
          </el-table-column>
          <el-table-column label="标准" valign="middle" prop="standard" align="center" min-width="100">
            <template slot-scope="scope">
              <el-input ref="active" v-model="scope.row.standard" />
            </template>
          </el-table-column>
          <el-table-column valign="middle" label="执行动作" min-width="90px" align="center">
            <template slot-scope="scope">
              <el-form :model="scope.row">
                <el-form-item prop="active">
                  <el-select
                    v-model="scope.row.active"
                    placeholder="执行动作"
                    class="filter-item"
                    style="width:100%;margin-top:15px"
                    @change="handleActive"
                  >
                    <el-option
                      v-for="item in listActive"
                      :key="item.id"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{row}">
              <!-- <a class="primary" @click="maintenanceSave(row)">保存</a> -->
              <a class="del" @click="maintenanceDelete(row)">删除</a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer" style="bottom:10px">
        <el-button type="primary" :disabled="isokDisable" @click="maintenanceSave()">保存并关闭</el-button>
        <el-button @click="dialogFormVisibleMaintenanceContents = false;get_table_data()">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 备件 -->
    <el-dialog :title="textMap[dialogStatusSparePart]" :visible.sync="dialogFormVisibleSparePart" :close-on-click-modal="false">
      <div class="content-SparePart">
        <el-form
          ref="sparePartTemp"
          :rules="rules"
          :model="sparePartTemp"
          label-position="right"
          label-width="100px"
          style="width: 90%; margin:0 auto;"
        >
          <el-row>
            <el-col :span="10">
              <el-form-item label="备件：" prop="partCode">
                <el-autocomplete
                  v-model="sparePartTemp.partCode"
                  value-key="name"
                  class="inline-input"
                  :fetch-suggestions="sparePartSearch"
                  placeholder="请输入备件编号或备件名称或备件规格"
                  style="width:550px"
                  @select="handleSelectSparePart"
                >
                  <template slot-scope="{ item }">
                    <b>编号：</b><div class="name" style="display: inline;">{{ item.partCode }}</div>&nbsp;
                    |  &nbsp;<b>名称：</b><span class="addr">{{ item.name }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          element-loading-text="给我一点时间"
          :data="listSparePart"
          border
          fit
          highlight-current-row
          style="width: 100%;margin-bottom:30px"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable"
        >
          <!-- table表格 -->
          <el-table-column label="序号" align="center" type="index" width="50px" />
          <el-table-column label="备件编号" min-width="90px" prop="partCode" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.partCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备件名称" min-width="80px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.partName }}</span><br>
            </template>
          </el-table-column>
          <el-table-column label="备件规格" prop="specification" align="center" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.specification }}</span>
            </template>
          </el-table-column>
          <el-table-column valign="middle" label="数量" min-width="90px" align="center">
            <template slot-scope="scope">
              <el-form :model="scope.row" :rules="rules">
                <el-form-item prop="amount">
                  <el-input
                    ref="amount"
                    v-model="scope.row.amount"
                    style="margin-top:15px"
                  />
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column valign="middle" label="备注" min-width="90px" align="center">
            <template slot-scope="scope">
              <el-form :model="scope.row" :rules="rules">
                <el-form-item prop="note">
                  <el-input
                    ref="note"
                    v-model="scope.row.note"
                    style="margin-top:15px"
                  />
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{row}">
              <!-- <a class="primary" @click="partSave(row)">保存</a> -->
              <a class="del" @click="partDelete(row)">删除</a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer" style="bottom:10px">
        <el-button type="primary" :disabled="isokDisable" @click="partSave()">保存并关闭</el-button>
        <el-button @click="dialogFormVisibleSparePart = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 复制 -->
    <el-dialog :title="textMap[dialogStatusCopy]" :visible.sync="dialogFormVisibleCopy" :close-on-click-modal="false">
      <div class="content-copy">
        <el-form
          label-position="right"
          label-width="110px"
          style="width: 90%px; margin: 0 auto;"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="设备类别：" prop="NewName">
                <tree-select
                  :disabled="disabled"
                  :height="300"
                  :width="300"
                  size="small"
                  multiple
                  :data="parentType"
                  :default-props="defaultProps"
                  collapse-tags
                  :node-key="nodeKey"
                  :checked-keys="defaultCheckedKeys"
                  @popoverHide="popoverHide"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="right:30px;position:absolute;bottom:30px">
          <el-button type="primary" @click="dialogStatus==='create'?createCopyData():createCopyData()">确认</el-button>
          <el-button @click="dialogFormVisibleCopy = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import enterToNext from '@/directive/enterToNext' // enterToNext directive
import { PostDataByName, GetDataByNames, GetDataByName, transData, ExecDataByConfig, failproccess } from '@/api/common'
import { MessageBox } from 'element-ui'
import TreeSelect from '@/components/TreeSelect'
import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'
import { parseTime, sortChange } from '@/utils/index.js'
export default {
  name: 'Baoyang',
  components: { TreeSelect },
  directives: { waves, enterToNext },
  props: {
    assetTypeid: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      parentType: [],
      getParmType: {
        name: 'geteqclasslist'
        // idname: 'id',
        // params: [-1]
      },
      defaultProps: {
        children: 'children',
        label: 'typeName'
      },
      nodeKey: 'id',
      defaultCheckedKeys: [],
      dataform: {
        id: '',
        name: '',
        selectType: [],
        sort: '',
        enable: ''
      },
      UpdateDataRelationParam: {
        name: '',
        dataname: '',
        datavalue: '',
        valuename: '',
        values: ''
      },
      getdataListParm: {
        name: 'getPartList',
        parammaps: {
          id: ''
        }
      },
      copyTemp: {},
      upkeepTypes: [],
      upkeepgrades: [],
      listActive: [],
      requestParams: [
        { name: 'getDictByName1', offset: 0, pagecount: 0, params: ['保养类型'] },
        { name: 'getDictByName2', offset: 0, pagecount: 0, params: ['保养级别'] },
        { name: 'getDictByName', offset: 0, pagecount: 0, params: ['保养模板执行动作'] }
      ],
      isDisplay: false,
      textMap: {
        create: '新增',
        update: '编辑',
        copy: '复制',
        maintenanceContents: '保养内容',
        sparePart: '备件'
      },
      dialogFormVisibleCopy: false,
      dialogStatusCopy: '',
      disabled: false,
      getdataListParmUpkeep: {
        name: 'getBigUpkeepTemplate',
        parammaps: {
          id: ''
        }
      },
      list: [],
      total: 0,
      listLoading: true,
      dialogStatus: '',
      dialogFormVisible: false,
      createTemp: {
        upkeepName: '',
        upkeepType: '',
        upkeepLevel: '',
        upkeepCycel: '',
        enable: 0
      },
      tableKey: 0,
      isokDisable: false,
      postDataPramas: {},
      dialogStatusMaintenanceContents: '',
      dialogFormVisibleMaintenanceContents: false,
      dialogFormVisibleSparePart: false,
      dialogStatusSparePart: '',
      getdataListParmSee: {
        name: 'getPositionPartBypid',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {}
      },
      requestParam: {},
      requestMaintenance: {
        name: 'getPositionByName',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
        }
      },
      getMaintenanceListParm: {
        name: 'getUpkeepTemplateListbyeq',
        parammaps: {
          id: ''
        }
      },

      maintenanceTemp: {},
      listMaintenance: [],
      postMaintenancePramas: {},
      requestSparePart: {
        name: 'getPartsListUpkeep',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {}
      },
      getSparePartListParm: {
        name: 'getUpkeepPartListbyeq',
        parammaps: {
          id: ''
        }
      },
      sparePartTemp: {},
      listSparePart: [],
      postSparePartPramas: {},
      rules: {
        upkeepName: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
        upkeepType: [{ required: true, message: '必填', trigger: 'blur' }],
        upkeepLevel: [{ required: true, message: '必填', trigger: 'blur' }],
        upkeepCycel: [{ type: 'number', required: true, validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('不能为空'))
          }
          setTimeout(() => {
            const re = /^[0-9]*[1-9][0-9]*$/ // /^[0-9]*[1-9][0-9]*$/
            const rsCheck = re.test(value)
            if (!rsCheck) {
              callback(new Error('请输入正整数'))
            } else {
              callback()
            }
          }, 0)
        }, trigger: 'blur' }]
      },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      myHeight:document.documentElement.clientHeight - 85- 200
    }
  },
  computed: {
    headers() {
      return {
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'updateUpKeepT',
        importParams: '设备类别名称,保养模板名称,保养级别,保养周期,保养类型,部位,项目,标准,执行动作',
        sheetname: 'SheetJS'
      }
    },
    // 设置上传地址
    uploadExcelUrl() {
      return process.env.VUE_APP_BASE_API + 'authdata/ImportExcel'
    }
  },

  watch: {
    assetTypeid(val) {
      console.log(val)
      if (this.assetTypeid != null) {
        this.getdataListParmUpkeep.parammaps.id = this.assetTypeid
        this.get_table_data()
        this.getTypeList()
      }
    }
  },
  created() {
    this.get_table_data()
    this.get_select_list()
  },

  // 设置变量

  methods: {
    tableSort(column) {
      sortChange(column, this.list)
    },
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.upkeepTypes = response.data.getDictByName1.list
        this.upkeepgrades = response.data.getDictByName2.list
        this.listActive = response.data.getDictByName.list
      })
    },
    get_table_data() {
      this.listLoading = true
      GetDataByName(this.getdataListParmUpkeep).then(response => {
        console.log('部位table数据', response.data.list)
        this.list = response.data.list
        if (response.data.total) {
          this.total = response.data.total
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    handleEnableChange(index, row) {
      this.requestParam.name = 'setBigUpkeepTemplate'
      this.requestParam.parammaps = {}
      this.requestParam.parammaps.id = row.id
      this.requestParam.parammaps.enable = row.enable
      PostDataByName(this.requestParam).then(() => {
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    resetCreateTemp() {
      this.createTemp.upkeepName = ''
      this.createTemp.upkeepType = ''
      this.createTemp.upkeepLevel = ''
      this.createTemp.enable = 0
    },
    form_add() {
      if (this.assetTypeid != '') {
        this.resetCreateTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        console.log(this.assetTypeid)
      }
    },
    handleActive(val) {
      console.log('执行动作', val)
    },
    changeType(item) {
      console.log(item)
      if (item == '间隔保养') {
        this.createTemp.upkeepCycel = ''
        this.isDisplay = true
      } else if (item == '周保养') {
        this.createTemp.upkeepCycel = 7
        this.isDisplay = false
      } else if (item == '月保养') {
        this.createTemp.upkeepCycel = 30
        this.isDisplay = false
      }
    },
    add_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.postDataPramas.name = 'insertBigUpkeepTemplate'
          this.postDataPramas.parammaps = this.createTemp
          this.postDataPramas.parammaps.eqclassId = this.assetTypeid
          PostDataByName(this.postDataPramas).then(response => {
            console.log('新增保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              this.get_table_data()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      })
    },
    add_dialog_save_again() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.postDataPramas.name = 'insertBigUpkeepTemplate'
          this.postDataPramas.parammaps = this.createTemp
          this.postDataPramas.parammaps.eqclassId = this.assetTypeid
          PostDataByName(this.postDataPramas).then(response => {
            console.log('新增保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              this.resetCreateTemp()
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      })
    },

    handleCopy(row) {
      if (this.assetTypeid != '') {
        this.dialogFormVisibleCopy = true
        this.dialogStatusCopy = 'copy'
        this.defaultCheckedKeys = []
        this.copyTemp = Object.assign({}, row)
      }
    },
    createCopyData() {
      console.log(this.dataform.selectType)
      if (this.dataform.selectType.length === 0) {
        this.$message({
          message: '请选择设备',
          type: 'warning',
          duration: 2000
        })
      } else {
        var selectedType = []
        for (var i = 0; i < this.dataform.selectType.length; i++) {
          var checkedIdsObj = {}
          checkedIdsObj['newEqclassId'] = this.dataform.selectType[i]
          selectedType.push(checkedIdsObj)
        }
        console.log('处理选中值', selectedType)
        this.dialogStatusCopy = 'copy'
        this.dialogFormVisibleCopy = true
        this.postDataPramas.common = { 'returnmap': '0' }
        this.postDataPramas.data = []
        this.postDataPramas.data[0] = { 'name': 'insertSpotList', 'resultmaps': { 'list': selectedType }}
        this.postDataPramas.data[0].children = []
        this.postDataPramas.data[0].children[0] = { 'name': 'CopyUpKeep', 'type': 'e', 'parammaps': {
          newEqclassId: '@insertSpotList.newEqclassId',
          eqclassid: this.copyTemp.id
        }}
        ExecDataByConfig(this.postDataPramas).then(response => {
          console.log('复制保存发送参数', this.postDataPramas)
          if (response.msg !== 'fail') {
            this.dialogFormVisibleCopy = false
            this.$notify({
              title: '成功',
              message: '复制成功',
              type: 'success',
              duration: 2000
            })
          } else {
            failproccess(response, this.$notify)
          }
        })
      }
    },
    popoverHide(checkedIds, checkedData) {
      console.log('选中值', checkedIds, checkedData)
      this.dataform.selectType = checkedIds
      this.UpdateDataRelationParam.values = checkedIds
      // eslint-disable-next-line no-unreachable
    },
    getTypeList() {
      GetDataByName(this.getParmType).then(response => {
        if (response.data.list !== null) {
          this.parentType = transData(response.data.list, 'id', 'pid', 'children')
        }
      })
    },
    handleMaintenanceContents(row) {
      this.maintenanceTemp = Object.assign({}, row)
      this.maintenanceTemp.bigId = row.id
      console.log(row)
      this.dialogStatusMaintenanceContents = 'maintenanceContents'
      this.dialogFormVisibleMaintenanceContents = true
      this.getMaintenanceList()
    },
    getMaintenanceList() {
      this.getMaintenanceListParm.parammaps.id = this.maintenanceTemp.id
      GetDataByName(this.getMaintenanceListParm).then(response => {
        console.log('保养部位数据', response.data.list)
        this.listMaintenance = response.data.list
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    maintenanceSearch(queryString, cb) {
      console.log('保养部位模糊查询输入值', queryString)
      this.requestMaintenance.parammaps['positionName'] = queryString
      this.requestMaintenance.parammaps.id = this.assetTypeid
      GetDataByName(this.requestMaintenance).then(response => {
        console.log('保养部位模糊查询搜索data', response.data.list)
        cb(response.data.list)
      })
    },
    handleSelectMaintenance(item) {
      console.log('保养部位模糊查询选中值', item)
      if (this.listMaintenance != null) {
        this.$set(item, 'positionId', item.id)
        this.$set(item, 'myid', new Date().getTime())
        this.listMaintenance.push(item)
      } else {
        this.listMaintenance = []
        this.$set(item, 'myid', new Date().getTime())
        this.$set(item, 'positionId', item.id)
        this.listMaintenance.push(item)
      }
    },
    maintenanceDelete(row) {
      console.log(row)
      console.log(this.listMaintenance)
      MessageBox.confirm('名称：' + row.positionName, '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for (var i = 0; i < this.listMaintenance.length; i++) {
          console.log(this.listMaintenance[i])
          if (this.listMaintenance[i].myid == row.myid) {
            var listMaintenanceIndex = this.listMaintenance.indexOf(this.listMaintenance[i])
          }
          if (listMaintenanceIndex > -1) {
            this.listMaintenance.splice(listMaintenanceIndex, 1)
            return
          }
        }
      })
    },
    maintenanceSave(row) {
      if (this.listMaintenance.length !== 0) {
        for (var i = 0; i < this.listMaintenance.length; i++) {
          if (this.listMaintenance[i].program !== '' && this.listMaintenance[i].standard !== '' && this.listMaintenance[i].active !== '' && this.listMaintenance[i].program !== null && this.listMaintenance[i].standard !== null && this.listMaintenance[i].active !== null && this.listMaintenance[i].program !== undefined && this.listMaintenance[i].standard !== undefined && this.listMaintenance[i].active !== undefined) {
            this.postDataPramas.common = { 'returnmap': '0' }
            this.postDataPramas.data = []
            this.postDataPramas.data[0] = { 'name': 'deleteUpkeepTemplateListbyeq', 'type': 'e', 'parammaps': {
              id: this.maintenanceTemp.id
            }}
            this.postDataPramas.data[1] = { 'name': 'insertSpotList', 'resultmaps': { 'list': this.listMaintenance }}
            this.postDataPramas.data[1].children = []
            this.postDataPramas.data[1].children[0] = { 'name': 'insertUpkeepTemplate', 'type': 'e', 'parammaps': {
              bigId: this.maintenanceTemp.id,
              positionId: '@insertSpotList.positionId',
              program: '@insertSpotList.program',
              standard: '@insertSpotList.standard',
              active: '@insertSpotList.active',
              eqclassId: this.assetTypeid
            }}
          } else {
            this.$message({
              message: '请完善保养内容',
              type: 'warning',
              duration: 2000
            })
          }
        }
        ExecDataByConfig(this.postDataPramas).then(response => {
          console.log('备件保存发送参数', this.postDataPramas)
          if (response.msg !== 'fail') {
            this.dialogFormVisibleMaintenanceContents = false
            this.get_table_data()
            this.$notify({
              title: '成功',
              message: '保养成功',
              type: 'success',
              duration: 2000
            })
          } else {
            failproccess(response, this.$notify)
          }
        })
      }
    },

    handleSparePart(row) {
      this.sparePartTemp = Object.assign({}, row)
      this.dialogStatusSparePart = 'sparePart'
      this.dialogFormVisibleSparePart = true
      this.getSparePartList()
    },
    getSparePartList() {
      this.getSparePartListParm.parammaps.id = this.sparePartTemp.id
      GetDataByName(this.getSparePartListParm).then(response => {
        console.log('备件数据', response.data.list)
        this.listSparePart = response.data.list
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    sparePartSearch(queryString, cb) {
      console.log('备件模糊查询输入值', queryString)
      this.requestSparePart.parammaps['partCode'] = queryString
      this.requestSparePart.parammaps.eqClassId = this.assetTypeid
      GetDataByName(this.requestSparePart).then(response => {
        console.log('备件模糊查询搜索data', response.data.list)
        cb(response.data.list)
      })
    },
    handleSelectSparePart(item) {
      console.log('备件模糊查询选中值', item)
      if (this.listSparePart != null) {
        // eslint-disable-next-line no-redeclare
        if (this.listSparePart.find(obj => obj.partId === item.id)) {
          this.$message({
            type: 'warning',
            message: '此备件已存在，请重新选择备件'
          })
        } else {
          this.$set(item, 'partId', item.id)
          this.$set(item, 'myid', new Date().getTime())
          this.listSparePart.push(item)
        }
      } else {
        this.listSparePart = []
        this.$set(item, 'partId', item.id)
        this.$set(item, 'myid', new Date().getTime())
        this.listSparePart.push(item)
      }
      this.sparePartTemp.partCode = ''
    },
    partDelete(row) {
      console.log(row)
      console.log(this.listSparePart)
      MessageBox.confirm('名称：' + row.positionName, '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          for (var i = 0; i < this.listSparePart.length; i++) {
            console.log(this.listSparePart[i])
            if (this.listSparePart[i].myid == row.myid) {
              var listSparePartIndex = this.listSparePart.indexOf(this.listSparePart[i])
            }
            if (listSparePartIndex > -1) {
              this.listSparePart.splice(listSparePartIndex, 1)
              return
            }
          }
        })
    },
    partSave() {
      if (this.listSparePart.length !== 0) {
        for (var i = 0; i < this.listSparePart.length; i++) {
          if (this.listSparePart[i].amount !== '' && this.listSparePart[i].amount !== null && this.listSparePart[i].amount !== undefined) {
            this.postDataPramas.common = { 'returnmap': '0' }
            this.postDataPramas.data = []
            this.postDataPramas.data[0] = { 'name': 'deleteUpkeepPartbyeq', 'type': 'e', 'parammaps': {
              id: this.sparePartTemp.id
            }}
            this.postDataPramas.data[1] = { 'name': 'insertSpotList', 'resultmaps': { 'list': this.listSparePart }}
            this.postDataPramas.data[1].children = []
            this.postDataPramas.data[1].children[0] = { 'name': 'insertUpkeepPart', 'type': 'e', 'parammaps': {
              bigId: this.sparePartTemp.id,
              partId: '@insertSpotList.partId',
              partName: '@insertSpotList.partName',
              partCode: '@insertSpotList.partCode',
              specification: '@insertSpotList.specification',
              amount: '@insertSpotList.amount',
              note: '@insertSpotList.note'
            }}
          } else {
            this.$message({
              message: '请完善保养内容',
              type: 'warning',
              duration: 2000
            })
          }
        }
        ExecDataByConfig(this.postDataPramas).then(response => {
          console.log('备件保存发送参数', this.postDataPramas)
          if (response.msg !== 'fail') {
            this.dialogFormVisibleSparePart = false
            this.get_table_data()
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          } else {
            failproccess(response, this.$notify)
          }
        })
      }
    },
    // partSave(row) {
    //   if (row.amount !== '' && row.amount !== null && row.amount !== undefined) {
    //     this.postSparePartPramas.name = 'insertUpkeepPart'
    //     this.postSparePartPramas.parammaps = row
    //     this.postSparePartPramas.parammaps.eqclassId = this.assetTypeid
    //     this.postSparePartPramas.parammaps.bigId = this.sparePartTemp.id
    //     PostDataByName(this.postSparePartPramas).then(response => {
    //       console.log('新增保存发送参数', this.postDataPramas)
    //       if (response.msg === 'fail') {
    //         this.$notify({
    //           title: '保存失败',
    //           message: response.data,
    //           type: 'warning',
    //           duration: 2000
    //         })
    //       } else {
    //         this.getSparePartList()
    //         this.$notify({
    //           title: '',
    //           message: '保存成功',
    //           type: 'success',
    //           duration: 2000
    //         })
    //       }
    //     })
    //   } else {
    //     this.$message({
    //       message: '请完善保养内容',
    //       type: 'warning',
    //       duration: 2000
    //     })
    //   }
    // },
    // partDelete(row) {
    //   console.log(row)
    //   console.log(this.listMaintenance)
    //   MessageBox.confirm('确认是否删除当前信息?', {
    //     confirmButtonText: '确认',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     this.postSparePartPramas.name = 'deleteUpkeepPart'
    //     this.postSparePartPramas.parammaps = {}
    //     this.postSparePartPramas.parammaps.id = row.id
    //     PostDataByName(this.postSparePartPramas).then(response => {
    //       console.log('新增保存发送参数', this.postDataPramas)
    //       if (response.msg === 'fail') {
    //         this.$notify({
    //           title: '保存失败',
    //           message: response.data,
    //           type: 'warning',
    //           duration: 2000
    //         })
    //       } else {
    //         this.getSparePartList()
    //         this.$notify({
    //           title: '',
    //           message: '保存成功',
    //           type: 'success',
    //           duration: 2000
    //         })
    //       }
    //     })
    //   })
    // },

    form_edit(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.createTemp = Object.assign({}, row)
      this.$nextTick(() => {
        this.$refs['createTemp'].clearValidate()
      })
    },
    edit_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.postDataPramas.name = 'updateBigUpkeepTemplate'
          this.postDataPramas.parammaps = this.createTemp
          PostDataByName(this.postDataPramas).then(response => {
            console.log('编辑保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              this.get_table_data()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      })
    },
    form_delete(row) {
      MessageBox.confirm('确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.requestParam.name = 'deleteBigUpkeepTemplate'
          this.requestParam.parammaps = {}
          this.requestParam.parammaps.id = row.id
          PostDataByName(this.requestParam).then((response) => {
            if (response.msg !== 'fail') {
              this.get_table_data()
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            } else {
              failproccess(response, this.$notify)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    beforeImportExcel(file) {
      const isLt2M = file.size / 1024 / 1024 < 6
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 6MB!')
      }
      return isLt2M
    },
    handleImportExcelSuccess(res, file) {
      this.get_table_data()
      if (res.msg === 'ok') {
        this.$message({
          title: '成功',
          message: '导入成功:' + res.data.success + '条!',
          type: 'success',
          duration: 2000
        })
        if (res.data.err_count > 0) {
          this.$notify({
            title: '失败',
            message: '导入失败:' + res.data.err_count + '条!',
            type: 'danger',
            duration: 2000
          })
           import('@/vendor/Export2Excel').then(excel => {
             const list1 = res.data.result
             const tHeader = [
               '设备类别名称', '保养模板名称', '保养级别', '保养周期', '保养类型', '部位', '项目', '标准', '执行动作', '报错信息'
             ]
             const filterVal = [
               '设备类别名称', '保养模板名称', '保养级别', '保养周期', '保养类型', '部位', '项目', '标准', '执行动作', 'error_msg'
             ]
             const data1 = this.formatJson(filterVal, list1)
             excel.export_json_to_excel({
               header: tHeader,
               data: data1,
               filename: '保养模板报错信息',
               autoWidth: true,
               bookType: 'xlsx'
             })
           })
        }
      } else {
        this.$notify({
          title: '失败',
          message: '上传失败',
          type: 'danger',
          duration: 2000
        })
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    // 导出模板
    handleDownloadTemp() {
      this.requestParam.name = 'pStockDownTemp'
      GetDataByName(this.requestParam).then(response => {
        this.$nextTick(() => {
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = response.data.list
            const tHeader = [
              '设备类别名称', '保养模板名称', '保养级别', '保养周期', '保养类型', '部位', '项目', '标准', '执行动作'
            ]
            const filterVal = [
              '设备类别名称', '保养模板名称', '保养级别', '保养周期', '保养类型', '部位', '项目', '标准', '执行动作'
            ]
            const data1 = this.formatJson(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '保养模板',
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
      })
    },
    // ------------------------------------------------------------------
    jump() {
      this.$router.push('/console/menu')
    }
  }
}
</script>
