<!--员工管理-->
<template>
  <div v-if="!$root.isOcxShow" class="app-container">
    <!--筛选条件-->
    <div class="search-div">
      <el-form ref="selectForm" :inline="true" :model="listQuery" class="form-container">
        <el-row>
          <el-form-item class="selectForm-container-item">
            <el-input v-model.trim="listQuery.keywords" placeholder="姓名" clearable/>
          </el-form-item>
          <el-form-item class="selectForm-container-item">
            <dept-select v-model="listQuery.deptid" :need-top="true" :dept-show="true" placeholder="单位/部门"/>
          </el-form-item>
          <!--<el-form-item class="selectForm-container-item">-->
          <!--<el-select v-model="listQuery.sex" placeholder="性别" clearable>-->
          <!--<el-option v-for="item in sexList" :key="item.value" :label="item.name" :value="item.value"/>-->
          <!--</el-select>-->
          <!--</el-form-item>-->
          <!--<el-form-item class="selectForm-container-item">-->
          <!--<el-select v-model="listQuery.duty" placeholder="职务" clearable>-->
          <!--<el-option v-for="item in dutyList" :key="item.value" :label="item.name" :value="item.value"/>-->
          <!--</el-select>-->
          <!--</el-form-item>-->
          <el-form-item class="selectForm-container-item" />
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        </el-row>
      </el-form>
    </div>
    <!--查询结果Table显示-->
    <div>
      <el-row class="table-title">
        <el-col :span="6"><div class="title-header"><i class="el-icon-menu"/>数据列表</div></el-col>
        <el-col :span="14" :offset="4" class="edit_btns">
          <el-button v-if="attendanceEnable" class="edit_btn" size="small" @click="initAnnualLeave">初始化剩余年假</el-button>
          <!--批量导入-->
          <el-upload
            v-if="attendanceEnable"
            :limit="1"
            :show-file-list="false"
            :http-request="uploadFile"
            :file-list="fileList"
            action="string"
            accept=".xls,.xlsx"
            class="edit_btn"
            style="margin-top: 0">
            <el-button slot="trigger" class="edit_btn" size="small">批量导入</el-button>
          </el-upload>
          <download-template v-if="attendanceEnable" ref="downloadTemplate" :filename="filename" />
          <el-button v-if="hasPerm('/records/exportStaff')" :disabled="total===0" class="edit_btn" size="small" @click="batchExport">导出记录</el-button>
          <el-button class="edit_btn" size="small" @click="updateData">人员数据下发</el-button>
          <el-button v-if="hasPerm('/staff/delete')" class="edit_btn" size="small" @click="del">删除</el-button>
          <el-button v-if="hasPerm('/staff/add')" class="edit_btn" size="small" @click="add">新增</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="listLoading" ref="dataTable" :data="list" class="table" border @selection-change="handleSelectionChange">
        <el-table-column v-if="hasPerm('/staff/delete')" align="center" type="selection" width="55"/>
        <el-table-column :index="indexMethod" align="center" label="序号" type="index" />
        <el-table-column v-for="column in columns" :key="column.value" :label="column.text" :width="column.width" :align="column.align" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="column.value === 'idCardNo'">{{ encrypIdCardNo(scope.row[column.value]) }}</span>
            <span v-else>{{ scope.row[column.value] ? scope.row[column.value] : scope.row.ext[column.value] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="140">
          <template slot-scope="scope">
            <el-button v-if="hasPerm('/staff/update')" type="text" @click="edit(scope.row)">编辑</el-button>
            <el-button v-if="hasPerm('/iris')&& scope.row['isRegist']=='0'" type="text" @click="registerIris(scope.row)">注册虹膜</el-button>
            <el-button v-if="hasPerm('/iris')&& scope.row['isRegist']=='1'" type="text" @click="registerIris(scope.row)">重新注册</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页-->
    <div class="pagination-container">
      <el-pagination
        v-show="total>listQuery.limit"
        :current-page="listQuery.offset"
        :page-sizes="[20,30,50]"
        :page-size="listQuery.limit"
        :total="total"
        align="center"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
    <capture-iris :v-if.sync="dialogFormVisible" ref="captureIris"/>
    <update-data ref="updateData" @finishUpdate="finishUpdate"/>
  </div>
</template>
<script>
import DeptSelect from '@/components/DeptSelect'
import { getPersonList, getSexType, getDutyType, delPerson, batchExportPerson, batchImportPerson } from '@/api/person'
import DownloadTemplate from '@/components/DownloadTemplate/index'
// import { getToken } from '@/utils/auth' // getToken from cookie
// import { getProject } from '@/utils/baseConfig'
// import { isIE } from '@/utils/browser'
import { downloadFile } from '@/utils/downloadUtils'
import { attendanceEnable } from '@/main.js'
import { initAnnualLeave } from '@/api/attendance'
import CaptureIris from './captureIris'
import UpdateData from './updateData'

export default {
  name: 'ListStaff',
  components: { CaptureIris, DeptSelect, DownloadTemplate, UpdateData },
  data() {
    return {
      listQuery: {
        keywords: '', // 关键字（姓名/身份证号)
        deptid: '', // 部门
        sex: '', // 性别
        duty: '', // 职务
        personType: '1', // 人员类型
        offset: 1,
        limit: 20,
        sort: '',
        order: ''
      }, // 筛选条件
      columns: [], // 显示列
      multipleSelection: [], // 多选选中项
      list: [], // 列表数据
      total: 0, // 数据总数
      sexList: [], // 性别列表
      dutyList: [], // 职务列表
      listLoading: false, // 加载动画
      fullscreenLoading: false, // 全屏加载动画
      filename: 'personAtdTempDownload.xlsx',
      attendanceEnable: attendanceEnable,
      fileList: []
    }
  },
  mounted() {
    this.columns = [
      {
        text: '员工编号',
        value: 'personCode',
        align: 'center'
      },
      {
        text: '姓名',
        value: 'name',
        align: 'center'
      },
      {
        text: '性别',
        value: 'sexName',
        align: 'center'
      },
      {
        text: '身份证号',
        value: 'idCardNo',
        align: 'center',
        width: 180
      },
      {
        text: '单位/部门',
        value: 'deptName',
        align: 'center'
      },
      {
        text: '职务',
        value: 'dutyName',
        align: 'center'
      }
      // ,
      // {
      //   text: '备注',
      //   value: 'remarks',
      //   width: 140,
      //   align: 'center'
      // }
    ]
    if (attendanceEnable === true) {
      this.columns.push(
        {
          text: '考勤',
          value: 'isKaoqinName',
          align: 'center'
        })
      this.columns.push(
        {
          text: '统计加班',
          value: 'isOtName',
          align: 'center'
        })
      this.columns.push(
        {
          text: '专务',
          value: 'isZhuanwuName',
          align: 'center'
        })
      this.columns.push(
        {
          text: '部门正职领导',
          value: 'isLeaderName',
          align: 'center'
        })
      this.columns.push(
        {
          text: '年假/天',
          value: 'initAnnualLeave',
          align: 'center'
        })
      this.columns.push(
        {
          text: '剩余年假/天',
          value: 'annualLeave',
          align: 'center'
        })
    }
    this.fetchSexType()// 获取性别列表
    this.fetchDutyType() // 获取职务列表
    this.fetchData()// 获取数据
  },
  activated() {
    this.fetchData(false)
  },
  methods: {
    receiveParamsFromHtml(res) {},
    // 检查选择情况
    checkSelection() {
      if (this.multipleSelection.length === 0) {
        return false
      } else {
        return true
      }
    },
    // 新增设备
    add() {
      this.$router.push({ path: '/addStaff', query: { type: 'create', personType: '1' }})
    },
    // 编辑设备信息
    edit(row) {
      this.$router.push({ path: '/updateStaff', query: { type: 'update', personType: '1', id: row.id }})
    },
    // 删除人员
    del() {
      if (this.checkSelection()) {
        const staffIds = []
        this.multipleSelection.forEach(function(value, index) {
          staffIds.push(value.id)
        })
        this.$confirm(
          '确定要删除所选员工吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          this.listLoading = true
          delPerson(staffIds).then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchData()
              this.listLoading = false
            }
          }).catch(() => {
            this.fetchData()
            this.listLoading = false
          })
        })
      } else {
        this.$message.error('至少选中一项')
      }
    },
    registerIris(row) {
      this.dialogFormVisible = true
      this.$refs.captureIris.initDialog(this.dialogFormVisible, row, '0')
    },
    initAnnualLeave() {
      this.$confirm(
        '此操作不可撤销！仍要将所有员工的剩余年假设置为初始值吗？',
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        initAnnualLeave().then(response => {
          if (response.code === 200) {
            this.$message.success('重置成功')
            this.fetchData()
          }
        })
      })
    },
    // 批量导出
    batchExport() {
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '数据处理中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      batchExportPerson(this.listQuery).then(res => {
        loading.close() // 关闭加载动画
        downloadFile(res.data, '员工列表')
      }).catch((res) => {
        loading.close()
      })
    },
    // 批量导入
    uploadFile(param) {
      // 判断文件大小是否符合要求
      const _file = param.file
      const isLt5M = _file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('请上传5M以下的excel文件')
        return false
      }
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '导入中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 发起导入请求
      batchImportPerson(_file).then(res => {
        loading.close() // 关闭加载动画
        if (res.code === 200) {
          this.$message.success('导入成功')
          this.fileList = []
          this.fetchData(false)
        }
      }).catch(() => {
        loading.close()
      })
      this.fileList = []
    },
    // 查询数据
    search() {
      this.fetchData(false)
    },
    // 获取集中器数据
    fetchData(isNowPage = true) {
      this.listLoading = true
      if (!isNowPage) { // 是否显示当前页，否则跳转第一页
        this.listQuery.offset = 1
      }
      getPersonList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = parseInt(response.data.total)
        this.listLoading = false
      })
    },
    // 获取性别
    fetchSexType() {
      getSexType().then(response => {
        this.sexList = response.data
      })
    },
    // 获取职务
    fetchDutyType() {
      getDutyType().then(response => {
        this.dutyList = response.data
      })
    },
    indexMethod(index) {
      return this.listQuery.limit * (this.listQuery.offset - 1) + index + 1
    },
    // 改变页容量
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    // 改变当前页
    handleCurrentChange(val) {
      this.listQuery.offset = val
      this.fetchData()
    },
    // 多选触发方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 身份证号加密
    encrypIdCardNo(idCardNo) {
      if (idCardNo) {
        return idCardNo.substr(0, 6) + '********' + idCardNo.substr(14, 18)
      } else {
        return ''
      }
    },
    // 人员数据下发
    updateData() {
      if (this.checkSelection()) {
        this.$refs.updateData.initDialog(true, this.multipleSelection)
      } else {
        this.$message.error('至少选中一项')
      }
    },
    finishUpdate() {
      this.$refs.dataTable.clearSelection()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  $tableTitleHeight:46px;
  .app-container{
    margin-bottom:20px
  }
  .table{
    margin-bottom: 20px;
  }
  .pagination-container{
    margin-bottom: 50px;
  }
  .table-title{
    background-color:rgba(243, 243, 243, 1);
    height: $tableTitleHeight;
    .title-header{
      line-height:$tableTitleHeight;
      color: #606266;
      font-size: 15px;
      i{
        margin-left: 5px;
        margin-right: 5px;
      }
    }
  }
  .edit_btns{
    .edit_btn{
      float:right;
      margin:7px 3px;//为了需要居中显示margin-top和bottom要用$tableTitleHeight减去按钮原高度除以2
    }
  }
</style>
