<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>

    </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.describe }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="260" fixed="right">
        <template slot-scope="{row}">

          <el-button type="danger" size="mini" @click="updateDelete(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-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="故障详情：" prop="describe">
                <el-input ref="describe" v-model="createTemp.describe" type="text" />
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button ref="createb" type="success" :disabled="isokDisable" @click="add_dialog_save_again()">保存并新增</el-button>
        <el-button type="primary" :disabled="isokDisable" @click="add_dialog_save()">保存并关闭</el-button>
        <el-button @click="dialogFormVisible = false;get_table_data()">取消并关闭</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import enterToNext from '@/directive/enterToNext' // enterToNext directive
import { PostDataByName, 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: 'Miaoshu',
  components: { TreeSelect },
  directives: { waves, enterToNext },
  props: {
    assetTypeid: {
      type: Number,
      default: 0
    },
    assetTypename: {
      type: String,
      default: '1'
    },
    assetAction: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      textMap: {
        create: '新增',
        update: '编辑',
        copy: '复制',
        see: '查看详情',
        addFault: '添加故障'
      },

      eqClassId:"",
      dialogFormVisibleCopy: false,
      dialogStatusCopy: '',
      disabled: false,
      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: 'getFaultdescription',
        parammaps: {
          id: '',
          eqClassId: '',
        }
      },
      list: [],
      total: 0,
      listLoading: true,
      dialogStatus: '',
      dialogFormVisible: false,
      createTemp: {
        positionId: '',
        describe: '',
        note: ''
      },
      listPart: [],

      tableKey: 0,
      isokDisable: false,
      postDataPramas: {},

      dialogStatusSee: '',
      isDisplay: false,
      dialogFormVisibleSee: false,
      listLoadingSee: true,
      totalSee: 0,
      listSee: [],
      getdataListParmSee: {
        name: 'getAppearancebyPid',
        returntype: 'Map',
        parammaps: {}
      },
      postUpdatePramas: {},
      requestParam: {},
      update: false,
      see: false,
      rules: {

        describe: [{ type: 'string', required: true, message: '必填', 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: 'updateUpKeepAppearance',
        importParams: '设备类别名称,部位,故障详情,备注',
        sheetname: 'SheetJS'
      }
    },
    // 设置上传地址
    uploadExcelUrl() {
      return process.env.VUE_APP_BASE_API + 'authdata/ImportExcel'
    }
  },
  watch: {
    assetTypeid(val) {
      console.log(val)
      if (this.assetTypeid != null) {
        this.getdataListParm.parammaps.id = this.assetTypeid
        this.getdataListParm.parammaps.eqClassId = this.assetTypeid
        this.eqClassId = this.assetTypeid
        console.log('eqClassId',eqClassId)
        this.get_table_data()


      }
    },
    assetTypename(val) {
      console.log(val)
    },
    assetAction(val) {
      console.log(val)
      this.get_table_data()
    }
  },
  created() {
    this.get_table_data()
  },

  // 设置变量

  methods: {
    // ------------------------------------------------------------------
    tableSort(column) {
      sortChange(column, this.list)
    },
    get_table_data() {
      this.listLoading = true
      GetDataByName(this.getdataListParm).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)
      })
    },
    resetCreateTemp() {
      this.createTemp.describe = ''
      this.createTemp.note = ''
    },

    form_add() {
      if (this.assetTypeid != '') {
        this.resetCreateTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.createTemp.positionId = ''
        console.log(this.assetTypeid)
        console.log(this.assetTypename)
        console.log(this.assetLable)

        console.log(this.listPart)
      }
    },

    partDelete(row) {
      console.log(this.listAdd)
      MessageBox.confirm('设备名称：' + row.partName, '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log(this.list2)
        for (var i = 0; i < this.listAdd.length; i++) {
          console.log(this.listAdd[i])
          if (this.listAdd[i].id === row.id) {
            var listAddIndex = this.listAdd.indexOf(this.listAdd[i])
          }
          if (listAddIndex > -1) {
            this.listAdd.splice(listAddIndex, 1)
            return
          }
        }
      })
    },
    add_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.postDataPramas.name = 'insertAppearance'
          this.postDataPramas.parammaps = this.createTemp
          this.postDataPramas.parammaps.eqClassId = this.assetTypeid
          this.postDataPramas.parammaps.eqClassName = this.assetTypename

          var send_data={
            name:'addFaultdescription',
            parammaps:{
              describe:this.createTemp.describe,
              eqClassId:this.assetTypeid,
            }
          }
          PostDataByName(send_data).then(response => {
            console.log('新增保存发送参数', this.postDataPramas)
            if (response.msg === 'fail') {
              this.$notify({
                title: '保存失败',
                message: response.data,
                type: 'warning',
                duration: 2000
              })
            } else {
              this.dialogFormVisible = false
              this.get_table_data()
              this.$notify({
                title: '',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    add_dialog_save_again() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.postDataPramas.name = 'insertAppearance'
          this.postDataPramas.parammaps = this.createTemp
          this.postDataPramas.parammaps.eqClassId = this.assetTypeid
          this.postDataPramas.parammaps.eqClassName = this.assetTypename

          var send_data={
            name:'addFaultdescription',
            parammaps:{
              describe:this.createTemp.describe,
              eqClassId:this.assetTypeid,
            }
          }
          PostDataByName(send_data).then(response => {
            console.log('新增保存发送参数', send_data)
            if (response.msg === 'fail') {
              this.$notify({
                title: '保存失败',
                message: response.data,
                type: 'warning',
                duration: 2000
              })
            } else {
              this.resetCreateTemp()
              console.log(this.dialogStatus)

              this.$notify({
                title: '',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },




    form_edit(row) {
      console.log(row)
      this.seeTemp = Object.assign({}, row)
      this.dialogStatusSee = 'update'
      this.isDisplay = true
      this.update = true
      this.see = false
      this.dialogFormVisibleSee = true
      this.getdataListParmSee.parammaps.id = row.id
      this.get_table_dataSee()
    },
    updateSave(row) {
      if (row.describe !== '' && row.describe !== null && row.describe !== undefined) {
        this.postUpdatePramas.name = 'updateAppearance'
        this.postUpdatePramas.parammaps = row
        PostDataByName(this.postUpdatePramas).then(response => {
          console.log('新增保存发送参数', this.postDataPramas)
          if (response.msg === 'fail') {
            this.$notify({
              title: '保存失败',
              message: response.data,
              type: 'warning',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      } else {
        this.$message({
          message: '请完善保养内容',
          type: 'warning',
          duration: 2000
        })
      }
    },
    updateDelete(row) {
      console.log(row)
      MessageBox.confirm('确认是否删除当前信息?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.postUpdatePramas.name = 'delFaultdescription'
        this.postUpdatePramas.parammaps = {}
        this.postUpdatePramas.parammaps.id = row.id
        PostDataByName(this.postUpdatePramas).then(response => {
          console.log('新增保存发送参数', this.postDataPramas)
          if (response.msg === 'fail') {
            this.$notify({
              title: '保存失败',
              message: response.data,
              type: 'warning',
              duration: 2000
            })
          } else {
            this.get_table_data()
            this.get_table_dataSee()
            this.$notify({
              title: '',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      })
    },

    addFaultData() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.postDataPramas.name = 'insertAppearance'
          this.postDataPramas.parammaps = this.createTemp
          this.postDataPramas.parammaps.eqClassId = this.assetTypeid
          this.postDataPramas.parammaps.eqClassName = this.assetTypename
          PostDataByName(this.postDataPramas).then(response => {
            console.log('添加故障保存发送参数', this.postDataPramas)
            if (response.msg === 'fail') {
              this.$notify({
                title: '保存失败',
                message: response.data,
                type: 'warning',
                duration: 2000
              })
            } else {
              this.dialogFormVisible = false
              this.get_table_data()
              this.$notify({
                title: '',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    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]
          }
        })
      )
    },
    // ------------------------------------------------------------------
    jump() {
      this.$router.push('/console/menu')
    }
  }
}
</script>
