<template>
  <div class="app-container">
    <div class="setting_title">账户管理</div>
    <el-divider></el-divider>

    <div class="mymain-container">
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addOrEdit('add')" v-if="checkBtnRole('add')">新增账户</el-button>
        </div>
        <div class="fr">
          <el-select v-model="screenForm.role" placeholder="全部" size="small" style="width: 120px; margin-right: 10px;" @change="getListByScreen">
            <el-option label="全部角色" value=""></el-option>
            <el-option :label="item.name" :value="item.adminRoleId" v-for="(item, index) in roleList" :key="index"></el-option>
          </el-select>
          <el-select v-model="screenForm.status" placeholder="全部" size="small" style="width: 120px; margin-right: 10px;" @change="getListByScreen">
            <el-option label="全部状态" value=""></el-option>
            <el-option :label="item.label" :value="item.value" v-for="(item, index) in select_status" :key="index"></el-option>
          </el-select>
          <el-input placeholder="请输入内容" v-model="screenForm.keyword" size="small" style="width: 180px;">
            <el-button slot="append" icon="el-icon-search" size="small" @click="getListByScreen"></el-button>
          </el-input>
        </div>
      </div>

      <div class="table">
        <el-table v-loading="listLoading" :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe>

          <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
          <el-table-column align="center" label="账号" prop="userName" min-width="120"></el-table-column>
          <el-table-column align="center" label="用户名" prop="nickName" min-width="120"></el-table-column>
          <el-table-column align="center" label="角色" prop="roleName" min-width="100"></el-table-column>
          <el-table-column align="center" label="创建时间" prop="createTime" min-width="160"></el-table-column>
          <el-table-column align="center" label="最后登录时间" prop="lastLoginTime" min-width="160"></el-table-column>
          <el-table-column align="center" label="状态" class-name="status-col">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status ? 'success':'danger'">{{ scope.row.status ? '正常':'冻结' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" min-width="160">
            <template slot-scope="scope">
              <template v-if="checkBtnRole('status')">
                <el-popconfirm v-if="scope.row.status" style="margin-right: 10px;" title="确定冻结吗？" @onConfirm="changeStatus(scope.row.adminUserId, 0)" >
                  <el-button slot="reference" type="text">冻结</el-button>
                </el-popconfirm>
                <el-popconfirm v-else style="margin-right: 10px;" title="确定恢复吗？" @onConfirm="changeStatus(scope.row.adminUserId, 1)" >
                  <el-button slot="reference" type="text">恢复</el-button>
                </el-popconfirm>
              </template>
              
              <el-button type="text" @click="addOrEdit('edit', scope.row.adminUserId)" v-if="checkBtnRole('edit')">编辑</el-button>
              <el-button type="text" @click="handleReset(scope.row.adminUserId)" v-if="checkBtnRole('reset')">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 重置密码 -->
    <el-dialog title="重置密码" :visible.sync="resetFormVisible" :show-close="false" width="40%" :close-on-click-modal="false">
      <el-form ref="resetForm" :model="resetForm" :rules="resetFormRules" label-position="left" label-width="100px">
        <el-form-item label="输入新密码" prop="newPassword">
          <el-input v-model="resetForm.newPassword" ref="password1" autocomplete="off" placeholder="请输入新密码" :type="passwordType1"></el-input>
          <span class="show-pwd" @click="showPwd(1)">
            <svg-icon :icon-class="passwordType1 === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetForm.confirmPassword" ref="password2" autocomplete="off" placeholder="请再次输入新密码" :type="passwordType2"></el-input>
          <span class="show-pwd" @click="showPwd(2)">
            <svg-icon :icon-class="passwordType2 === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelResetForm">取 消</el-button>
        <el-button type="primary" @click="submitResetForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增编辑账户 -->
    <el-dialog :title="addFormType == 'add' ? '新增账户':'编辑账户'" :visible.sync="addFormVisible" :show-close="false" width="40%" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="left" label-width="80px">
        <el-form-item label="账号" prop="account">
          <el-input v-model="addForm.account" autocomplete="off" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="nickName">
          <el-input v-model="addForm.nickName" autocomplete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="角色组" prop="role">
          <el-select v-model="addForm.role" placeholder="请选择角色组" style="width: 100%;">
            <el-option :label="item.name" :value="item.adminRoleId" v-for="(item, index) in roleList" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="department" v-show="accountType === 0">
          <el-tree
            :data="departmentList"
            show-checkbox
            node-key="id"
            ref="tree"
            highlight-current
            :props="props">
          </el-tree>
        </el-form-item>
        <el-form-item label="商户" prop="merchant" v-show="accountType === 1 || accountType === 2">
          <el-select v-model="addForm.merchant" placeholder="请选择商户" style="width: 100%;">
            <el-option :label="item.companyName" :value="item.companyWechatId" v-for="(item, index) in merchantList" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="newPassword">
          <el-input v-model="addForm.newPassword" ref="password1" autocomplete="off" placeholder="请输入密码" :type="passwordType1"></el-input>
          <span class="show-pwd" @click="showPwd(1)">
            <svg-icon :icon-class="passwordType1 === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="addForm.confirmPassword" ref="password2" autocomplete="off" placeholder="请再次输入密码" :type="passwordType2"></el-input>
          <span class="show-pwd" @click="showPwd(2)">
            <svg-icon :icon-class="passwordType2 === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddForm">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getAccountList, getRoleList, changeAccountStatus, resetPassword, addAccount, editAccount, getUserInfo, getDepartmentList, getMerchantList } from '@/api/setting'
