<template>
  <div class="app-container">
    <div class="app-container">
      <div class="filter-container">
        <el-select
          v-model="getdataListParm.parammaps.pastureName"
          placeholder="牧场"
          style="width:120px"
          class="filter-item"
        >
          <el-option
            v-for="item in findAllPasture"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
        <el-input v-model="getdataListParm.parammaps.empCode" placeholder="工号" style="width: 140px;" class="filter-item" />
        <el-input v-model="getdataListParm.parammaps.empname" placeholder="姓名" style="width: 140px;" class="filter-item" />
        <el-input v-model="getdataListParm.parammaps.position" placeholder="职位" style="width: 140px;" class="filter-item" />

        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
        <el-button v-if="isEmpAdd" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
        <el-button class="filter-item" type="success" icon="el-icon-download" style="" @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"
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @sort-change="tableSort"
        :max-height="myHeight"
      >
        <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="姓名" min-width="110px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.empname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="EAS账户名" header-align="center" width="120px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.easName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="牧场" min-width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.pastureName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" min-width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.deptname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工号" min-width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.empCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="职位" min-width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.position }}</span>
          </template>
        </el-table-column>
        <el-table-column label="电话" min-width="130px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.tel }}</span>
          </template>
        </el-table-column>
        <el-table-column label="账号数" sortable prop="isuser" min-width="90px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.isuser }}</span>
          </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 v-if="isEmpUpdate" type="primary" size="mini" @click="form_edit(row)">编辑</el-button>
            <el-button v-if="row.status!='已删' && isEmpDel" 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="getdataListParm.offset"
        :limit.sync="getdataListParm.pagecount"
        @pagination="get_table_data"
      />

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
        <el-form
          ref="dataForm"
          v-enterToNext="true"
          :rules="rules"
          :model="dataform"
          label-position="left"
          label-width="100px"
          style="width: 600px; margin-left:50px;"
        >
          <el-form-item label="用户名" prop="empname">
            <el-input ref="empname" v-model="dataform.empname" />
          </el-form-item>
          <el-form-item label="EAS账户名" prop="easName">
            <el-input ref="easName" v-model="dataform.easName" />
          </el-form-item>
          <el-form-item label="部门" prop="deptid">
            <tree-select
              :disabled="disabled"
              :height="280"
              :width="200"
              size="small"
              :data="parentDept"
              :default-props="defaultProps"
              :node-key="nodeKey"
              :checked-keys="defaultCheckedKeys"
              @popoverHide="popoverHide"
            />
          </el-form-item>
          <el-form-item label="职位" prop="position">
            <el-input ref="position" v-model="dataform.position" />
          </el-form-item>
          <el-form-item label="工号" prop="empCode">
            <el-input ref="empCode" v-model="dataform.empCode" />
          </el-form-item>
          <el-form-item label="联系方式" prop="tel">
            <el-input ref="tel" v-model="dataform.tel" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input ref="remark" v-model="dataform.remark" />
          </el-form-item>
          <el-form-item label="顺序" prop="sort">
            <el-input
              ref="sort"
              v-model="dataform.sort"
            />
          </el-form-item>
          <!-- <el-form-item label="启用" prop="enable">
            <el-switch
              ref="enable"
              v-model="dataform.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="dialogStatus==='create'" ref="createb" type="success" @click="add_dialog_save_again()">确认新增</el-button>
          <el-button type="primary" @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
