<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-input
          v-model="getDeptListParm.parammaps.warehoseCode"
          placeholder="库位编号"
          clearable
          style="width: 200px;"
          class="filter-item"
        />
        <el-button
          v-waves
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="form_search"
        >搜索</el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add">
          新增
        </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-if="isWarehouseImport"
            v-waves
            class="filter-item"
            type="warning"
            icon="el-icon-upload2"
            @click="form_search"
          >导入</el-button>
        </el-upload>
        <el-button
          :disabled="isokDisable"
          class="filter-item"
          style="margin-left: 10px;"
          type="success"
          icon="el-icon-edit"
          @click="handleDownload"
        >导出</el-button>
      </div>
      <!-- :tree-props="{children: 'children'}" -->
      <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"
        @sort-change="tableSort"
      >
        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (pageNum-1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库位名称" header-align="left" min-width="200px">
          <template slot-scope="scope">
            <!-- <span>{{ scope.row.warehoseCode }}({{ scope.row.warehosetName }}) </span> -->
            <span>{{ scope.row.warehoseCode }} </span>
          </template>
        </el-table-column>

        <!-- <el-table-column 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="子类数" 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="pls" min-width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.pls }}</span>
          </template>
        </el-table-column>

        <el-table-column label="出库数" sortable prop="pts" min-width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.pts }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备件数" sortable prop="prs" min-width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.prs }}</span>
          </template>
        </el-table-column>
        <el-table-column label="盘点" header-align="center" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.row.cps }}</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="260" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="form_edit(row)"> 编辑 </el-button>
            <el-button v-if="row.childrens === 0 && row.cps === 0 && row.prs === 0 && row.pts === 0 && row.pls === 0" size="mini" type="danger" @click="form_delete(row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="getDeptListParm.offset"
        :limit.sync="getDeptListParm.pagecount"
        @pagination="getList"
      />
      <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: 90%; margin-left:50px;">
          <el-row>
            <el-col :span="8">
              <el-form-item label="库位编码" prop="warehoseCode">
                <el-input ref="warehoseCode" v-model="deptform.warehoseCode" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="备注" prop="remark">
                <el-input ref="remark" v-model="deptform.remark" :autosize="{ minRows: 2, maxRows: 10}" type="textarea" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="启用" prop="enable">
                <el-switch ref="enable" v-model="deptform.enable" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="dialogStatus==='create'" :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 { PostDataByName, GetDataByName, transData, failproccess, formatJson, checkButtons, GetAccount } from '@/api/common'
