<template>
  <div class="system-account main-wrap">
    <el-form class="search-bar">
      <div class="grid-content">
        <el-input v-model.trim="filters.name" placeholder="请输入姓名" clearable></el-input>
      </div>
      <div class="grid-content">
        <el-input v-model.trim="filters.department" 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="list" style="width: 100%">
        <el-table-column type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column prop="name" label="姓名" min-width="120">
        </el-table-column>
        <el-table-column prop="department" label="部门科室" min-width="120">
        </el-table-column>
        <el-table-column prop="cellphone" label="手机号" min-width="120">
        </el-table-column>
        <el-table-column prop="sex" :formatter="getSexValue" label="性别" min-width="120">
        </el-table-column>
        <el-table-column prop="account" label="登陆账号" min-width="120">
        </el-table-column>
        <el-table-column prop="isFrozen" :formatter="getStatusValue" label="状态" min-width="120">
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="80" align="center">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <el-button type="primary" size="mini">
                <i class="el-icon-setting"></i>
              </el-button>
              <el-dropdown-menu class="AccountIndex" slot="dropdown">
                <el-dropdown-item>
                  <el-button type="primary" size="mini" class="operationBtnWidth" @click="showEditDialog(1, scope)">修改</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="primary" size="mini" class="operationBtnWidth" @click="showUserAuth(scope)">授权</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="primary" size="mini" class="operationBtnWidth" @click="showResetUserPwd(scope)">重置密码</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="primary" size="mini" class="operationBtnWidth" @click="freezeUser(scope)">{{scope.row.isFrozen?'账户解冻':'账户冻结'}}</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </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 class="rateDialog" :title="editType?'修改':'新增'" :visible.sync="dialogEditVisible" :before-close="resetEditDialog">
      <el-form :disabled="loading">
        <el-form-item label="姓名" label-width="200px">
          <el-input v-model.trim="selected.name" placeholder="请输入姓名" :maxlength="20" clearable></el-input>
        </el-form-item>
        <el-form-item label="部门科室" label-width="200px">
          <el-input v-model.trim="selected.department" placeholder="请输入部门科室" :maxlength="20" clearable></el-input>
        </el-form-item>
        <el-form-item label="登陆账号" label-width="200px">
          <span v-if="editType">{{selected.account}}</span>
          <el-input v-else v-model.trim="selected.account" placeholder="请输入登陆账号" :maxlength="20" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="200px">
          <el-input :value="selected.cellphone" @change="updateCellphone" type="number" placeholder="请输入手机号" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别" label-width="200px">
          <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 v-if="editType === 0" label-width="200px">
          <p style="color:red">
            用户初始密码为：123456
          </p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetEditDialog">取 消</el-button>
        <el-button type="primary" @click="updateAccount">确 定</el-button>
      </div>
    </drag-dialog>
    <drag-dialog class="rateDialog" title="权限" :visible.sync="dialogAuthVisible" :before-close="resetAuthDialog">
      <el-checkbox-group class="menuList" v-model="selected.menuList">
        <div class="menuItem" v-for="(menu, index) in menuList" :key="index">
          <div class="menuName">{{menu.menuName}}</div>
          <div class="subMenuList">
            <el-checkbox class="subMenuItem" v-for="(subMenu, index) in menu.childList" :key="index" :label="subMenu.id">{{subMenu.menuName}}</el-checkbox>
          </div>
        </div>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetAuthDialog">取 消</el-button>
        <el-button type="primary" @click="updateUserAuth">确 定</el-button>
      </span>
    </drag-dialog>
  </div>
</template>

<script>
import listMixin from '../../../mixin/listPage.js';
import { accountStatusOptions } from '@/config';
import { mapGetters, mapActions } from 'vuex';
import store from './store.js';
import {
  resetPwd,
  toggleUserFreezeState,
  addAccount,
  updateAccount,
  fetchMenuList,
  fetchUserMenuList,
  updateUserAuthMenu,
} from '@/api/system/account';
import { sexOptions } from '@/config';