// eslint-disable-next-line no-unused-vars
import { isIntegerZero } from '@/utils/validate'
import { validatePhoneTwo } from '@/utils/validate'
import enterToNext from '@/directive/enterToNext' // enterToNext directive
import { PostDataByName, GetDataByName, getRecuData, GetDataByNames, checkButtons, failproccess,GetAccount } from '@/api/common'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
import { sortChange, json2excel } from '@/utils/index.js'
export default {
  name: 'Emp',
  components: { Pagination, TreeSelect },
  directives: { waves, enterToNext },
  data() {
    return {
      myHeight:document.documentElement.clientHeight - 85- 150,
      isEmpAdd: [],
      isEmpUpdate: [],
      isEmpDel: [],
      disabled: false,
      tableKey: 0,
      list: [{ sqlname: '', id: 0, sqlstr: '' }],
      parentDept: [],
      total: 0,
      listLoading: true,
      requestParam: {
        name: 'createapisql',
        offset: 0,
        pagecount: 0,
        parammaps: []
      },
      dataform: {
        position: '',
        empname: '',
        deptname: '',
        deptid: '',
        tel: '',
        remark: '',
        id: '',
        sort: '',
        parentid: '',
        enable: '1',
        empCode: '',
        easName: ''
      },

      getDeptParm: { name: 'getdeptrecu', idname: 'value', params: [Cookies.get('pastureid')] },
      getdataListParm: {
        name: 'getEmpAllL',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          empname: '',
          empCode: '',
          pastureId: Cookies.get('pastureid'),
          pastureName: Cookies.get('pasturename')
        }
      },
      getdataListParmSH: {
        name: 'getEmpAllL',
        page: 0,
        offset: 0,
        pagecount: 0,
        returntype: 'Map',
        parammaps: {
          empname: '',
          empCode: '',
          pastureId: Cookies.get('pastureid'),
          pastureName: Cookies.get('pasturename')
        }
      },
      rules: {
        empname: [{ type: 'string', required: true, message: '必填', trigger: 'change' }],
        empCode: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
        tel: [
          {
            type: 'number',
            required: true,
            message: '请输入正确的格式',
            trigger: 'change'
          }
        ],

        sort: [{ validator: isIntegerZero, trigger: 'blur' }],
        // eslint-disable-next-line no-dupe-keys
        tel: [{ validator: validatePhoneTwo, trigger: 'blur' }]
      },

      // 2-3：下拉框请求后数据加入[]
      findAllPasture: [],

      // 2-1.请求下拉框接口
      requestParams: [
        { name: 'findAllPasture', offset: 0, pagecount: 0, returntype: 'Map', parammaps: { 'id': Cookies.get('pastureid') }}
      ],

      dialogFormVisible: false,
      selectedRole: '',
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      nodeKey: 'value',
      defaultCheckedKeys: [],
      pageNum: 0,
      pageSize: 10
    }
  },
  created() {
    this.get_table_data()
    this.get_auto_buttons()
  },

  methods: {
    tableSort(column) {
      sortChange(column, this.list)
    },
    get_auto_buttons() {
      // 新增
      const EmpAdd = 'console:emp:add'
      const isEmpAdd = checkButtons(this.$store.state.user.buttons, EmpAdd)
      this.isEmpAdd = isEmpAdd
      // 编辑
      const EmpUpdate = 'console:emp:update'
      const isEmpUpdate = checkButtons(this.$store.state.user.buttons, EmpUpdate)
      this.isEmpUpdate = isEmpUpdate
      // 删除
      const EmpDel = 'console:emp:del'
      const isEmpDel = checkButtons(this.$store.state.user.buttons, EmpDel)
      this.isEmpDel = isEmpDel
    },
    popoverHide(checkedIds, checkedData) {
      console.log(checkedIds, checkedData)
      this.dataform.pastureId = checkedData.pastureId
      this.dataform.deptid = checkedIds
      this.dataform.parentid = checkedData.parentid
    },

    deptenter() {
      this.$nextTick(() => {
        this.$refs['remark'].focus()
      })
    },
    get_table_data() {
      this.listLoading = true
      GetDataByName(this.getdataListParm).then(response => {
        this.list = response.data.list
        this.pageNum = response.data.pageNum
        this.pageSize = response.data.pageSize
        if (response.data.total) {
          this.total = response.data.total
        }
        this.get_select_list()
        this.getDeptList()
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    // 2-2：下拉框
    get_select_list() {
      GetDataByNames(this.requestParams).then(response => {
        this.findAllPasture = response.data.findAllPasture.list
      })
    },

    form_search() {
      this.listLoading = true
      this.getdataListParm.offset = 1
      this.get_table_data()
    },

    getDeptList() {
      getRecuData(this.getDeptParm).then(response => {
        this.parentDept = response.data
      })
    },
    resetRequestParam() {
      this.dataform.easName = ''
      this.dataform.empname = ''
      this.dataform.deptname = ''
      this.dataform.parentid = ''
      this.dataform.deptid = ''
      this.dataform.position = ''
      this.dataform.tel = ''
      this.dataform.remark = ''
      this.dataform.empCode = ''
      this.dataform.id = ''
      this.dataform.sort = '0'
      this.dataform.enable = '1'
      this.defaultCheckedKeys = []
    },
    form_add() {
      this.resetRequestParam()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    add_dialog_save() {
      console.log(this.dataform)
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataform.deptid == '') {
            this.$message({ type: 'error', message: '部门必填', duration: 2000 })
            return false
          }
          this.requestParam.name = 'createEmp'
          this.requestParam.parammaps = {}
          if (this.dataform.easName == '') { this.dataform.easName = this.dataform.empname }
          this.requestParam.parammaps.easName = this.dataform.easName
          this.requestParam.parammaps.empname = this.dataform.empname
          this.requestParam.parammaps.deptid = this.dataform.deptid
          this.requestParam.parammaps.tel = this.dataform.tel
          this.requestParam.parammaps.position = this.dataform.position
          this.requestParam.parammaps.remark = this.dataform.remark
          this.requestParam.parammaps.sort = this.dataform.sort
          this.requestParam.parammaps.enable = this.dataform.enable
          this.requestParam.parammaps.pastureId = this.dataform.pastureId
          this.requestParam.parammaps.empCode = this.dataform.empCode

          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 {
              var Duplicate = new RegExp('Duplicate')
              if (Duplicate.test(response.data)) {
                this.$notify({ title: '', message: '此员工已存在', type: 'warning', duration: 2000 })
              } else {
                failproccess(response, this.$notify)
              }
            }
          })
        }
      })
    },
    add_dialog_save_again() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataform.deptid == '') {
            this.$message({ type: 'error', message: '部门必填', duration: 2000 })
            return false
          }
          this.requestParam.name = 'createEmp'
          this.requestParam.parammaps = {}
          if (this.dataform.easName == '') { this.dataform.easName = this.dataform.empname }
          this.requestParam.parammaps.easName = this.dataform.easName
          this.requestParam.parammaps.empname = this.dataform.empname
          this.requestParam.parammaps.deptid = this.dataform.deptid
          this.requestParam.parammaps.tel = this.dataform.tel
          this.requestParam.parammaps.position = this.dataform.position
          this.requestParam.parammaps.remark = this.dataform.remark
          this.requestParam.parammaps.sort = this.dataform.sort
          this.requestParam.parammaps.enable = this.dataform.enable
          this.requestParam.parammaps.pastureId = this.dataform.pastureId
          this.requestParam.parammaps.empCode = this.dataform.empCode

          PostDataByName(this.requestParam).then(response => {
            if (response.msg !== 'fail') {
              this.get_table_data()
              this.resetRequestParam()
              this.$notify({ title: '成功', message: '新增成功', type: 'success', duration: 2000 })
            } else {
              var Duplicate = new RegExp('Duplicate')
              if (Duplicate.test(response.data)) {
                this.$notify({ title: '', message: '此员工已存在', type: 'warning', duration: 2000 })
              } else {
                failproccess(response, this.$notify)
              }
            }
          })
        }
      })
    },
    form_edit(row) {
      console.log(row)
      this.dataform = Object.assign(row, {})
      this.defaultCheckedKeys = [this.dataform.deptid]
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    edit_dialog_save() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'updateEmp'
          this.requestParam.parammaps = {}
          if (this.dataform.easName == '' || this.dataform.easName == undefined) { this.dataform.easName = this.dataform.empname }
          this.requestParam.parammaps.easName = this.dataform.easName
          this.requestParam.parammaps.empname = this.dataform.empname
          this.requestParam.parammaps.deptid = this.dataform.deptid
          this.requestParam.parammaps.tel = this.dataform.tel
          this.requestParam.parammaps.position = this.dataform.position
          this.requestParam.parammaps.remark = this.dataform.remark
          this.requestParam.parammaps.sort = this.dataform.sort
          this.requestParam.parammaps.enable = this.dataform.enable
          this.requestParam.parammaps.pastureId = this.dataform.pastureId
          this.requestParam.parammaps.empCode = this.dataform.empCode
          this.requestParam.parammaps.id = this.dataform.id
          PostDataByName(this.requestParam).then(() => {
            this.get_table_data()
            this.resetRequestParam()
            this.dialogFormVisible = false
          })
        }
      })
    },
    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.getdataListParmSH.parammaps = this.getdataListParm.parammaps
      // GetDataByName(this.getdataListParm)
      GetAccount(this.getdataListParmSH).then(response => {
        this.downLoadList = response.data.list
        if (response.data.list !== '') {
          this.percentage = 99
          setTimeout(() => {
            this.isPercentage = false
          }, 2000)
        }
        console.log(this.downLoadList)
        const elecExcelDatas = [
          {
            tHeader: ['牧场', '姓名', '部门', '职位', '电话', '工号'],
            filterVal: ['pastureName', 'empname', 'deptname', 'position', 'tel', 'empCode'],
            tableDatas: this.downLoadList,
            sheetName: '员工信息'
          }
        ]
        json2excel(elecExcelDatas, '员工信息', true, 'xlsx')
      })
    },
    form_delete(row) {
      MessageBox.confirm('名称：' + row.empname, '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'deleteEmp'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.id = row.id
        // this.requestParam.params[1] = this.$store.state.user.pastureid
        PostDataByName(this.requestParam).then(response => {
          if (response.msg !== 'fail') {
            this.get_table_data()
            this.resetRequestParam()
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
          } else {
            this.$notify({ title: '失败', message: '删除失败-' + response.data, type: 'danger', duration: 2000 })
          }
        })
      })
    }
  }
}
</script>