import { MessageBox } from 'element-ui'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'
import { parseTime, sortChange } from '@/utils/index.js'
export default {
  name: 'Dept',
  components: { TreeSelect, Pagination },
  directives: { waves },
  data() {
    return {
      isWarehouseImport: [],
      isokDisable: false,
      disabled: false,
      tableKey: 0,
      total: 0,
      list: [{ 'deptname': '公司', 'id': 1, 'parentid': -1, 'remark': '' }],
      parentDept: [],
      listLoading: true,
      requestParam: {
        name: 'createdept'
      },
      deptform: {
        id: '',
        tempPtypeCode: '',
        temptypeCode: '',
        warehosetName: '',
        warehoseCode: '',
        remark: '',
        pid: '',
        pastureId: '',
        section: '',
        isWhPostion: '',
        sort: 0,
        enable: ''
      },
      getDeptListParm: {
        name: 'getWarehouselist',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          pastureId: this.$store.state.user.pastureid,
          warehoseCode: ''
        }
      },
      pageNum: 0,
      pageSize: 0,
      getDeptParm: { name: 'getdeptrecu',
        idname: 'value',
        params: [-1] },
      rules: {
        temptypeCode: [{ type: 'string', required: true, message: '库位编码必填', trigger: 'blur' }],
        warehosetName: [{ type: 'string', required: true, message: '库位名称必填', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      parentWHVisible: 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: [],
      isPercentage: false,
      percentage: 1
    }
  },
  computed: {
    // 设置请求头
    headers() {
      return {
        // 设置token
        token: getToken()
      }
    },
    uploadData() {
      return {
        name: 'insertwarehouseprovider',
        importParams: '牧场,库位,供应商',
        sheetname: 'SheetJS'
      }
    },
    // 设置上传地址
    uploadExcelUrl() {
      // process.env.VUE_APP_BASE_API是服务器的路径，也是axios的基本路径
      return process.env.VUE_APP_BASE_API + 'authdata/ImportExcel'
    }
  },
  created() {
    this.getList()
    const that = this
    GetDataByName({ 'name': 'getUserPCButtons', 'parammaps': { 'jwt_username': Cookies.get('name') }}).then(response => {
      that.buttons = response.data.list
      that.get_auto_buttons()
    })
  },
  methods: {
    tableSort(column) {
      sortChange(column, this.list)
    },
    get_auto_buttons() {
      // 新增
      const WarehouseImport = 'basic:warehouse:upload'
      const isWarehouseImport = checkButtons(this.$store.state.user.buttons, WarehouseImport)
      this.isWarehouseImport = isWarehouseImport
    },
    popoverHide(checkedIds, checkedData) {
      this.deptform.pid = checkedIds
      if (checkedIds !== null) {
        // this.deptform.warehoseCode = checkedData.warehoseCode
      } else {
        this.deptform.pid = -1
      }
      this.getMaxCode()
    },
    deptenter() {
      /*  this.$nextTick(() => {
        this.$refs['remark'].focus()
      }) */
    },
    getList() {
      this.listLoading = true // 列表加载
      GetDataByName(this.getDeptListParm).then(response => {
        this.list = response.data
        console.log(this.list)
        if (response.data.list !== null) {
          this.list = transData(response.data.list, 'id', 'pid', 'children')
          this.pageNum = response.data.pageNum
          this.pageSize = response.data.pageSize
          console.log(this.list)
        }
        if (response.data.total) {
          this.total = response.data.total
          console.log(this.total)
        }
        this.parentDept = this.list
        // this.getDeptList()
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    form_search() {
      this.listLoading = true
      this.getDeptListParm.offset = 1
      this.getList()
    },
    querySearchWarehoseCode(queryString, cb) {
      console.log('库位编号模糊查询输入值', queryString)
      this.getDeptListParm.parammaps['warehoseCode'] = queryString
      GetDataByName(this.getDeptListParm).then(response => {
        console.log('库位模糊查询搜索data', response.data.list)
        cb(response.data.list)
      })
    },
    handleSelectWarehoseCode(item) {
      console.log('库位编号模糊查询选中值', item.id)
    },
    resetRequestParam() {
      this.requestParam = {
        name: 'createwh',
        params: []
      }

      this.deptform.id = ''
      this.deptform.temptypeCode = ''
      this.deptform.tempPtypeCode = ''

      this.deptform.warehosetName = ''
      this.deptform.warehoseCode = ''
      this.deptform.remark = ''
      this.deptform.pid = -1
      this.deptform.pastureId = this.$store.state.user.pastureid
      this.deptform.section = ''
      this.deptform.isWhPostion = '0'
      this.deptform.sort = '0'
      this.deptform.enable = '1'
    },
    form_add() {
      this.resetRequestParam()
      this.dialogStatus = 'create'
      this.defaultCheckedKeys = []
      this.dialogFormVisible = true
      this.deptform.pid = -1
      this.deptform.enable = 1
      this.getMaxCode()
      this.parentWHVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    getMaxCode() {
      this.requestParam.name = 'getWHMaxcodeByPid' // 请求接口名称
      this.requestParam.parammaps = {}
      this.requestParam.parammaps.pid = this.deptform.pid // 父级id
      this.requestParam.parammaps.pastureId = this.deptform.pastureId // 牧场id
      GetDataByName(this.requestParam).then(response => {
        if (response.data.list.length > 0) {
          if (response.data.list[0].parentcode !== '') { // 响应数据的父编码不为空
            this.deptform.tempPtypeCode = response.data.list[0].parentcode // 赋值给前输入框
          }
          if (this.requestParam.parammaps.pid === -1) { // 如果没有父级
            this.deptform.tempPtypeCode = ''
          }
          console.log(this.deptform)
        }
      })
    },

    add_dialog_save() { // 新建数据
      this.isokDisable = true // 禁用按钮
      setTimeout(() => {
        this.isokDisable = false // 延时1秒后启用按钮
      }, 1000)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'createwh'
          this.deptform.isWhPostion = 1
          this.requestParam.parammaps = this.deptform
          if (this.deptform.pid === null || this.deptform.pid === '') {
            this.requestParam.parammaps.pid = -1
          } else {
            this.requestParam.parammaps.pid = this.deptform.pid
          }
          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) => {
        this.requestParam.name = 'createwh'
        this.deptform.isWhPostion = 1
        this.requestParam.parammaps = this.deptform
        if (this.deptform.pid === null || this.deptform.pid === '') {
          this.requestParam.parammaps.pid = -1
        } else {
          this.requestParam.parammaps.pid = this.deptform.pid
        }
        PostDataByName(this.requestParam).then(response => {
          if (response.msg !== 'fail') {
            this.deptform.remark = ''
            this.deptform.warehoseCode = ''
            this.$notify({ title: '成功', message: '新增成功', type: 'success', duration: 2000 })
          } else {
            failproccess(response, this.$notify)
          }
        })
      })
    },
    // 更新
    form_edit(row) {
      this.defaultCheckedKeys = [row.pid]
      this.deptform.id = row.id
      this.deptform.warehosetName = row.warehosetName
      this.deptform.warehoseCode = row.warehoseCode
      this.deptform.remark = row.remark
      this.deptform.pid = row.pid
      this.deptform.pastureId = this.$store.state.user.pastureid
      this.deptform.section = row.section
      this.deptform.isWhPostion = row.isWhPostion
      this.deptform.sort = row.sort
      this.deptform.enable = row.enable
      this.deptform.tempPtypeCode = this.deptform.warehoseCode.substr(0, this.deptform.warehoseCode.lastIndexOf('.') + 1)
      this.deptform.temptypeCode = this.deptform.warehoseCode.substr(this.deptform.warehoseCode.lastIndexOf('.') + 1)

      this.parentWHVisible = row.pid > 0
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        /*     this.$refs['deptname'].focus() */
      })
    },
    // 提交更新
    edit_dialog_save() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'updatewh'
          this.deptform.warehoseCode = this.deptform.warehoseCode
          // this.deptform.warehoseCode = this.deptform.tempPtypeCode + this.deptform.temptypeCode
          this.requestParam.parammaps = this.deptform

          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)
            }
          })
        }
      })
    },
    handleEnableChange(index, row) {
      this.requestParam.name = 'updatewh'
      if (row.sort === null) {
        row.sort = 0
      }
      this.requestParam.parammaps = row

      PostDataByName(this.requestParam).then(response => {
        if (response.msg !== 'fail') {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
        } else {
          failproccess(response, this.$notify)
        }
      })
    },
    // 导入
    beforeImportExcel(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!')
      }
      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]
          }
        })
      )
    },
    // 导出
    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)
      GetAccount(this.getDeptListParm).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 = [
              'warehoseCode', 'warehosetName', 'section', 'childrens', 'pls', 'pts', 'prs', 'cps', 'isWhPostion', 'enable'
            ]
            const data1 = formatJson(filterVal, list1)
            excel.export_json_to_excel({
              header: tHeader,
              data: data1,
              filename: '库位管理',
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
      })
    },
    form_delete(row) {
      MessageBox.confirm('是否删除当前库位信息？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'deletewh'
        this.requestParam.parammaps = {
          id: row.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)
          }
        })
      })
    }
  }
}
</script>
