<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="app-container">
      <div class="filter-container">
        <el-button v-if="isAssetTypeAdd" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add">新增 </el-button>
        <el-button :disabled="isokDisable" class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleDownload">导出</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"
        row-key="id"
        :tree-props="{children: 'children'}"
        @sort-change="tableSort"
      >
        <el-table-column label="类别编号名称" min-width="400px" header-align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.typeCode }}({{ scope.row.typeName }}) </span>
          </template>
        </el-table-column>
        <el-table-column label="层级" sortable prop="section" min-width="80px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.section }}</span>
          </template>
        </el-table-column>
        <el-table-column label="子类数" sortable prop="childrens" min-width="80px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.childrens }}</span>
          </template>
        </el-table-column>
        <el-table-column label="启用" min-width="80px" header-align="center" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="handleEnableChange(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="是否保养" min-width="80px" header-align="center" align="center">
          <template slot-scope="scope">
            <el-switch v-if="parseInt(scope.row.childrens)==0" v-model="scope.row.eqplan" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="handleEqplanChange(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="是否启停" min-width="80px" header-align="center" align="center">
          <template slot-scope="scope">
            <el-switch v-if="parseInt(scope.row.childrens)==0" v-model="scope.row.eqstart" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="handleEqstartChange(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button v-if="isAssetTypeUpdate" type="primary" size="mini" @click="form_edit(row)"> 编辑 </el-button>
            <el-button v-if="row.childrens === 0 && row.bes === 0 && row.eps === 0 && row.eqts === 0 && row.es === 0" size="mini" type="danger" @click="form_delete(row)">删除 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
        <el-form ref="dataForm" :rules="rules" :model="deptform" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item v-if="parentDeptVisible" label="上级分类" prop="parentid">
            <tree-select
              :disabled="disabled"
              :height="280"
              :width="350"
              size="small"
              clearable
              :data="parentDept"
              :default-props="defaultProps"
              :node-key="nodeKey"
              :checked-keys="defaultCheckedKeys"
              @popoverHide="popoverHide"
            />
          </el-form-item>
          <el-form-item label="类别编号" prop="temptypeCode" style="width:300px">
            <el-input ref="temptypeCode" v-model="deptform.temptypeCode" placeholder="请输入编码">
              <template slot="prepend">{{ deptform.tempPtypeCode }}</template>
            </el-input>
          </el-form-item>
          <el-form-item label="类别名称" prop="typeName" style="width:300px">
            <el-input ref="typeName" v-model="deptform.typeName" />
          </el-form-item>
          <el-form-item label="启用" prop="enable">
            <el-switch ref="enable" v-model="deptform.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item v-if="dialogStatus=='update' && parseInt(deptform.childrens)==0" label="是否保养" prop="eqplan">
            <el-switch ref="eqplan" v-model="deptform.eqplan" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item v-if="dialogStatus=='update' && parseInt(deptform.childrens)==0" label="是否启停" prop="eqstart ">
            <el-switch ref="eqstart " v-model="deptform.eqstart " active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="textMap[dialogStatus]==='新增'" ref="createb" :disabled="isokDisable" type="success" @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;getList();"> 取消并关闭 </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import TreeSelect from '@/components/TreeSelect'
