<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="isStockTypeAdd" 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', hasChildren: 'hasChildren'}"
        @sort-change="tableSort"
        :max-height="myHeight"
      >
        <el-table-column label="类别编号名称" min-width="260px" header-align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.partClassCode }}({{ scope.row.partClassName }}) </span>
          </template>
        </el-table-column>
        <el-table-column sortable prop="section" label="层级" 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="品牌数" sortable prop="bps" min-width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.bps }}</span>
          </template>
        </el-table-column>

        <el-table-column label="供应商数" sortable prop="pps" min-width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.pps }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备件数" sortable prop="ps" min-width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.ps }}</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="操作" header-align="center" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button v-if="isStockTypeUpdate" type="primary" size="mini" @click="form_edit(row)"> 编辑 </el-button>
            <el-button v-if="row.childrens === 0 && row.pps === 0 && row.bps === 0 && row.ps === 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="300"
              size="small"
              clearable
              :data="parentDept"
              :default-props="defaultProps"
              :node-key="nodeKey"
              :checked-keys="defaultCheckedKeys"
              @popoverHide="popoverHide"
            />
          </el-form-item>
          <el-form-item label="类别编号" prop="tempClassCode" style="width:300px">
            <el-input ref="tempClassCode" v-model="deptform.tempClassCode" placeholder="请输入编码">
              <template slot="prepend">{{ deptform.tempPClassCode }}</template>
            </el-input>
          </el-form-item>
          <el-form-item label="类别名称" prop="partClassName" style="width:300px">
            <el-input
              ref="partClassName"
              v-model="deptform.partClassName"
            />
          </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>
        <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;get_table_data();"> 取消并关闭 </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: 'StockType',
  components: { TreeSelect },
  directives: { waves },
  data() {
    return {
      myHeight:document.documentElement.clientHeight - 85- 150,
      isokDisable: false,
      disabled: false,
      tableKey: 0,
      list: [{ 'deptname': '公司', 'id': 1, 'parentid': -1 }],
      parentDept: [],
      listLoading: true,
      requestParam: {
        name: 'createCategoryType',
        parammaps: {}
      },
      deptform: {
        id: '',
        tempClassCode: '',
        tempPClassCode: '',
        partClassName: '',
        partClassCode: '',
        pid: '',
        sort: '',
        enable: ''
      },
      getDeptListParm: { name: 'getpart_classList' },
      getDeptParm: { name: 'getCategoryTyperecu',
        idname: 'value',
        params: [-1] },
      rules: {
        tempClassCode: [{ type: 'string', required: true, message: '类别编码必填', trigger: 'blur' },
          { validator: isIntegerZero, trigger: 'blur' }],
        partClassName: [{ 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: 'partClassNameCode'
      },
      nodeKey: 'id',
      defaultCheckedKeys: [],
      buttons: [],
      isStockTypeAdd: [],
      isStockTypeUpdate: [],
      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.get_table_data()
  },
  methods: {
    tableSort(column) {
      sortChange(column, this.list)
    },
    get_auto_buttons() {
      // 新增
      const StockTypeAdd = 'console:stockType:insert'
      const isStockTypeAdd = checkButtons(this.$store.state.user.buttons, StockTypeAdd)
      this.isStockTypeAdd = isStockTypeAdd
      // 编辑
      const StockTypeUpdate = 'console:stockType:update'
      const isStockTypeUpdate = checkButtons(this.$store.state.user.buttons, StockTypeUpdate)
      this.isStockTypeUpdate = isStockTypeUpdate
    },
    popoverHide(checkedIds, checkedData) {
      this.deptform.pid = checkedIds
      if (checkedIds !== null) {
        this.deptform.partClassCode = checkedData.partClassCode
      } else {
        this.deptform.pid = -1
      }
      this.getMaxCode()
    },
    get_table_data() {
      this.listLoading = true
      GetDataByName(this.getDeptListParm).then(response => {
        this.list = response.data
        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)
          }
          this.list = transData(response.data.list, 'id', 'pid', 'children')
        }
        this.parentDept = this.list
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    resetRequestParam() {
      this.requestParam = {
        name: 'createCategoryType',
        parammaps: {}
      }
      this.deptform.id = ''
      this.deptform.pid = -1
      this.deptform.tempClassCode = ''
      this.deptform.tempPClassCode = ''
      this.deptform.partClassName = ''
      this.deptform.partClassCode = ''
      this.deptform.sort = '0'
      this.deptform.enable = 1
    },
    form_add() {
      this.resetRequestParam()
      this.dialogStatus = 'create'
      this.defaultCheckedKeys = []
      this.parentDeptVisible = true
      this.dialogFormVisible = true
      this.deptform.pid = -1
      this.deptform.enable = 1
      this.getMaxCode()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    getMaxCode() {
      this.requestParam.name = 'getPCMaxcodeByPid'
      this.requestParam.parammaps = {}
      this.requestParam.parammaps.pid = this.deptform.pid
      GetDataByName(this.requestParam).then(response => {
        if (response.data.list.length > 0) {
          if (response.data.list[0].parentcode === '') {
            this.deptform.tempPClassCode = this.deptform.partClassCode + '.'
          } else {
            this.deptform.tempPClassCode = response.data.list[0].parentcode
          }
          this.deptform.tempClassCode = response.data.list[0].newcode
          if (this.requestParam.parammaps.pid === -1) {
            this.deptform.tempClassCode = this.deptform.tempPClassCode + this.deptform.tempClassCode
            this.deptform.tempPClassCode = ''
          }
        }
      })
    },
    add_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.deptform)
          this.requestParam.name = 'createCategoryType'
          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['partName'] = this.deptform.partClassName
          this.deptform.partClassCode = this.deptform.tempPClassCode + this.deptform.tempClassCode
          this.requestParam.parammaps['partCode'] = this.deptform.partClassCode
          this.requestParam.parammaps['sort'] = this.deptform.sort
          this.requestParam.parammaps['enable'] = this.deptform.enable
          PostDataByName(this.requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.get_table_data()
              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 = 'createCategoryType'
          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['partName'] = this.deptform.partClassName
          this.deptform.partClassCode = this.deptform.tempPClassCode + this.deptform.tempClassCode
          this.requestParam.parammaps['partCode'] = this.deptform.partClassCode
          this.requestParam.parammaps['sort'] = this.deptform.sort
          this.requestParam.parammaps['enable'] = this.deptform.enable

          PostDataByName(this.requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.deptform.id = ''
              this.deptform.partClassName = ''
              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
      this.deptform.id = row.id
      this.deptform.pid = row.pid
      this.deptform.partClassName = row.partClassName
      this.deptform.partClassCode = row.partClassCode

      this.deptform.tempPClassCode = this.deptform.partClassCode.substr(0, this.deptform.partClassCode.lastIndexOf('.') + 1)
      this.deptform.tempClassCode = this.deptform.partClassCode.substr(this.deptform.partClassCode.lastIndexOf('.') + 1)
      this.deptform.sort = row.sort
      this.deptform.enable = row.enable

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    edit_dialog_save() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'updateCategoryType'
          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['partName'] = this.deptform.partClassName
          this.deptform.partClassCode = this.deptform.tempPClassCode + this.deptform.tempClassCode
          this.requestParam.parammaps['partCode'] = this.deptform.partClassCode
          this.requestParam.parammaps['sort'] = this.deptform.sort
          this.requestParam.parammaps['enable'] = this.deptform.enable
          this.requestParam.parammaps['id'] = this.deptform.id

          PostDataByName(this.requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.get_table_data()
              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 = 'getpart_classList'
      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 = [
              'partClassName', 'partClassCode', 'section', 'childrens', 'pps', 'bps', 'ps', '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 = 'updateCategoryType'
      this.requestParam.parammaps = {}
      if (row.pid === null || row.pid === '') { this.requestParam.parammaps['pid'] = -1 } else { this.requestParam.parammaps['pid'] = row.pid }
      this.requestParam.parammaps['partName'] = row.partClassName
      this.requestParam.parammaps['partCode'] = row.partClassCode
      this.requestParam.parammaps['sort'] = row.sort
      this.requestParam.parammaps['enable'] = row.enable
      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.partClassName + '(' + row.partClassCode + ')', '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'deleteCategoryType'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps['id'] = row.id
        PostDataByName(this.requestParam).then(response => {
          if (response.msg !== 'fail') {
            this.get_table_data()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
 .el-table th.gutter {
  display: table-cell!important;
  }
</style>
