<template>
  <div class="manage-account main-wrap">
    <el-form class="search-bar">
      <div class="grid-content">
        <el-input v-model.trim="filters.name" :maxlength="20" placeholder="请输入姓名" clearable></el-input>
      </div>
      <div class="grid-content">
        <el-input v-model.trim="filters.department" :maxlength="20" placeholder="请输入科室" clearable></el-input>
      </div>
      <div class="grid-content">
        <el-select v-model="filters.isFrozen" filterable clearable placeholder="账号状态">
          <el-option v-for="item in accountStatusOptions" :key="item.id" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <el-button type="primary" icon="el-icon-search" @click="searchList">搜索</el-button>
      <el-button class="margin-css" type="primary" icon="el-icon-upload" @click="showEditDialog(0)">新增</el-button>
    </el-form>
    <div class="tabel-wrap">
      <el-table border v-loading="loading" :data="userList" style="width: 100%">
        <el-table-column type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column prop="name" label="姓名" min-width="80">
        </el-table-column>
        <el-table-column prop="department" label="部门科室" min-width="100">
        </el-table-column>
        <el-table-column prop="duty" label="职务" min-width="100">
        </el-table-column>
        <el-table-column prop="title" label="职称" min-width="80">
        </el-table-column>
        <el-table-column prop="sex" :formatter="getSexValue" label="性别" min-width="50">
        </el-table-column>
        <el-table-column prop="birthday" :formatter="(c,r,val) => val ? $formatDate(new Date(val),'yyyy-MM-dd') : ''" label="出生年月" min-width="80">
        </el-table-column>
        <el-table-column prop="cellphone" label="手机号" min-width="100">
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="130" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" class="operationBtnWidth" @click="showEditDialog(1, scope)">修改</el-button>
            <el-button type="primary" size="mini" class="operationBtnWidth" @click="toggleTeacherStatus(scope)">{{scope.row.isFrozen?'账户解冻':'账户冻结'}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination layout="prev, pager, next" :current-page="pagination.pageNum" :page-size="pagination.pageSize" :total="pagination.total" @current-change="changePage">
      </el-pagination>
    </div>
    <!-- 新增/编辑账号 -->
    <drag-dialog :title="editType ? '编辑用户' : '新增用户'" :visible.sync="dialogEditVisible" :before-close="resetEditDialog" width="70%">
      <el-form class="editForm" :disabled="loading">
        <el-form-item class="editItem" label="姓名" label-width="100px">
          <el-input v-model.trim="selected.name" placeholder="请输入姓名" :maxlength="20" clearable></el-input>
        </el-form-item>
        <el-form-item class="editItem" label="部门科室" label-width="100px">
          <el-input v-model.trim="selected.department" placeholder="请输入部门科室" :maxlength="20" clearable></el-input>
        </el-form-item>
        <el-form-item class="editItem" label="职务" label-width="100px">
          <el-input v-model.trim="selected.duty" placeholder="请输入职务" :maxlength="20" clearable></el-input>
        </el-form-item>
        <el-form-item class="editItem" label="职称" label-width="100px">
          <el-input v-model.trim="selected.title" placeholder="请输入职称" :maxlength="20" clearable></el-input>
        </el-form-item>
        <el-form-item class="editItem" label="性别" label-width="100px">
          <el-radio v-for="(sex, index) in sexOptions" :key="index" v-model="selected.sex" :label="sex.value">{{sex.label}}</el-radio>
        </el-form-item>
        <el-form-item class="editItem" label="出生年月" label-width="100px">
          <el-date-picker v-model="selected.birthday" type="date" placeholder="请输入出生年月" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item class="editItem" label="工号" label-width="100px">
          <el-input v-model.trim="selected.jobNumber" placeholder="请输入工号" :maxlength="8" clearable></el-input>
        </el-form-item>
        <el-form-item class="editItem" label="手机号" label-width="100px">
          <el-input v-model="selected.cellphone" ref="telInput" :maxlength="11" placeholder="请输入手机号" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetEditDialog">取 消</el-button>
        <el-button type="primary" @click="updateTeacher">确 定</el-button>
      </div>
    </drag-dialog>
  </div>
</template>

<script>
import listMixin from '@/mixin/listPage.js';
import { mapGetters, mapActions } from 'vuex';
import store from './store.js';
import {
  addTeacher,
  updateTeacher,
  toggleTeacherStatus,
} from '@/api/management/user.js';
import { sexOptions } from '@/config';

export default {
  beforeRouteEnter(to, from, next) {
    store.install();
    next();
  },
  mixins: [listMixin],
  data() {
    return {
      filters: {
        name: '',
        department: '',
        isFrozen: '',
      },
      selected: {},
      accountStatusOptions: [
        {
          label: '解冻',
          value: 0,
        },
        {
          label: '冻结',
          value: 1,
        },
      ],
      sexOptions: sexOptions,
    };
  },
  computed: {
    ...mapGetters('management/user', ['userList', 'pagination']),
    ...mapGetters(['loading']),
  },
  methods: {
    ...mapActions('management/user', { fetchList: 'fetchUserList' }),
    ...mapActions(['fetchAllAuthUserList']),
    initfilters() {
      this.filters = {
        name: '',
        department: '',
        isFrozen: '',
      };
    },
    initSelected() {
      this.selected = {
        userId: '',
        name: '',
        department: '',
        duty: '',
        title: '',
        sex: '',
        birthday: '',
        jobNumber: '',
        cellphone: '',
      };
    },
    getSexValue(c, r, val) {
      let item = this.sexOptions.find(item => item.value == val);
      return item ? item.label : val;
    },
    getFilters() {
      let filters = {
        ...this.$getFilters(this.filters),
        isFrozen: this.filters.isFrozen,
      };
      return filters;
    },
    showEditDialog(type, data) {
      this.editType = type;
      if (type) {
        this.selected = {
          userId: data.row.userId,
          name: data.row.name,
          department: data.row.department,
          duty: data.row.duty,
          title: data.row.title,
          sex: data.row.sex,
          birthday: data.row.birthday,
          jobNumber: data.row.jobNumber,
          cellphone: data.row.cellphone,
        };
      } else {
        this.initSelected();
      }
      this.dialogEditVisible = true;
    },
    validateSelect() {
      if (!this.selected.name) {
        this.$message.error('请输入姓名！');
        return;
      }
      if (!this.selected.department) {
        this.$message.error('请输入部门科室！');
        return;
      }
      // if (!this.selected.duty) {
      //   this.$message.error('请输入职务！');
      //   return;
      // }
      // if (!this.selected.title) {
      //   this.$message.error('请输入职称！');
      //   return;
      // }
      if (!this.selected.sex) {
        this.$message.error('请输入性别！');
        return;
      }
      // if (!this.selected.birthday) {
      //   this.$message.error('请输入出生年月！');
      //   return;
      // }
      return true;
    },
    formatCellphone(val) {
      return val.replace(/\D/g, '');
    },
    updateCellphone(val) {
      console.log(this.$refs.telInput);
      // this.selected.cellphone = val.replace(/\D/g, '');
      this.$refs.telInput.value = val.replace(/\D/g, '');
    },
    updateTeacher() {
      if (!this.validateSelect()) {
        return;
      }
      const entity = {
        userId: this.selected.userId,
        name: this.selected.name,
        department: this.selected.department,
        duty: this.selected.duty,
        title: this.selected.title,
        sex: this.selected.sex,
        birthday: this.selected.birthday,
        jobNumber: this.selected.jobNumber,
        cellphone: this.selected.cellphone,
      };
      this.$confirm(`确认要${this.editType ? '编辑' : '新增'}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          if (this.editType) {
            updateTeacher(entity)
              .then(res => {
                this.fetchList();
                this.resetEditDialog();
                this.$message.success(res.msg);
              })
              .catch(err => {
                this.$message.error(err.msg || '更新失败！');
              });
          } else {
            addTeacher(entity)
              .then(res => {
                this.fetchList();
                this.fetchAllAuthUserList();
                this.resetEditDialog();
                this.$message.success(res.msg);
              })
              .catch(err => {
                this.$message.error(err.msg || '新增失败！');
              });
          }
        })
        .catch(action => {
          console.log(action);
        });
    },
    toggleTeacherStatus(data) {
      this.$confirm(
        `确认要${data.row.isFrozen ? '解冻' : '冻结'} ${data.row.name} 吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          const entity = {
            userId: data.row.userId,
            isFrozen: data.row.isFrozen ? 0 : 1,
          };
          toggleTeacherStatus(entity)
            .then(res => {
              this.fetchList();
              this.$message.success(res.msg);
            })
            .catch(err => {
              this.$message.error('删除失败！');
            });
        })
        .catch(action => {
          console.log(action);
        });
    },
  },
};
</script>

<style lang="scss">
.manage-account {
  .editForm {
    display: flex;
    flex-wrap: wrap;
  }
  .editItem {
    width: 45%;
  }
}
</style>