import waves from '@/directive/waves' // waves directive
import { isIntegerZero } from '@/utils/validate'
import { PostDataByName, GetDataByName, transData, failproccess, formatJson, checkButtons, GetAccount } from '@/api/common'
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
import { sortChange } from '@/utils/index.js'
export default {
  name: 'AssetType',
  components: { TreeSelect },
  directives: { waves },
  data() {
    return {
      isokDisable: false,
      disabled: false,
      tableKey: 0,
      list: [{ 'deptname': '公司', 'id': 1, 'parentid': -1 }],
      parentDept: [],
      listLoading: true,
      requestParam: {
        name: 'createAssetType',
        parammaps: {}
      },
      deptform: {
        id: '',
        tempPtypeCode: '',
        temptypeCode: '',
        typeName: '',
        typeCode: '',
        pid: '',
        sort: '',
        enable: '',
        eqplan: '',
        eqstart: ''
      },
      getDeptListParm: { name: 'geteqclasslist' },
      rules: {
        temptypeCode: [{ type: 'string', required: true, message: '类别编码必填', trigger: 'blur' },
          { validator: isIntegerZero, trigger: 'blur' }],
        typeName: [{ type: 'string', required: true, message: '类别名称必填', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      parentDeptVisible: true,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      defaultProps: {
        children: 'children',
        label: 'typeNameCode'
      },
      nodeKey: 'id',
      defaultCheckedKeys: [],
      buttons: [],
      isAssetTypeAdd: [],
      isAssetTypeUpdate: [],
      isPercentage: false,
      percentage: 1
    }
  },
  created() {
    const that = this
    GetDataByName({ 'name': 'getUserPCButtons', 'parammaps': { 'jwt_username': Cookies.get('name') }}).then(response => {
      that.buttons = response.data.list
      that.get_auto_buttons()
    })
    this.getList()
  },
  methods: {
    tableSort(column) {
      sortChange(column, this.list)
    },
    get_auto_buttons() {
      // 新增
      const AssetTypeAdd = 'console:assetType:insert'
      const isAssetTypeAdd = checkButtons(this.$store.state.user.buttons, AssetTypeAdd)
      this.isAssetTypeAdd = isAssetTypeAdd
      // 编辑
      const AssetTypeUpdate = 'console:assetType:update'
      const isAssetTypeUpdate = checkButtons(this.$store.state.user.buttons, AssetTypeUpdate)
      this.isAssetTypeUpdate = isAssetTypeUpdate
    },
    popoverHide(checkedIds, checkedData) {
      this.deptform.pid = checkedIds
      if (checkedIds !== null) {
        this.deptform.typeCode = checkedData.typeCode
      } else {
        this.deptform.pid = -1
      }
      this.getMaxCode()
    },
    getList() {
      this.listLoading = true
      GetDataByName(this.getDeptListParm).then(response => {
        this.list = response.data
        console.log(this.list)

        if (response.data.list !== null) {
          for (var i = 0; i < response.data.list.length; i++) {
            response.data.list[i].enable = parseInt(response.data.list[i].enable)
            response.data.list[i].eqplan = parseInt(response.data.list[i].eqplan)
            response.data.list[i].eqstart = parseInt(response.data.list[i].eqstart)
          }
          this.list = transData(response.data.list, 'id', 'pid', 'children')
          console.log(this.list)
        }
        this.parentDept = this.list
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    resetRequestParam() {
      this.requestParam = {
        name: 'createAssetType',
        parammaps: {}
      }
      this.deptform.id = ''
      this.deptform.pid = -1
      this.deptform.typeName = ''
      this.deptform.typeCode = ''
      this.deptform.sort = '0'
      this.deptform.enable = 1
      this.deptform.eqplan = 1
      this.deptform.eqstart = 1
      this.deptform.temptypeCode = ''
      this.deptform.tempPtypeCode = ''
    },
    form_add() {
      this.resetRequestParam()
      this.dialogStatus = 'create'
      this.defaultCheckedKeys = []
      this.parentDeptVisible = true
      this.dialogFormVisible = true
      this.deptform.pid = -1
      this.deptform.enable = 1
      this.deptform.eqstart = 1
      this.deptform.eqplan = 1

      this.getMaxCode()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    getMaxCode() {
      this.requestParam.name = 'getEQMaxcodeByPid'
      this.requestParam.parammaps = {}
      this.requestParam.parammaps.pid = this.deptform.pid
      GetDataByName(this.requestParam).then(response => {
        console.log(response, '----------------')
        if (response.data.list.length > 0) {
          if (response.data.list[0].parentcode === '') {
            this.deptform.tempPtypeCode = this.deptform.typeCode + '.'
          } else {
            this.deptform.tempPtypeCode = response.data.list[0].parentcode
          }
          this.deptform.temptypeCode = response.data.list[0].newcode
          if (this.requestParam.parammaps.pid === -1) {
            this.deptform.typeCode = this.deptform.tempPtypeCode + this.deptform.temptypeCode
            this.deptform.tempPtypeCode = ''
          }
        }
      })
    },
    add_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'createAssetType'
          this.requestParam.parammaps = {}
          if (this.deptform.pid === null || this.deptform.pid === '') { this.requestParam.parammaps.pid = -1 } else { this.requestParam.parammaps.pid = this.deptform.pid }
          this.requestParam.parammaps.typeName = this.deptform.typeName
          this.deptform.typeCode = this.deptform.tempPtypeCode + this.deptform.temptypeCode
          this.requestParam.parammaps.typeCode = this.deptform.typeCode
          this.requestParam.parammaps.enable = this.deptform.enable
          this.requestParam.parammaps.eqstart = this.deptform.eqstart
          this.requestParam.parammaps.eqplan = this.deptform.eqplan

          PostDataByName(this.requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.getList()
              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['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'createAssetType'
          this.requestParam.parammaps = {}

          if (this.deptform.pid === null || this.deptform.pid === '') { this.requestParam.parammaps.pid = -1 } else { this.requestParam.parammaps.pid = this.deptform.pid }
          this.requestParam.parammaps.typeName = this.deptform.typeName
          this.deptform.typeCode = this.deptform.tempPtypeCode + this.deptform.temptypeCode
          this.requestParam.parammaps.typeCode = this.deptform.typeCode
          this.requestParam.parammaps.enable = this.deptform.enable
          this.requestParam.parammaps.eqstart = this.deptform.eqstart
          this.requestParam.parammaps.eqplan = this.deptform.eqplan
          PostDataByName(this.requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.deptform.id = ''
              this.deptform.typeName = ''
              this.getMaxCode()
              this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
              })
              this.$notify({ title: '成功', message: '新增成功', type: 'success', duration: 2000 })
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      })
    },
    form_edit(row) {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.defaultCheckedKeys = [row.pid]
      this.parentDeptVisible = row.pid > 0
      console.log(row)
      this.deptform.childrens = row.childrens
      this.deptform.id = row.id
      this.deptform.pid = row.pid
      this.deptform.typeName = row.typeName
      this.deptform.typeCode = row.typeCode
      this.deptform.tempPtypeCode = this.deptform.typeCode.substr(0, this.deptform.typeCode.lastIndexOf('.') + 1)
      this.deptform.temptypeCode = this.deptform.typeCode.substr(this.deptform.typeCode.lastIndexOf('.') + 1)

      this.deptform.sort = row.sort
      this.deptform.enable = row.enable
      this.deptform.eqstart = row.eqstart
      this.deptform.eqplan = row.eqplan

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    edit_dialog_save() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'updateAssetTypeD'
          this.requestParam.parammaps = {}
          if (this.deptform.pid === null || this.deptform.pid === '') { this.requestParam.parammaps.pid = -1 } else { this.requestParam.parammaps.pid = this.deptform.pid }
          this.requestParam.parammaps.typeName = this.deptform.typeName
          this.deptform.typeCode = this.deptform.tempPtypeCode + this.deptform.temptypeCode
          this.requestParam.parammaps.typeCode = this.deptform.typeCode
          this.requestParam.parammaps.enable = this.deptform.enable
          this.requestParam.parammaps.eqstart = this.deptform.eqstart
          this.requestParam.parammaps.eqplan = this.deptform.eqplan
          this.requestParam.parammaps.id = this.deptform.id

          PostDataByName(this.requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            } else {
              failproccess(response, this.$notify)
            }
          })
        }
      })
    },
    // 导出
    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.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.requestParam.name = 'geteqclasslist'
      GetAccount(this.requestParam).then(response => {
        this.$nextTick(() => {
          import('@/vendor/Export2Excel').then(excel => {
            const list1 = response.data.list
            if (response.data.list !== '') {
              this.percentage = 99
              setTimeout(() => {
                this.isPercentage = false
              }, 2000)
            }
            const tHeader = [
              '类别名称', '类别编号', '层级', '子类数', '供应商数', '品牌数', '设备数', '模板数', '是否启用'
            ]
            const filterVal = [
              'typeName', 'typeCode', 'section', 'childrens', 'eps', 'bes', 'es', 'eqts', 'enable'
            ]
            const data1 = formatJson(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '设备类别',
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
      })
    },
    handleEnableChange(index, row) {
      this.requestParam.name = 'updateAssetTypeD'
      this.requestParam.parammaps = {}
      if (row.pid === null || row.pid === '') { this.requestParam.parammaps.pid = -1 } else { this.requestParam.parammaps.pid = row.pid }
      this.requestParam.parammaps.typeName = row.typeName
      this.deptform.typeCode = row.tempPtypeCode + row.temptypeCode
      this.requestParam.parammaps.typeCode = row.typeCode
      this.requestParam.parammaps.enable = row.enable
      this.requestParam.parammaps.eqstart = row.eqstart
      this.requestParam.parammaps.eqplan = row.eqplan
      this.requestParam.parammaps.id = row.id

      PostDataByName(this.requestParam).then(response => {
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '修改成功', type: 'success', duration: 2000 })
        } else {
          failproccess(response, this.$notify)
        }
      })
    },
    handleEqplanChange(index, row) {
      this.requestParam.name = 'updateAssetTypeD'
      this.requestParam.parammaps = {}
      if (row.pid === null || row.pid === '') { this.requestParam.parammaps.pid = -1 } else { this.requestParam.parammaps.pid = row.pid }
      this.requestParam.parammaps.typeName = row.typeName
      this.deptform.typeCode = row.tempPtypeCode + row.temptypeCode
      this.requestParam.parammaps.typeCode = row.typeCode
      this.requestParam.parammaps.enable = row.enable
      this.requestParam.parammaps.eqstart = row.eqstart
      this.requestParam.parammaps.eqplan = row.eqplan
      this.requestParam.parammaps.id = row.id

      PostDataByName(this.requestParam).then(response => {
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '修改成功', type: 'success', duration: 2000 })
        } else {
          failproccess(response, this.$notify)
        }
      })
    },
    handleEqstartChange(index, row) {
      this.requestParam.name = 'updateAssetTypeD'
      this.requestParam.parammaps = {}
      if (row.pid === null || row.pid === '') { this.requestParam.parammaps.pid = -1 } else { this.requestParam.parammaps.pid = row.pid }
      this.requestParam.parammaps.typeName = row.typeName
      this.deptform.typeCode = row.tempPtypeCode + row.temptypeCode
      this.requestParam.parammaps.typeCode = row.typeCode
      this.requestParam.parammaps.enable = row.enable
      this.requestParam.parammaps.eqstart = row.eqstart
      this.requestParam.parammaps.eqplan = row.eqplan
      this.requestParam.parammaps.id = row.id

      PostDataByName(this.requestParam).then(response => {
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '修改成功', type: 'success', duration: 2000 })
        } else {
          failproccess(response, this.$notify)
        }
      })
    },
    form_delete(row) {
      MessageBox.confirm('设备类别名称：' + row.typeName + '(' + row.typeCode + ')', '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'deleteAssetType'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.id = row.id
        PostDataByName(this.requestParam).then(response => {
          if (response.msg !== 'fail') {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      })
    }
  }
}
</script>
