<template>
  <div class='m-container'>
    <h2>
      <div class="squrt"></div>员工管理
    </h2>
    <div class="m-core">
      <div @click="roleOperation('create')"
           v-permission="'employee/add'"
           class='newBand'>添加</div>

      <el-form :inline="true"
               class="searchForm"
               @submit.native.prevent
               v-model="searchForm">
        <el-form-item>
          <el-input type="text"
                    v-model="searchForm.search"
                    @keyup.enter.native='search'
                    placeholder="姓名或手机号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.jobNature"
                     clearable
                     filterable
                     placeholder="请选择工作类型">
            <el-option label="全职"
                       value="FULL_TIME"></el-option>
            <el-option label="兼职"
                       value="PART_TIME"></el-option>
            <el-option label="临时"
                       value="TEMPORARY"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.organId"
                     clearable
                     filterable
                     placeholder="请选择分部">
            <el-option v-for="item in branchList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <!--   multiple -->
          <el-select v-model="searchForm.roleId"
                     clearable
                     filterable
                     placeholder="请选择角色">
            <el-option v-for="item in roleList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
          <!-- collapse-tags -->
        </el-form-item>
        <el-form-item>
          <el-button @click="search"
                     type="danger">搜索</el-button>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <div class="tableWrap">
        <el-table :data='tableList'
                  :header-cell-style="{background:'#EDEEF0',color:'#444'}">
          <el-table-column align='center'
                           prop="realName"
                           label="姓名">
          </el-table-column>
          <el-table-column align='center'
                           prop="phone"
                           label="手机号">
          </el-table-column>
          <el-table-column align='center'
                           label="角色分类">
            <template slot-scope="scope">
              <span style="max-height: 68px;display: block;"
                    :title="scope.row.roleNames | joinArray(',')">{{ scope.row.roleNames | joinArray(',') }}</span>
            </template>
          </el-table-column>
          <el-table-column align='center'
                           prop="jobNature"
                           label="工作类型">
            <template slot-scope="scope">
              {{ scope.row.jobNature | jobNature }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           label="所属部门">

            <span style="display: inline-block;width: 100%;overflow: hidden;white-space: nowrap; text-overflow: ellipsis;"
                  slot-scope="scope">
              <el-popover placement="top-start"
                          width="200"
                          trigger="hover"
                          :content="scope.row.organNameList | joinArray(',')">
                <span slot="reference">{{ scope.row.organNameList | joinArray(',') }}</span>
              </el-popover>

            </span>
          </el-table-column>
          <el-table-column align='center'
                           label="状态"
                           :formatter="formatLockFlag">
          </el-table-column>
          <el-table-column align='center'
                           label="入职时间">
            <template slot-scope="scope">
              {{ scope.row.entryDate | formatTimer }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           label="离职时间">
            <template slot-scope="scope">
              {{ scope.row.demissionDate | formatTimer }}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           width="250px"
                           label="操作">
            <template slot-scope="scope">
              <el-button @click="roleOperation('update', scope.row)"
                         v-permission="'employee/update'"
                         type="text">修改</el-button>
              <el-button @click="onStaffOperation('RESET_PASSWORD', scope.row)"
                         v-permission="'employee/employeeOperate'"
                         type="text">重置密码</el-button>
              <el-button @click="onStaffOperation('LOCK_UNLOCK', scope.row)"
                         v-permission="'employee/employeeOperate'"
                         type="text">{{ scope.row.lockFlag == 1 ? '解冻' : '冻结' }}</el-button>
              <el-button @click="onStaffOperation('DEMISSION', scope.row)"
                         v-permission="'employee/employeeOperate'"
                         type="text">{{ scope.row.demissionDate ? '复职' : '离职' }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="pageInfo.total"
                    :page.sync="pageInfo.page"
                    :limit.sync="pageInfo.limit"
                    :page-sizes="pageInfo.page_size"
                    @pagination="getList" />
      </div>
    </div>

    <el-dialog :title="formTitle[formActionTitle]"
               :visible.sync="roleStatus"
               @close="onFormClose('ruleForm')"
               width="500px">
      <el-form :model="form"
               :rules="rules"
               ref="ruleForm">
        <el-form-item label="姓名"
                      prop="realName"
                      :label-width="formLabelWidth">
          <el-input v-model="form.realName"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别"
                      prop="gender"
                      :label-width="formLabelWidth">
          <el-select v-model="form.gender"
                     clearable
                     filterable>
            <el-option label="男"
                       :value="1"></el-option>
            <el-option label="女"
                       :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号"
                      prop="phone"
                      :label-width="formLabelWidth">
          <el-input v-model.number="form.phone"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色分类"
                      prop="roleIds"
                      :label-width="formLabelWidth">
          <el-select v-model="form.roleIds"
                     clearable
                     filterable
                     multiple>
            <el-option v-for="item in roleList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
          <!-- collapse-tags -->
        </el-form-item>
        <el-form-item label="所属部门"
                      prop="organIdLists"
                      :label-width="formLabelWidth">
          <el-select style="width: calc(100% - 75px) !important;"
                     filterable
                     clearable
                     v-model="form.organIdLists"
                     multiple>
            <el-option v-for="item in branchList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
          <el-button @click="onBranchCheckAll">全选</el-button>
        </el-form-item>
        <el-form-item label="工作类型"
                      prop="jobNature"
                      :label-width="formLabelWidth">
          <el-select v-model="form.jobNature"
                     clearable
                     filterable>
            <el-option label="全职"
                       value="FULL_TIME"></el-option>
            <el-option label="兼职"
                       value="PART_TIME"></el-option>
            <el-option label="临时"
                       value="TEMPORARY"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间"
                      prop="entryDate"
                      :label-width="formLabelWidth">
          <el-date-picker v-model="form.entryDate"
                          type="date"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="roleStatus = false">取 消</el-button>
        <el-button @click="onRoleSubmit('ruleForm')"
                   type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import pagination from '@/components/Pagination/index'
import { queryEmployByOrganId, employeeOperate, getUserRole, employeeAdd, employeeUpdate } from '@/api/systemManage'
import { branchQueryPage } from '@/api/specialSetting'
import store from '@/store'
import { isvalidPhone } from '@/utils/validate'
let validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入电话号码'))
  } else if (!isvalidPhone(value)) {
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}
export default {
  components: { pagination },
  data () {
    return {
      tableList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      roleStatus: false,
      formActionTitle: 'create',
      roleList: [], // 角色列表
      branchList: [], // 分部列表
      formTitle: {
        create: '添加员工',
        update: '修改员工'
      },
      formLabelWidth: '100px',
      form: {
        realName: null,
        gender: null,
        phone: null,
        roleIds: [],
        organIdLists: [],
        jobNature: null,
        entryDate: null,
      },
      rules: {
        realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        phone: [{ type: 'number', required: true, validator: validPhone, trigger: 'blur' }],
        roleIds: [{ type: 'array', required: true, message: '请选择分类', trigger: 'change' }],
        organIdLists: [{ type: 'array', required: true, message: '请选择所属部门', trigger: 'change' }],
        jobNature: [{ required: true, message: '请选择工作类型', trigger: 'change' }],
        entryDate: [{ required: true, message: '请选择入职时间', trigger: 'blur' }],
      },
      searchForm: {
        search: null,
        jobNature: null,
        organId: null,
        roleId: null
      }
    }
  },
  mounted () {
    this.getList()
    this.getRoleList()


  },
  methods: {
    onBranchCheckAll () {
      this.form.organIdLists = []
      this.branchList.forEach(item => {
        this.form.organIdLists.push(item.value)
      })
    },
    onRoleSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.organIdList = this.form.organIdLists.join(',')
          if (this.formActionTitle == 'create') {
            if (this.form.id) { // 判断有没有Id，如果有则删除
              delete this.form.id
            }
            employeeAdd(this.form).then(res => {
              this.messageTips('添加', res)
            })
          } else if (this.formActionTitle == 'update') {
            employeeUpdate(this.form).then(res => {
              this.messageTips('修改', res)
            })
          }
        } else {
          return
        }
      })
    },
    messageTips (title, res) {
      if (res.code == 200) {
        this.$message.success(title + '成功')
        this.roleStatus = false
        this.getList()
      } else {
        this.$message.error(res.msg)
      }
    },
    search () {
      this.pageInfo.page = 1
      this.getList()
    },
    getList () {
      let params = this.searchForm
      params.rows = this.pageInfo.limit
      params.page = this.pageInfo.page
      queryEmployByOrganId(params).then(res => {
        if (res.code == 200 && res.data) {
          this.tableList = res.data.rows
          this.pageInfo.total = res.data.total
        }
      })
    },
    getRoleList () { // 获取角色
      getUserRole({ delFlag: 0, rows: 9999 }).then(res => {
        let result = res.data
        if (res.code == 200 && result && result.rows.length > 0) {
          result.rows.forEach(item => {
            this.roleList.push({
              label: item.roleName,
              value: item.id
            })
          })
        }
      })
      branchQueryPage({ // 获取分部
        delFlag: 0,
        rows: 9999
      }).then(res => {
        if (res.code == 200 && res.data && res.data.rows) {
          res.data.rows.forEach(item => {
            this.branchList.push({
              label: item.name,
              value: item.id
            })
          })
        }
      })

    },
    roleOperation (type, data) {
      this.formActionTitle = type
      this.roleStatus = true
      // 修改的时候
      if (type == 'update') {
        this.form = {
          id: data.id,
          realName: data.realName,
          gender: data.gender,
          phone: Number(data.phone),
          roleIds: data.roleIds,
          organIdLists: data.organIdList ? data.organIdList : [],
          jobNature: data.jobNature,
          entryDate: data.entryDate
        }
      }
    },
    onFormClose (formName) { // 关闭弹窗重置验证
      this.form = {
        realName: null,
        gender: null,
        phone: null,
        roleName: null,
        organIdLists: [],
        jobNature: null,
        entryDate: null
      }
      this.$refs[formName].resetFields()
    },
    formatLockFlag (row) {
      let reuslt = ['正常', '冻结']
      if (row.demissionDate) {
        return '离职'
      } else {
        return reuslt[row.lockFlag]
      }
    },
    onStaffOperation (type, data) {
      employeeOperate({
        employeeId: data.id,
        operate: type
      }).then(res => {
        if (res.code == 200) {
          this.$message.success('更改成功')
          this.roleStatus = false
          this.getList()
        } else {
          this.$message.error(res.msg)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/.el-button--primary {
  background: #14928a;
  border-color: #14928a;
  color: #fff;
  &:hover,
  &:active,
  &:focus {
    background: #14928a;
    border-color: #14928a;
    color: #fff;
  }
}
/deep/.el-dialog__body {
  padding: 0 20px;
}
/deep/.el-select,
/deep/.el-date-editor.el-input {
  width: 100% !important;
}
</style>