<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
    >
      <el-table-column label="序号" align="center" type="index" width="50px" />
      <el-table-column label="部位" header-align="center" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.positionName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检查内容" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.examine }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标准" min-width="100px" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.standard }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" header-align="center" 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="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="positionId">
                <el-select
                  v-model="createTemp.positionId"
                  placeholder="部位"
                  class="filter-item"
                  style="width:100%"
                  :disabled="dialogStatus==='update'"
                  @change="changePart"
                >
                  <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="examine">
                <el-input ref="examine" v-model="createTemp.examine" type="textarea" autosize />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="检查标准：" prop="standard">
                <el-input ref="standard" v-model="createTemp.standard" type="textarea" autosize />
              </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;getdataListParm.parammaps.id = assetTypeid;getList()">取消并关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="textMap[dialogStatusSee]"
      :visible.sync="dialogFormVisibleSee"
      :close-on-click-modal="false"
      width="50%"
    >
      <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="20">
              <el-form-item label="部位：" prop="positionName">
                <el-input ref="positionName" v-model="seeTemp.positionName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="检查内容：" prop="examine">
                <el-input ref="examine" v-model="seeTemp.examine" type="textarea" autosize disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="检查标准：" prop="standard">
                <el-input ref="standard" v-model="seeTemp.standard" type="textarea" autosize disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </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, GetDataByNames, GetDataByName, transData, ExecDataByConfig } from '@/api/common'
import { MessageBox } from 'element-ui'
import TreeSelect from '@/components/TreeSelect'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/index.js'
// import Cookies from 'js-cookie'
export default {
  name: 'Dianjian',
  components: { TreeSelect },
  directives: { waves, enterToNext },
  props: {
    assetTypeid: {
      type: Number,
      default: 0
    },
    assetTypename: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      textMap: {
        create: '新增',
        update: '编辑',
        copy: '复制',
        see: '查看详情'
      },
      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: 'getSpotCheckTemplateList',
        parammaps: {
          id: ''
        }
      },
      list: [],
      total: 0,
      listLoading: true,
      dialogStatus: '',
      dialogFormVisible: false,
      createTemp: {
        part: '',
        note: ''
      },
      listAdd: [],
      listPart: [],
      getPartListParam: {
        name: 'getPartList',
        parammaps: {
          id: ''
        }
      },
      tableKey: 0,
      isokDisable: false,
      postDataPramas: {},
      seeTemp: {},
      dialogStatusSee: '',
      dialogFormVisibleSee: false,
      requestParam: {},
      rules: {
        positionId: [{ required: true, message: '必填', trigger: 'blur' }],
        examine: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
        standard: [{ 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: 'updateUpKeepSpot',
        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.getPartList()
        this.getTypeList()
      }
    },
    assetTypename(val) {
      console.log(val)
    }
  },
  created() {
    // this.getList()

  },

  // 设置变量

  methods: {
    // ------------------------------------------------------------------
    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 = {}
    },
    form_add() {
      this.getPartList()
      if (this.assetTypeid != '') {
        this.resetCreateTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.getPartListParam.parammaps.id = this.assetTypeid
        this.getPartList()
        console.log(this.listPart)
      }
    },
    getPartList() {
      GetDataByName(this.getPartListParam).then(response => {
        this.listPart = response.data.list
      })
    },
    changePart(item) {
      console.log(this.listPart.find(obj => obj.id == item))
      if (this.listPart.find(obj => obj.id == item)) {
        console.log(this.listPart.find(obj => obj.id == item).positionName)
        this.createTemp.positionName = this.listPart.find(obj => obj.id == item).positionName
        this.createTemp.eqClassId = this.listPart.find(obj => obj.id == item).eqClassId
        this.createTemp.note = this.listPart.find(obj => obj.id == item).note
      }
    },
    add_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['createTemp'].validate(valid => {
        if (valid) {
          this.postDataPramas.name = 'insertSpotCheckTemplate'
          this.postDataPramas.parammaps = this.createTemp
          this.postDataPramas.eqClassId = this.assetTypeid
          this.postDataPramas.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 = 'insertSpotCheckTemplate'
          this.postDataPramas.parammaps = this.createTemp
          this.postDataPramas.eqClassId = this.assetTypeid
          this.postDataPramas.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()
              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 = 'updateSpotCheckTemplate'
          this.postDataPramas.parammaps = this.createTemp
          this.postDataPramas.eqClassId = this.assetTypeid
          this.postDataPramas.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
              })
            }
          })
        }
      })
    },
    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': 'CopySpotCheck', 'type': 'e', 'parammaps': {
          newEqclassId: '@insertSpotList.newEqclassId',
          eqclassid: this.assetTypeid
        }}
        ExecDataByConfig(this.postDataPramas).then(response => {
          console.log('复制保存发送参数', this.postDataPramas)
          if (response.msg === 'fail') {
            this.$notify({
              title: '复制失败',
              message: response.data,
              type: 'warning',
              duration: 2000
            })
          } else {
            this.dialogFormVisibleCopy = false
            this.$notify({
              title: '',
              message: '复制成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      }
    },
    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
    },

    form_delete(row) {
      MessageBox.confirm('名称：' + row.positionName, '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.requestParam.name = 'deleteSpotCheckTemplate'
          this.requestParam.parammaps = {}
          this.requestParam.parammaps.id = row.id
          PostDataByName(this.requestParam).then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
        .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.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
        })
      }
    },
    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>
