<template>
  <div id="index">
    <list-normal>
      <template v-slot:title>
        HR成员
      </template>
      <template v-slot:functionBar>
        <el-col :span="6">
          &nbsp;
          <!-- <search v-model="input" placeholder="请输入手机号查询HR"></search> -->
        </el-col>
        <el-col :span="17">
          &nbsp;
          <!-- <el-button type="info" circle icon="el-icon-search icons" @click="search()"></el-button> -->
        </el-col>
        <el-col :span="1">
          <el-button type="success" @click="openAlert('add')" v-if="is_admin">新增HR</el-button>
        </el-col>
      </template>
      <template v-slot:main>
        <el-table :data="dataList" stripe border style="width: 100%">
          <el-table-column align="center" type="index" label="序号" width="50"> </el-table-column>
          <el-table-column align="center" prop="name" label="HR姓名" width="200"></el-table-column>
          <el-table-column align="center" prop="mobile" label="联系电话" width="200"> </el-table-column>
          <el-table-column align="center" prop="operation" label="操作">
            <template v-slot="scoped">
              <el-row :gutter="1" class="row-bg" type="flex" align="middle" justify="center" v-if="judUser(scoped.row)">
                <el-col :span="6">
                  <el-button size="mini" type="text" @click="openAlert('update', scoped.row)">修改密码</el-button>
                </el-col>
                <el-col :span="6">
                  <el-button size="mini" type="text" @click="toBind(scoped.row)">更绑微信</el-button>
                </el-col>
                <el-col :span="6">
                  <el-button size="mini" type="text" @click="toDelete(scoped.row)" v-if="judDelete(scoped.row)">注销用户</el-button>
                </el-col>
                <el-col :span="6">
                  <el-button size="mini" type="text" @click="change(scoped.row)" v-if="changeUser(scoped.row)">转让管理员</el-button>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>

        <el-row class="row_pagination">
          <el-col :span="24">
            <el-pagination
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-size="15"
              layout="total, prev, pager, next, jumper"
              :total="totalRow"
            >
            </el-pagination>
          </el-col>
        </el-row>
        <el-dialog :title="dialogTitle" :visible.sync="dialog" @close="closeAlert">
          <el-row type="flex" align="middle" justify="center">
            <el-col :span="24">
              <el-form :model="form" label-width="auto" label-position="right">
                <el-col :span="24">
                  <el-form-item label="HR姓名" porp="name">
                    <el-input v-model="form.name" style="width: 100%" v-if="!dialogTitle.includes('修改')"></el-input>
                    <span v-else>{{ form.name }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="手机" porp="mobile" v-if="!dialogTitle.includes('修改')">
                    <el-input v-model="form.mobile" style="width: 100%"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="密码" porp="passwd">
                    <el-input v-model="form.passwd" type="password" show-password style="width: 100%"></el-input>
                  </el-form-item>
                </el-col>
              </el-form>
            </el-col>
          </el-row>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialog = false">取 消</el-button>
            <el-button type="primary" @click="onSubmit">确 定</el-button>
          </div>
        </el-dialog>
        <el-dialog :visible.sync="dialogUser" @close="closeAlert">
          <el-row type="flex" align="middle" justify="center">
            <el-col :span="24">
              <el-form :model="formUser" label-width="auto" label-position="right">
                <el-col :span="24">
                  <el-form-item label="用户" prop="name">
                    <el-select v-model="formUser.name" placeholder="请选择用户" style="width:100%" @change="select">
                      <el-option v-for="(item, index) in regionList" :key="index" :label="item.title" :value="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-form>
            </el-col>
          </el-row>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogUser = false">取 消</el-button>
            <el-button type="primary" @click="onSubmitUser">确 定</el-button>
          </div>
        </el-dialog>
        <bind :display="bindDialog" :mobile="mobile" @close="closeAlert">
          <el-col :span="24" style="text-align:center;font-size:1.25rem;padding-top:1rem;">
            扫码更换微信!
          </el-col>
          <template v-slot:footer>
            <el-col :span="24" style="text-align:center;">
              <el-button @click="closeAlert('bind')">返回</el-button>
            </el-col>
          </template>
        </bind>
      </template>
    </list-normal>
  </div>
</template>

<script>
import bind from '@/components/bind.vue';
// import search from '@/components/search.vue';
import listNormal from '@/layout/list-normal.vue';
import _ from 'lodash';
import { mapActions, mapState, mapMutations } from 'vuex';
export default {
  name: 'index',
  // metaInfo: {
  //   title: 'hr管理',
  // },
  components: {
    listNormal,
    bind,
    // search,
  },
  data: () => ({
    dataList: [],
    input: '',
    currentPage: 1,
    totalRow: 0,
    dialogTitle: '',
    dialogWidth: 12,
    dialog: false,
    dialogUser: false,
    form: {},
    formUser: {},
    regionList: [],
    noUse: {},
    pwInput: '',
    mobile: '',
    bindDialog: false,
    is_admin: false,
  }),
  created() {
    this.search();
    this.otherList();
    this.setUser();
  },
  computed: {
    ...mapState(['user']),
  },
  methods: {
    ...mapMutations(['setUser']),
    ...mapActions(['getList', 'hrOperation']),
    async search() {
      let result;
      if (this.input.length > 0) {
        result = await this.hrOperation({ type: 'search', data: { tel: this.input } });
        this.$set(this, `dataList`, [result.data]);
      } else {
        result = await this.hrOperation({ type: 'list', data: this.user.corpid });
        this.$set(this, `totalRow`, result.data.length);
        this.$set(this, `dataList`, result.data);
        let res = this.dataList.filter(fil => fil.role === '0');
        for (const item of res) {
          if (item.mobile === this.user.sub) this.$set(this, `is_admin`, true);
        }
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.search();
    },
    openAlert(type, data) {
      this.$set(this, `dialogTitle`, `${type === 'add' ? '新增' : '修改'}HR`);
      this.$set(this, `dialogWidth`, type === 'add' ? 12 : 24);
      this.$set(this, `dialog`, true);
      if (type !== 'add') {
        this.$set(this, `form`, JSON.parse(JSON.stringify(data)));
      }
    },
    closeAlert(type) {
      if (type === 'bind') {
        this.bindDialog = false;
        this.$set(this, `mobile`, '');
        return;
      }
      this.dialog = false;
      this.form = {};
      this.pwInput = '';
    },
    async onSubmit() {
      let type; //? 'update' : 'add';
      let data = JSON.parse(JSON.stringify(this.form));
      if (this.form._id) {
        type = 'update';
        let { _id, passwd } = data;
        data = { id: _id, passwd: passwd };
      } else {
        type = 'add';
      }
      let result = await this.hrOperation({
        type: type,
        data: { corpid: this.user.corpid, info: data },
      });
      if (`${result.errcode}` === `0`) {
        this.$message.success(type === 'add' ? '添加成功' : '修改成功');
        this.closeAlert();
        this.search();
      }
    },
    async toDelete(item) {
      this.$confirm('您确定注销此HR吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let result = await this.hrOperation({ type: 'delete', data: { id: item._id } });
          if (`${result.errcode}` === '0') {
            this.$message.success('注销成功');
            this.search();
          }
        })
        .catch(() => {});
    },
    toBind(item) {
      this.mobile = JSON.parse(JSON.stringify(item.mobile));
      this.bindDialog = true;
    },
    judDelete(item) {
      //管理员,不能注销
      if (item.role === '0') return false;
      //此hr不是管理员,看当前用户是不是管理员,是管理员则允许
      else if (this.is_admin) return true;
      else return false;
    },
    judUser(item) {
      if (this.is_admin) return true;
      else return item.mobile === this.user.sub;
    },
    changeUser(item) {
      //管理员,不能注销
      if (item.role === '0') return true;
      //此hr不是管理员,看当前用户是不是管理员,是管理员则允许
      else if (this.is_admin) return false;
      else return false;
    },
    async change(item) {
      console.log(item.mobile);
      let result = await this.hrOperation({ type: 'search', data: { tel: item.mobile } });
      this.$set(this, `formUser`, result.data);
      this.dialogUser = true;
    },
    async otherList() {
      let result = await this.hrOperation({ type: 'list', data: this.user.corpid });
      if (`${result.errcode}` === '0') {
        console.log(result.data);
        this.$set(this, `regionList`, result.data);
      } else {
        this.$message.error(result.errmsg ? result.errmsg : 'error');
      }
    },
    select(select) {
      let res = this.regionList.filter(item => {
        return `${item.name}` === `${select}`;
      });
      console.log(res);
    },
    async onSubmitUser() {
      let adminres = this.regionList.filter(item => item.role === '0');
      let adminid;
      for (const item of adminres) {
        adminid = item._id;
      }
      let newres = this.regionList.filter(item => item.role === '1');
      let newid;
      for (const item of newres) {
        newid = item._id;
      }
      let result = await this.hrOperation({ type: 'change', data: { corpid: this.user.corpid, adminid: adminid, id: newid } });
      if (`${result.errcode}` === '0') {
        this.$message.success('修改管理成功');
        sessionStorage.removeItem('token');
        sessionStorage.removeItem('user');
        this.setUser(undefined);
        this.$router.push('/login');
      } else {
        this.$message.error(result.errmsg);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.row_pagination {
  text-align: right;
  margin-top: 1rem;
}
.icons {
  zoom: 2;
  position: relative;
  top: 0.5rem;
}
</style>