import { findElem } from '@/utils/util'

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else if (value && value.length < 6) {
        callback(new Error('密码长度至少6位'));
      } else {
        if (this.resetForm.confirmPassword !== '') {
          this.$refs.resetForm.validateField('confirmPassword');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.resetForm.newPassword) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    var validatePass3 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else if (value && value.length < 6) {
        callback(new Error('密码长度至少6位'));
      } else {
        if (this.addForm.confirmPassword !== '') {
          this.$refs.addForm.validateField('confirmPassword');
        }
        callback();
      }
    };
    var validatePass4 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.addForm.newPassword) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    return {
      dataList: null, // 列表数据
      listLoading: true, // 列表加载loading
      screenForm: { // 筛选表单数据
        role: '', // 角色
        status: '', // 状态
        keyword: '', // 关键词
      },
      select_status: [ // 筛选字段 - 状态
        { label: '正常', value: true },
        { label: '冻结', value: false }
      ],
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      roleList: [], // 角色列表
      departmentList: [], // 部门列表
      props: {
        multiple: true,
        value: 'id',
        label: 'name',
        children: 'children',
      },
      merchantList: [], // 商户列表

      resetId:  null,
      resetFormVisible: false,
      resetForm: {
        newPassword: '', // 新密码
        confirmPassword: '', // 确认密码
      },
      resetFormRules: {
        newPassword: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ],
      },

      editId:  null,
      accountType: '',
      addFormType: 'add',
      addFormVisible: false,
      addForm: {
        account: '', // 账号
        nickName: '', // 用户名
        merchant: '', // 商户
        role: '', // 角色组
        newPassword: '', // 新密码
        confirmPassword: '', // 确认密码
      },
      addFormRules: {
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色组', trigger: 'change' }
        ],
        newPassword: [
          { required: true, validator: validatePass3, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass4, trigger: 'blur' }
        ],
      },

      passwordType1: 'password',
      passwordType2: 'password',
    }
  },
  async created() {
    await this.getRoleList();
    if(this.$route.query.type) {
      let index = findElem(this.roleList, 'name', '企业负责人');
      this.screenForm.role = this.roleList[index].adminRoleId;
    }
    this.getList();
  },
  watch: {
    'addForm.role'() {
      console.log('change role');
      if(this.addForm.role) {
        let index = findElem(this.roleList, 'adminRoleId', this.addForm.role);
        this.accountType = this.roleList[index].type - 1;
      }
      // this.$refs.tree.setCheckedKeys([]);
      // this.addForm.merchant = '';
    }
  },
  methods: {
    // 查询按钮权限
    checkBtnRole(value) {
      // let btnRole = this.$route.meta.roles;
      // if(!btnRole) {return true}
      // let index = btnRole.indexOf(value);
      // return index >= 0 ? true : false;
      return true;
    },
    
    getList() {
      this.listLoading = true;

      let params = {
        roleId: this.screenForm.role,
        status: this.screenForm.status,
        userName: this.screenForm.keyword,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };

      getAccountList(params).then(res => {
        this.dataList = res.data.records;
        this.listTotal = res.data.total;
        this.listLoading = false;
      })
    },

    // 筛选后重新获取列表
    getListByScreen() {
      this.currentPage = 1;
      this.getList();
    },

    // 获取角色列表
    async getRoleList() {
      const result = await new Promise((resolve, reject) => {
        getRoleList({pageNum: 1, pageSize: 1000}).then(res => {
          this.roleList = res.data.records;
          resolve(res.data);
        }).catch(res => {
          resolve([]);
        })
      })
      return result;
    },

    // 获取部门列表
    async getDepartmentList() {
      const result = await new Promise((resolve, reject) => {
        getDepartmentList().then(res => {
          resolve(res.data);
        }).catch(res => {
          resolve([]);
        })
      })
      return result;
    },

    // 获取商户列表
    async getMerchantList() {
      const result = await new Promise((resolve, reject) => {
        getMerchantList({
          pageNum: 1,
          pageSize: 1000
        }).then(res => {
          resolve(res.data.records);
        }).catch(res => {
          resolve([]);
        })
      })
      return result;
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },

    // 操作 - 更改状态(type: 禁用0，启用1)
    changeStatus(id, type) {
      type = type ? true : false
      changeAccountStatus({adminUserId: id, status: type}).then(res => {
        this.getList();
        this.$successMsg();
      })
    },

    // 显示隐藏密码
    showPwd(num) {
      if(num == 1) {
        if (this.passwordType1 === 'password') {
          this.passwordType1 = ''
        } else {
          this.passwordType1 = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password1.focus()
        })
      }
      if(num == 2) {
        if (this.passwordType2 === 'password') {
          this.passwordType2 = ''
        } else {
          this.passwordType2 = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password2.focus()
        })
      }
    },

    // 重置密码
    handleReset(id) {
      this.resetId = id;
      this.resetFormVisible = true;
    },

    // 取消重置密码
    cancelResetForm(){
      this.resetFormVisible = false;
      this.passwordType1 = 'password';
      this.passwordType2 = 'password';
      this.$refs.resetForm.resetFields();
    },

    // 提交重置密码
    submitResetForm() {
      this.$refs.resetForm.validate((valid) => {
        if (valid) {
          let params = {
            password: this.resetForm.newPassword,
            adminUserId: this.resetId
          }
          resetPassword(params).then(res => {
            this.cancelResetForm();
            this.getList();
            this.$successMsg();
          })
        }
      })
    },

    // 新增编辑 账户
    async addOrEdit(type, id) {
      this.addFormType = type;
      this.addFormVisible = true;
      this.departmentList = await this.getDepartmentList();
      this.merchantList = await this.getMerchantList();

      if(type == 'edit') {
        this.editId = id;
        getUserInfo({adminUserId: id}).then(res => {
          this.addForm = {
            account: res.data.userName,
            role: res.data.roleId,
            nickName: res.data.nickName,
            merchant: res.data.companyWechatId
          }
          this.$refs.tree.setCheckedKeys(res.data.adminWebsitIds || []);
        })
      }
    },

    // 取消 新增编辑账户
    cancelAddForm(){
      this.addFormVisible = false;
      this.passwordType1 = 'password';
      this.passwordType2 = 'password';
      this.$refs.addForm.resetFields();
    },

    // 提交 新增编辑账户
    submitAddForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let params = {
            userName: this.addForm.account,
            nickName: this.addForm.nickName,
            roleId: this.addForm.role,
            password: this.addForm.newPassword,
            type: this.accountType
          }
          if(this.accountType === 0) {
            params.adminWebsitIds = this.$refs.tree.getCheckedKeys();
          }else {
            let index = findElem(this.merchantList, 'companyWechatId', this.addForm.merchant);
            params.companyWechatId = this.addForm.merchant;
            params.linkName = this.merchantList[index].linkName || '';
            params.linkPhone = this.merchantList[index].linkPhone || '';
            params.email = this.merchantList[index].email || '';
            params.address = this.merchantList[index].address || '';
          }
          if(this.addFormType == 'edit') {
            params.adminUserId = this.editId;
            editAccount(params).then(res => {
              this.cancelAddForm();
              this.getList();
              this.$successMsg('编辑成功');
            })
          }else {
            addAccount(params).then(res => {
              this.cancelAddForm();
              this.getList();
              this.$successMsg('新增成功');
            })
          }
        }
      })
    },

  }
}
</script>

<style scoped lang="scss">
  .show-pwd {
    position: absolute;
    right: 15px;
    top: 0;
    font-size: 16px;
    cursor: pointer;
    user-select: none;
  }
</style>