<template>
  <div class="app-container">
    <div v-if="isPercentage" class="percentage" style="width: 210px;height: 90px;background: #fff;position: fixed;bottom: 0;left: 0;z-index: 9999999999999;">
      <h4 style="padding-left: 10px;line-height: 0;">导出进度：</h4>
      <el-progress style="padding-left: 10px;" :text-inside="true" :stroke-width="26" :percentage="percentage" />
    </div>
    <div class="filter-container">
      <tree-select
        v-model="table.getdataListParm.partClassId"
        :height="200"
        :width="300"
        size="small"
        class="typeSelect"
        :data="equipmentCategory.list"
        :disabled="equipmentCategory.disabled"
        :default-props="equipmentCategory.defaultProps"
        :node-key="equipmentCategory.nodeKey"
        :placeholder="equipmentCategory.placeholder"
        :checked-keys="equipmentCategory.defaultCheckedKeys"
        style="display: inline-block;top: -3px;"
        @popoverHide="popoverHide"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
      <el-button class="filter-item" type="info" icon="el-icon-tickets" @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 class="filter-item" type="warning" icon="el-icon-download" @click="form_search">导入</el-button>
      </el-upload>
      <el-button class="filter-item" type="success" icon="el-icon-upload2" @click="handleDownload">导出</el-button>
    </div>
    <div class="operation">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
    </div>
    <el-table
      slot="reference"
      border
      :data="table.list"
      header-align="center"
      :row-style="rowStyle"
      :cell-style="cellStyle"
      class="elTable"
      :max-height="myHeight"
    >
      <el-table-column label="备件类别" min-width="240px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.NoEdit || scope.row.isDispaly== false">{{ scope.row.partName }}</span>
          <tree-select
            v-else
            v-model="scope.row.partClassId"
            size="small"
            :width="200"
            :display="scope.row.dispaly"
            :data="equipmentCategory.list"
            :disabled="equipmentCategory.disabled"
            :default-props="equipmentCategory.defaultProps"
            :node-key="equipmentCategory.nodeKey"
            :placeholder="equipmentCategory.placeholder"
            :checked-keys="equipmentCategory.defaultCheckedKeys"
            style="display: inline-block;"
            @popoverHide="popoverHide2"
          />
          </tree-select>
        </template>
      </el-table-column>
      <el-table-column v-for="(item,index) in table.tablelist" :key="index" align="center" :property="item.property" :label="item.label" min-width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.NoEdit">{{ scope.row[scope.column.property] }}</span>
          <el-input v-if="scope.row.Edit" v-model="scope.row[scope.column.property]" type="number" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button v-if="row.isCreate" :disabled="isokDisable" type="success" size="mini" @click="add_dialog_save(row)">保存</el-button>
          <el-button v-if="row.isCreate" type="danger" size="mini" @click="createCancel(row)">取消</el-button>
          <el-button v-if="row.isUpdate" type="success" size="mini" @click="form_edit(row)">编辑</el-button>
          <el-button v-if="row.isUpdateSave" :disabled="isokDisable" type="success" size="mini" @click="edit_dialog_save(row)">保存</el-button>
          <el-button v-if="row.isUpdateSave" type="danger" size="mini" @click="updateCancel(row)">取消</el-button>
          <el-button v-if="row.isUpdate" type="danger" size="mini" @click="handleRowDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="table.total>0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="get_table_data" />

  </div>
</template>

<script>

import { GetDataByName, StandardPart, updateAndInster, transData } from '@/api/common'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
import TreeSelect from '@/components/TreeSelect'
import { getToken } from '@/utils/auth'
import { json2excel } from '@/utils/index.js'

