<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 class="font-small" type="warning" icon="el-icon-copy-document" style="margin:0 10px 10px 0" @click="handleCopy"> 复制 </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"
    >
      <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.positionName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="常见故障数量" sortable prop="cou" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.cou }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="260" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="form_see(row)">查看</el-button>
          <el-button type="danger" size="mini" @click="handleAddFault(row)">添加故障</el-button>
          <el-button type="success" size="mini" @click="form_edit(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="positionId">
                <el-select
                  v-model="createTemp.positionId"
                  placeholder="故障部位"
                  class="filter-item"
                  style="width:100%"
                  :disabled="dialogStatus==='addFault'"
                >
                  <el-option
                    v-for="item in listPart"
                    :key="item.id"
                    :label="item.positionName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="故障详情：" prop="appearanceName">
                <el-input ref="appearanceName" v-model="createTemp.appearanceName" type="text" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="备注：" prop="note">
                <el-input ref="note" v-model="createTemp.note" 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="dialogStatus==='create'?add_dialog_save():addFaultData()">保存并关闭</el-button>
        <el-button @click="dialogFormVisible = false;getList()">取消并关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="textMap[dialogStatusSee]"
      :visible.sync="dialogFormVisibleSee"
      :close-on-click-modal="false"
    >
      <div class="content-see">
        <el-form
          ref="seeTemp"
          :rules="rules"
          :model="seeTemp"
          label-position="right"
          label-width="120px"
          style="width: 90%;margin:0 auto;"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="部位名称：" prop="positionName">
                <el-select
                  v-model="seeTemp.positionName"
                  placeholder="部位名称"
                  class="filter-item"
                  style="width:100%"
                  disabled
                >
                  <el-option
                    v-for="item in listPart"
                    :key="item.id"
                    :label="item.positionName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table
          v-loading="listLoadingSee"
          element-loading-text="给我一点时间"
          :data="listSee"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable table-fixed"
          row-key="id"
        >
          <el-table-column label="序号" align="center" type="index" width="50px" />
          <el-table-column label="故障详情" header-align="center" min-width="100px" align="center">
            <template slot-scope="scope">
              <el-input v-if="update" ref="appearanceName" v-model="scope.row.appearanceName" />
              <span v-if="see">{{ scope.row.appearanceName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="100px" header-align="center" align="center">
            <template slot-scope="scope">
              <el-input v-if="update" ref="note" v-model="scope.row.note" />
              <span v-if="see">{{ scope.row.note }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="isDisplay" label="操作" align="center" width="100" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{row}">
              <a class="primary" @click="updateSave(row)">保存</a>
              <a class="del" @click="updateDelete(row)">删除</a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer" style="bottom:10px">
        <el-button @click="dialogFormVisibleSee = 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"
                  :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, 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: 'Guzhang',
  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: '添加故障'
      },
      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: 'getAppearancePosList',
        parammaps: {
          id: ''
        }
      },
      list: [],
      total: 0,
      listLoading: true,
      dialogStatus: '',
      dialogFormVisible: false,
      createTemp: {
        positionId: '',
        appearanceName: '',
        note: ''
      },
      listPart: [],
      getPartListParam: {
        name: 'getPartList',
        parammaps: {}
      },
      tableKey: 0,
      isokDisable: false,
      postDataPramas: {},
      seeTemp: {},
      dialogStatusSee: '',
      isDisplay: false,
      dialogFormVisibleSee: false,
      listLoadingSee: true,
      totalSee: 0,
      listSee: [],
      getdataListParmSee: {
        name: 'getAppearancebyPid',
        returntype: 'Map',
        parammaps: {}
      },
      postUpdatePramas: {},
      requestParam: {},
      update: false,
      see: false,
      rules: {
        positionId: [{ required: true, message: '必填', trigger: 'blur' }],
        appearanceName: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }]
      },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' }
    }
  },
  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.getPartListParam.parammaps.id = this.assetTypeid
        this.getList()
        this.getTypeList()
        this.getPartList()
      }
    },
    assetTypename(val) {
      console.log(val)
    },
    assetAction(val) {
      console.log(val)
      this.getList()
    }
  },
  created() {
    this.getList()
  },

  // 设置变量

  methods: {
    // ------------------------------------------------------------------
    tableSort(column) {
      sortChange(column, this.list)
    },
    getList() {
      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.appearanceName = ''
      this.createTemp.note = ''
    },
    getPartList() {
      GetDataByName(this.getPartListParam).then(response => {
        this.listPart = response.data.list
        this.$forceUpdate()
      })
    },
    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)
        this.getPartListParam.parammaps.id = this.assetTypeid
        this.getPartList()
        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
          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.getList()
              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
          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.resetCreateTemp()
              console.log(this.dialogStatus)
              if (this.dialogStatus == 'addFault') {
                this.createTemp.positionId = this.createTemp.positionId
              } else {
                this.createTemp.positionId = ''
              }
              this.$notify({
                title: '',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleCopy() {
      if (this.assetTypeid != '') {
        this.dialogFormVisibleCopy = true
        this.dialogStatusCopy = 'copy'
        this.defaultCheckedKeys = []
      }
    },
    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': 'CopyAppearance', 'type': 'e', 'parammaps': {
          newEqclassId: '@insertSpotList.newEqclassId',
          eqclassid: this.assetTypeid
        }}
        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')
        }
      })
    },
    form_see(row) {
      console.log(row)
      this.seeTemp = Object.assign({}, row)
      this.dialogStatusSee = 'see'
      this.dialogFormVisibleSee = true
      this.isDisplay = false
      this.see = true
      this.update = false
      this.getdataListParmSee.parammaps.id = row.id
      this.getListSee()
    },
    getListSee() {
      GetDataByName(this.getdataListParmSee).then(response => {
        console.log('部位table数据', response.data.list)
        this.listSee = response.data.list
        if (response.data.total) {
          this.totalSee = response.data.total
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoadingSee = false
        }, 100)
      })
    },
    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.getListSee()
    },
    updateSave(row) {
      if (row.appearanceName !== '' && row.appearanceName !== null && row.appearanceName !== 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 = 'deleteAppearance'
        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.getList()
            this.getListSee()
            this.$notify({
              title: '',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      })
    },
    handleAddFault(row) {
      this.dialogStatus = 'addFault'
      this.dialogFormVisible = true
      // this.createTemp = Object.assign({}, row)
      this.resetCreateTemp()
      this.createTemp.positionId = row.id
      this.$nextTick(() => {
        this.$refs['createTemp'].clearValidate()
      })
    },
    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.getList()
              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.getList()
      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
        })
      }
    },
    // 导出模板
    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'
            })
          })
        })
      })
    },
    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>