export default {
  beforeRouteEnter(to, from, next) {
    store.install();
    next();
  },
  mixins: [listMixin],
  data() {
    return {
      filters: {
        name: '',
        department: '',
        isFrozen: '',
      },
      accountStatusOptions: accountStatusOptions,
      dialogAuthVisible: false,
      menuList: [],
      sexOptions: sexOptions,
    };
  },
  computed: {
    ...mapGetters('system/account', {
      list: 'accountList',
      pagination: 'pagination',
    }),
  },
  methods: {
    ...mapActions('system/account', { fetchList: 'fetchList' }),
    initSelected() {
      this.selected = {
        id: '',
        name: '',
        account: '',
        department: '',
        cellphone: '',
        sex: '',
        menuList: [],
      };
    },
    getSexValue(c, r, val) {
      let item = this.sexOptions.find(item => item.value == val);
      return item ? item.label : val;
    },
    getStatusValue(c, r, val) {
      let item = this.accountStatusOptions.find(item => item.value == val);
      return item ? item.label : val;
    },
    showEditDialog(type, data) {
      this.editType = type;
      if (type) {
        this.selected = {
          id: data.row.id,
          name: data.row.name,
          account: data.row.account,
          department: data.row.department,
          cellphone: data.row.cellphone,
          sex: data.row.sex,
        };
      } else {
        this.initSelected();
      }
      this.dialogEditVisible = true;
    },
    showResetUserPwd(data) {
      this.$confirm(`是否要重置密码？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const entity = {
            id: data.row.id,
          };
          resetPwd(entity)
            .then(res => {
              this.fetchList();
              this.$message.success('密码已重置为123456！');
            })
            .catch(err => {
              this.$message.error('重置密码失败！');
            });
        })
        .catch(action => {
          console.log(action);
        });
    },
    freezeUser(data) {
      this.$confirm(
        `确认要${data.row.isFrozen ? '解冻' : '冻结'} ${data.row.name} 用户吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          const entity = {
            id: data.row.id,
            isFrozen: data.row.isFrozen ? 0 : 1,
          };
          toggleUserFreezeState(entity)
            .then(res => {
              this.fetchList();
              this.$message.success(res.msg);
            })
            .catch(err => {
              this.$message.error('冻结/解冻失败！');
            });
        })
        .catch(action => {
          console.log(action);
        });
    },
    validateSelect() {
      if (!this.selected.name) {
        this.$message.error('请输入姓名！');
        return;
      }
      if (!this.selected.department) {
        this.$message.error('请选择部门科室！');
        return;
      }
      if (!this.selected.account) {
        this.$message.error('请选择登陆账号！');
        return;
      }
      if (!this.selected.cellphone) {
        this.$message.error('请输入手机号！');
        return;
      }
      if (this.selected.cellphone.length !== 11) {
        this.$message.error('请输入正确手机号！');
        return;
      }
      if (!this.selected.sex) {
        this.$message.error('请选择性别！');
        return;
      }
      return true;
    },
    updateCellphone(val) {
      console.log(val);
      this.selected.cellphone = val.slice(0, 11);
    },
    updateAccount() {
      if (!this.validateSelect()) {
        return;
      }
      const entity = {
        id: this.selected.id,
        account: this.selected.account,
        name: this.selected.name,
        department: this.selected.department,
        cellphone: this.selected.cellphone,
        sex: this.selected.sex,
      };
      if (this.editType) {
        updateAccount(entity)
          .then(res => {
            this.fetchList();
            this.resetEditDialog();
            this.$message.success(res.msg);
          })
          .catch(err => {
            this.$message.error(err.msg || '更新失败！');
          });
      } else {
        addAccount(entity)
          .then(res => {
            this.fetchList();
            this.resetEditDialog();
            this.$message.success(res.msg);
          })
          .catch(err => {
            this.$message.error(err.msg || '新增失败！');
          });
      }
    },
    showUserAuth(data) {
      if (this.menuList.length == 0) {
        fetchMenuList().then(res => {
          this.menuList = res.data;
        });
      }
      fetchUserMenuList({
        id: data.row.id,
      })
        .then(res => {
          this.selected = {
            id: data.row.id,
            menuList: res.data,
          };
          this.dialogAuthVisible = true;
        })
        .catch(err => {
          this.$message.error(err.msg || '请求失败');
        });
    },
    resetAuthDialog(done) {
      this.selected = {};
      done && typeof done == 'function'
        ? done()
        : (this.dialogAuthVisible = false);
    },
    updateUserAuth() {
      const entity = {
        id: this.selected.id,
        author: this.selected.menuList.join(','),
      };
      updateUserAuthMenu(entity)
        .then(res => {
          this.$message.success(res.msg);
          this.resetAuthDialog();
        })
        .catch(err => {
          this.$message.success(err.msg || '更新失败！');
        });
    },
  },
};
</script>

<style lang="scss">
.system-account {
  .menuItem {
    padding: 5px 24px;
    border-bottom: 1px solid #ccc;
  }
  .menuName {
    margin: 20px 0 5px;
    font-size: 18px;
  }
  .subMenuList {
    line-height: 40px;
  }
}
</style>