export default {
  name: 'StandardStock',
  components: { Pagination, TreeSelect },
  data() {
    return {
      myHeight:document.documentElement.clientHeight - 85- 200,
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      equipmentCategory: {
        getdataListParm: { name: 'getStandardPartClass' },
        list: [], placeholder: '备件类别', nodeKey: 'id', defaultCheckedKeys: [], disabled: false,
        defaultProps: { children: 'children', label: 'partClassNameCode' }, display: 'none'
      },
      table: {
        tableKey: 0, list: [], tablelist: [], total: 0, listLoading: true, idsArray: [],
        getdataListParm: {
          partClassId: '', page: 1, offset: 1, pagecount: 10, returntype: 'Map', parammaps: {}
        }
      },
      createTemp: {},
      postDataParm: {},
      isokDisable: false,
      headers: {
        optname: 'insertcustompic', id: 1, token: getToken()
      },
      uploadImageUrl: process.env.VUE_APP_BASE_API + 'authdata/uploaderimage',
      isPercentage: false,
      percentage: 1,
      downloadParam: {}
    }
  },
  computed: {
    uploadData() {
      return {
        name: 'importPartsStandard',
        importParams: '牧场,一级备件类别,二级备件类别,标准库存（元）',
        sheetname: 'SheetJS'
      }
    },
    // 设置上传地址
    uploadExcelUrl() {
      return process.env.VUE_APP_BASE_API + 'authdata/ImportExcel'
    }
  },
  created() {
    this.getEquipmentCategoryList()
    this.get_table_data()
  },
  methods: {
    getEquipmentCategoryList() {
      GetDataByName(this.equipmentCategory.getdataListParm).then(response => {
        if (response.data.list !== null) {
          this.equipmentCategory.list = transData(response.data.list, 'id', 'pid', 'children')
        } else {
          this.equipmentCategory.list = []
        }
      })
    },
    popoverHide(checkedIds, checkedData) {
      if (checkedIds !== null) {
        if (checkedData.children === undefined) {
          this.table.getdataListParm.partClassId = checkedData.partClassId
        } else {
          this.equipmentCategory.defaultCheckedKeys = []
          this.table.getdataListParm.partClassId = ''
          this.$message({ type: 'warning', message: '请选择具体设备类型' })
        }
      } else {
        this.equipmentCategory.defaultCheckedKeys = []
        this.table.getdataListParm.partClassId = ''
      }
    },
    get_table_data() {
      this.table.listLoading = true
      StandardPart(this.table.getdataListParm).then(response => {
        if (response.data.list !== null) {
          console.log('table数据', response.data.list)
          this.table.tablelist = response.data.list[0]
          this.table.idsArray = []
          for (let i = 0; i < this.table.tablelist.length; i++) {
            this.table.idsArray.push(this.table.tablelist[i].id)
          }
          this.table.list = response.data.list[1]
          for (let i = 0; i < this.table.list.length; i++) {
            this.$set(this.table.list[i], 'Edit', false) // 编辑
            this.$set(this.table.list[i], 'NoEdit', true) // 不可编辑/输入
            this.$set(this.table.list[i], 'isCreate', false) // 新增操作
            this.$set(this.table.list[i], 'isUpdate', true) // 编辑操作
            this.$set(this.table.list[i], 'isUpdateSave', false) // 编辑保存
            this.$set(this.table.list[i], 'isDispaly', false)
            this.$set(this.table.list[i], 'dispaly', 'none')
          }
          this.table.pageNum = response.data.pageNum
          this.table.pageSize = response.data.pageSize
          this.table.total = response.data.total
        } else {
          this.table.tablelist = []
          this.table.list = []
        }
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    form_search() {
      this.table.listLoading = true
      this.table.getdataListParm.offset = 1
      this.get_table_data()
    },
    form_add() {
      console.log('新增')
      for (let i = 0; i < this.table.list.length; i++) {
        if (this.table.list[i].Edit === true) {
          this.$message({ type: 'error', message: '当前内容未保存，请点击取消或保存继续进行操作', duration: 2000 })
          return false
        }
      }

      var obj = {}
      for (let i = 0; i < this.table.tablelist.length; i++) {
        obj.myId = (new Date()).valueOf()
        obj.Edit = true
        obj.NoEdit = false
        obj.isCreate = true
        obj.isUpdate = false
        obj.isUpdateSave = false
        obj.display = 'block'
        obj.typeName = ''
        obj.partClassId = ''
        obj.eqCode = ''
        obj.typeName = ''
        obj.isDispaly = true
        obj.display = 'block'
        obj[this.table.tablelist[i].property] = ''
        var a = i + 1
        obj['pastureId' + a] = this.table.tablelist[i].id
      }
      this.equipmentCategory.defaultCheckedKeys = []
      this.createTemp = obj
      this.table.list.unshift(obj)
    },

    popoverHide2(checkedIds, checkedData) {
      console.log(checkedIds, checkedData)
      if (this.createTemp.isCreate == true) {
        if (checkedIds !== null) {
          if (checkedData.children == undefined) {
            this.createTemp.partClassId = checkedData.id
            this.createTemp.eqCode = checkedData.partClassCode
            this.createTemp.typeName = checkedData.partClassName
          } else {
            this.createTemp.partClassId = ''
            this.createTemp.eqCode = ''
            this.createTemp.typeName = ''
            this.$message({ type: 'warning', message: '请选择具体设备类型' })
          }
        } else {
          this.createTemp.partClassId = ''
          this.createTemp.eqCode = ''
          this.createTemp.typeName = ''
        }
      }
    },
    add_dialog_save(row) {
      console.log('新增保存', row)
      console.log(this.table.tablelist, 'this.table.tablelist')
      if (this.createTemp.partClassId == '') {
        this.$message({ type: 'error', message: '设备类别必填', duration: 2000 })
        return false
      }
      var arr = []
      for (let i = 0; i < this.table.tablelist.length; i++) {
        if (row[this.table.tablelist[i].property] !== '' && row[this.table.tablelist[i].property] !== 0 && row[this.table.tablelist[i].property] !== '0') {
          arr.push(row[this.table.tablelist[i].property])
        }
      }
      if (arr.length == 0) {
        this.$message({ type: 'error', message: '请检查录入数据，至少有一条不为0！', duration: 2000 })
        return false
      }
      MessageBox.confirm('是否保存？', '提示', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        for (let i = 0; i < this.table.tablelist.length; i++) {
          if (row[this.table.tablelist[i].property] == '') {
            row[this.table.tablelist[i].property] = 0
          }
        }
        this.postDataParm = {}
        this.postDataParm.check = 'insert'
        this.postDataParm.name = 'partStandard'
        this.postDataParm.param = {}
        this.postDataParm.param = this.createTemp
        updateAndInster(this.postDataParm).then(response => {
          if (response.msg !== 'fail') {
            this.$notify({ title: '成功', message: '新增成功', type: 'success', duration: 2000 })
            this.get_table_data()
          } else {
            this.$notify({ title: '失败', message: '新增失败-' + response.data, type: 'danger', duration: 2000 })
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消' })
      })
    },
    createCancel(row) {
      for (let i = 0; i < this.table.list.length; i++) {
        if (row.myId === this.table.list[i].myId) {
          var listIndex = this.table.list.indexOf(this.table.list[i])
        }
        if (listIndex > -1) {
          this.table.list.splice(listIndex, 1)
          return
        }
      }
    },
    form_edit(row) {
      for (let i = 0; i < this.table.list.length; i++) {
        if (this.table.list[i].Edit == true) {
          this.$message({ type: 'error', message: '当前内容未保存，请点击取消或保存继续进行操作', duration: 2000 })
          return false
        }
      }
      row.Edit = true
      row.NoEdit = false
      row.isCreate = false
      row.isUpdate = false
      row.isUpdateSave = true
      this.equipmentCategory.defaultCheckedKeys = [row.partClassId]
      this.createTemp = row
    },
    edit_dialog_save(row) {
      var arr = []
      for (let i = 0; i < this.table.tablelist.length; i++) {
        if (row[this.table.tablelist[i].property] !== '' && row[this.table.tablelist[i].property] !== 0 && row[this.table.tablelist[i].property] !== '0') {
          arr.push(row[this.table.tablelist[i].property])
        }
      }
      if (arr.length == 0) {
        this.$message({ type: 'error', message: '请检查录入数据，至少有一条不为0！', duration: 2000 })
        return false
      }
      console.log(arr.length)
      for (let i = 0; i < this.table.tablelist.length; i++) {
        if (row[this.table.tablelist[i].property] == '') {
          row[this.table.tablelist[i].property] = 0
        }
      }
      this.postDataParm = {}
      this.postDataParm.check = 'update'
      this.postDataParm.name = 'partStandard'
      this.postDataParm.param = {}
      this.postDataParm.param = this.createTemp
      console.log('编辑保存', this.postDataParm)
      updateAndInster(this.postDataParm).then(response => {
        if (response.msg !== 'fail') {
          this.get_table_data()
          this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
        } else {
          this.$notify({ title: '失败', message: '失败-' + response.data, type: 'danger', duration: 2000 })
        }
      })
    },
    updateCancel(row) {
      row.Edit = false
      row.NoEdit = true
      row.isCreate = false
      row.isUpdate = true
      row.isUpdateSave = false
      this.get_table_data()
    },
    handleRowDelete(row) {
      MessageBox.confirm('是否确认删除此信息?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.postDataParm = {}
        this.postDataParm.check = 'delete'
        this.postDataParm.name = 'partStandard'
        this.postDataParm.param = {}
        this.postDataParm.param = row
        updateAndInster(this.postDataParm).then(response => {
          if (response.msg !== 'fail') {
            this.get_table_data()
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
          } else {
            this.$notify({ title: '失败', message: '删除失败-' + response.data, type: 'danger', duration: 2000 })
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    handleDownloadTemp() {
      const ExcelDatas = [
        {
          tHeader: ['牧场', '一级备件类别', '二级备件类别', '标准库存（元）'],
          filterVal: ['牧场', '一级备件类别', '二级备件类别', '标准库存（元）'],
          tableDatas: [],
          sheetName: 'SheetJS'
        }
      ]
      json2excel(ExcelDatas, '标准库存模板', true, 'xlsx')
    },
    handleDownload() {
      this.$alert('备件基础信息正在导出中，请勿刷新或离开本页面，若导出时间过长，建议缩小导出数据范围重新导出', {})
      this.isPercentage = true
      this.percentage = 1
      var timer = setInterval(() => {
        this.percentage += 5
        if (this.percentage > 95) {
          this.percentage = 99
          clearInterval(timer)
        }
        this.percentage = this.percentage
      }, 1000)
      this.downloadParam = {}
      this.downloadParam = this.table.getdataListParm
      StandardPart(this.downloadParam).then(response => {
        if (response.data.list !== '') {
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
        }
        var headerList = []
        var filterList = []
        for (let i = 0; i < response.data.list[0].length; i++) {
          headerList.push(response.data.list[0][i].label)
          filterList.push(response.data.list[0][i].property)
        }
        headerList.unshift('设备类别')
        filterList.unshift('partName')
        console.log(headerList, filterList)
        this.$nextTick(() => {
          const ExcelDatas = [
            { tHeader: headerList, filterVal: filterList, tableDatas: response.data.list[1], sheetName: '标准库存' }
          ]
          json2excel(ExcelDatas, '标准库存', true, 'xlsx')
        })
      })
    },
    beforeImportExcel(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt2M
    },
    handleImportExcelSuccess(res, file) {
      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 = ['牧场', '一级备件类别', '二级备件类别', '标准库存']
            const data1 = this.formatJson(filterVal, list1)
            excel.export_json_to_excel({ header: tHeader, data: data1, filename: this.requestParam.parammaps.formType, autoWidth: true, bookType: 'xlsx' })
          })
        }
      } else {
        this.$notify({ title: '失败', message: '上传失败', type: 'danger', duration: 2000 })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .operation{margin-bottom: 10px;}
</style>
