<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="container_item">
        <span class="item_text">用户名：</span>
        <el-input v-model="query.account" placeholder="" class="filter-item input_item"  />
      </div>
      <div class="container_item">
        <span class="item_text">真实姓名：</span>
        <el-input v-model="query.name" placeholder="" class="filter-item input_item"    />
      </div>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-my-search" @click="handleSearch">
        {{ $t('table.search') }}
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-my-reset" @click="query={};handleSearch()">
        {{ $t('table.reset') }}
      </el-button>
      <el-button v-if="permission.includes('user_add')" v-waves class="filter-item" type="primary" icon="el-icon-my-add" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>
    <div class="wrapper_table">
      <el-table
        :data="tableData"
        fit
        stripe
        highlight-current-row
        style="width: 100%;"
        :header-cell-class-name="headerStyle"
        :max-height="tableHeight"
      >
        <el-table-column :label="$t('user.account')"  align="left">
          <template slot-scope="{row}">
            <span>{{ row.account  }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('user.orgId')" align="left">
          <template slot-scope="{row}">
            <span>{{ row.orgName }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('user.employeeNumber')"  align="left">
          <template slot-scope="{row}">
            <span>{{ row.employeeNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" :label="$t('user.name')"  align="left"></el-table-column>
        <el-table-column prop="phone" :label="$t('user.phone')" align="left"></el-table-column>
        <el-table-column prop="emailAddress" :label="$t('user.emailAddress')" align="left" width="160" show-overflow-tooltip></el-table-column>
        <el-table-column prop="pwdExpireTime" :label="$t('user.pwdExpireTime')" width="160" align="left"></el-table-column>
        <el-table-column :label="$t('table.actions')" align="left" width="250">
          <template slot-scope="{row}">
            <div class="flex_d">
              <el-button v-if="permission.includes('user_pwd_init')" type="text" size="mini" icon="el-icon-my-init-pwd" @click="handleReset(row)">
                {{ $t('table.initPwd') }}
              </el-button>
              <el-button v-if="permission.includes('user_update')" type="text" size="mini" icon="el-icon-my-edit" @click="handleUpdate(row)">
                {{ $t('table.edit') }}
              </el-button>
              <el-button v-if="permission.includes('user_pwd_modify')" size="mini" type="text" icon="el-icon-my-chpwd" @click="handleChangePwd(row)">
                {{ $t('table.changePwd') }}
              </el-button>
            </div>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="getData" />
    <el-dialog
      :title="handleType==1?'新增用户':'编辑用户'"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="560px">
      <div class="userinfo">
        <p>用户信息</p>
        <el-form ref="dataForm"  :model="temp" label-position="right" label-width="100px"  >
           <el-form-item class="require" :label="$t('user.account')+'：'">
            <el-input v-model="temp.account"/>
          </el-form-item>
          <el-form-item class="require" :label="$t('user.orgId')+'：'">
            <el-select v-model="temp.orgId"  >
              <el-option v-for="item in orgList" :key="item.id" :label="item.orgName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item class="require" :label="$t('user.userType')+'：'">
            <el-select v-model="temp.userType"  >
              <el-option
                v-for="item in userTypeList"
                :key="item.id"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item class="require" :label="$t('user.employeeNumber')+'：'">
            <el-input v-model="temp.employeeNumber" />
          </el-form-item>
          <el-form-item class="require" :label="$t('user.name')+'：'">
            <el-input v-model="temp.name"  />
          </el-form-item>
          <el-form-item class="require" :label="$t('user.phone')+'：'">
            <el-input v-model="temp.phone"  />
          </el-form-item>
          <el-form-item class="require" label="生日：">
            <el-date-picker
              v-model="temp.birthday"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择生日"
              style="width: 100%;"></el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('user.emailAddress')+'：'">
            <el-input v-model="temp.emailAddress"  />
          </el-form-item>
          <el-form-item :label="$t('user.status')+'：'">
            <el-radio-group v-model="temp.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="2">注销</el-radio>
            </el-radio-group>
          </el-form-item>


        </el-form>
      </div>
       <div class="userinfo">
        <p>角色设置</p>
        <div class="tab">
          <el-table
            ref="multipleTable"
            :data="listRole"
            fit
            stripe
            highlight-current-row
            style="width: 100%;"
            :header-cell-class-name="headerStyle"
            max-height="300px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
            type="selection"
            width="55">
            </el-table-column>
            <el-table-column prop="name" :label="$t('role.name')" align="center"></el-table-column>
            <el-table-column :label="$t('role.description')" prop="description"  align="center"></el-table-column>
            <!-- <el-table-column :label="$t('table.actions')" >
              <template slot-scope="{row}">
              <span @click="authorization(row)">授权管理</span>
              </template>
            </el-table-column> -->
          </el-table>
        </div>

       </div>

      <div slot="footer" class="dialog-footer" style="padding-right:26px">
        <el-button v-waves class="filter-item flex_align" type="primary" icon="el-icon-my-tijiao" @click="sbumitData">
            {{ $t('table.sbumit') }}
        </el-button>
        <el-button v-waves class="filter-item flex_align" type="primary" icon="el-icon-my-quxiao" @click="dialogFormVisible=false">
            {{ $t('table.cancel') }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('user.chpwd')"
      :visible.sync="chpwdVisible"
      v-el-drag-dialog
      :close-on-click-modal="false"
      width="460px">
        <el-form ref="dataForm" :model="form" label-position="right" style="margin-top:20px" label-width="100px" >
          <el-form-item :label="$t('user.account')+'：'" class="unabled">
            <el-input disabled v-model="pwdChangeData.account"  style="width:294px"  />
          </el-form-item>
          <el-form-item :label="$t('user.oldPassword')+'：'" class="require">
             <el-input v-model="form.oldPassword" type="password"  style="width:294px"  />
          </el-form-item>
          <el-form-item :label="$t('user.password')+'：'" class="require">
            <el-input v-model="form.password"  type="password"  style="width:294px"  />
          </el-form-item>
          <el-form-item :label="$t('user.confirmPassword')+'：'" class="require">
            <el-input v-model="form.confirmPassword" type="password"  style="width:294px"  />
          </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer" style="padding-right:26px">
        <el-button v-waves class="filter-item flex_align" type="primary" icon="el-icon-my-tijiao" @click="sbumitPwd">
            {{ $t('table.sbumit') }}
        </el-button>
        <el-button v-waves class="filter-item flex_align" type="primary" icon="el-icon-my-quxiao" @click="chpwdVisible = false">
            {{ $t('table.cancel') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog'
import { mapGetters } from 'vuex'
import http from '@/api/http'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import md5 from 'js-md5';
import { validatenull } from '@/utils/validate.js'
export default {
  name: '',
  components: { Pagination },
  directives: { waves, elDragDialog },
  computed: {
    ...mapGetters([
      'permission',
    ])
  },
  data() {
    return {
      total: 0,
      query:{},
      listRole:[],
      tableData:[],
      pageSize:10,
      pageNum:1,
      orgList:[],
      form:{},
      temp: {},
      dialogFormVisible: false,
      dialogStatus: '',
      handleType:'1',
      tableHeight: 0,
      chpwdVisible:false,
      pwdChangeData:{},
      multipleSelection:[],
      userTypeList: [ // 1总行2分行3客户经理
        { id: 1, label: '总行', value: 1 },
        { id: 2, label: '分行', value: 2 },
        { id: 3, label: '客户经理', value: 3 },
      ]
    }
  },
  created() {
    this.getData()
    this.getRole()
    this.getOrg()
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 250
    })
  },
  methods: {
    getData() {
      http.post(`/sys/userinfo/queryLists`,{cpage:this.pageNum,pageSize:this.pageSize,...this.query}).then((res)=>{
          this.tableData = res.data.list;
          this.total = res.data.total || 0;
      }).catch(err=>{});
    },
    getRole(){
      http.post(`/sys/userRole/queryLists`,{cpage:1,pageSize:99}).then((res)=>{
          this.listRole = res.data.list;
      }).catch(err=>{});
    },
    getOrg(){
      http.post(`/sys/org/queryLists`,{cpage:1,pageSize:99}).then((res)=>{
          this.orgList = res.data.list;
      }).catch(err=>{});
    },
    handleSearch(){
      this.pageNum = 1
      this.getData()
    },
    sbumitPwd(){
      let { oldPassword, password, confirmPassword } = this.form
      if (validatenull(oldPassword)) {
        this.$message.error('旧密码不能为空')
        return
      }
      if (validatenull(password)) {
        this.$message.error('新密码不能为空')
        return
      }
      if (validatenull(confirmPassword)) {
        this.$message.error('确认密码不能为空')
        return
      }
      if(this.form.password != this.form.confirmPassword){
        this.$message.error('新密码和确认密码不一致')
        return false
      }
      let par = {
        id:this.pwdChangeData.id,
        oldPassword: oldPassword,
        password: password,
        confirmPassword: confirmPassword
        // oldPassword: md5(this.form.oldPassword),
        // password: md5(this.form.password),
        // confirmPassword: md5(this.form.confirmPassword)
      }
      http.post(`/sys/userinfo/modifyPasswd`,par).then((res)=>{
        this.$message.success('修改成功！');
        this.chpwdVisible = false
      }).catch(err=>{});
    },

    handleChangePwd(row){
      this.form = {}
      this.pwdChangeData = row
      this.chpwdVisible = true
    },

    handleCreate() {
      this.temp = {}
      this.handleType = 1
      this.dialogFormVisible = true
    },
    // 用户密码重置
    handleReset(row) {
      http.post('/sys/userinfo/resetPasswd', { id: row.id, status: 1 }).then((res) => {
        this.$message.success(res.msg.info)
      })
    },
    sbumitData() {
      if(!this.temp.account){
          this.$message.error('请输入用户名')
          return false
      }
      if(!this.temp.orgId){
        this.$message.error('请选择用户机构')
        return false
      }
      if(!this.temp.userType){
        this.$message.error('请选择用户类型')
        return false
      }
      if(!this.temp.employeeNumber){
          this.$message.error('请输入工号')
          return false
      }
      if(!this.temp.name){
          this.$message.error('请输入真实姓名')
          return false
      }
      if(!this.temp.phone){
          this.$message.error('请输入手机号')
          return false
      }else{
        var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
        if (!myreg.test(this.temp.phone)) {
            this.$message.error('手机号格式不正确')
          return false;
        }
      }
      if(!this.temp.birthday){
          this.$message.error('请选择生日')
          return false
      }
      if(this.temp.status!==0&&!this.temp.status){
          this.$message.error('请选择用户状态')
          return false
      }
      if(this.temp.emailAddress){
        var emailReg=/^(\w|(\.\w+))+@([a-zA-Z0-9_-]+\.)+(com|org|cn|net)+$/;
        if(!emailReg.test(this.temp.emailAddress)) {
            this.$message.error('邮箱格式不正确')
          return false;
        }
      }
      if(this.multipleSelection.length==0){
        this.$message.error('请选择用户角色')
        return false
      }
      for(let item of this.orgList){
        if(item.id == this.temp.orgId){
          this.temp.orgTreeCode = item.orgTreeCode
        }
      }
      let roleIds = []
      for(let item of this.multipleSelection){
        roleIds.push(item.id)
      }
      this.temp.roleIds = roleIds
      let { birthday } = this.temp
      this.temp = Object.assign(this.temp, { birthday: birthday ? birthday+" 00:00:00" : "" })
      if(this.handleType==1){
        http.post(`/sys/userinfo/create`,this.temp).then((res)=>{
            this.$message.success('提交成功！');
            this.getData();
            this.dialogFormVisible = false;
        }).catch(err=>{});
      }else{
        this.temp.password = ''
        http.post(`/sys/userinfo/update`,this.temp).then((res)=>{
            this.$message.success('提交成功！');
            this.getData();
            this.dialogFormVisible = false;
        }).catch(err=>{});
      }
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.orgItem = {
      //   id: row.orgId,
      //   orgCode: row.orgTreeCode
      // }
      this.handleType = 2
      this.dialogFormVisible = true
      // console.log('listRole', this.listRole);
      // 通过id查询用户所有角色信息
      http.post('/sys/userRole/findRoleByuserId', { id: row.id }).then((res) => {
        // console.log('res.data', res.data);
        let idArr = res.data.map((v) => { return v.id })
        // console.log(idArr);
        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection();
          if (!validatenull(res.data)) {
            this.listRole.forEach((row) => {
              if (idArr.includes(row.id)) {
                this.$refs.multipleTable.toggleRowSelection(row);
              }
            })
          }
        })
      })
    },

    headerStyle() {
      return 'tableStyle'
    },
    authorization(){

    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  }
}
</script>
<style scoped lang="scss">
  .userinfo{
    margin: 20px 50px;
    width: 464px;
    // height: 313px;
    background: rgba(212,235,254,.1);
    border: 1px solid rgba(61,85,150,.1);
    p{
      margin-left: 20px;
      font-size: 14px;
      font-family: "SourceHanSansCN";
      font-weight: 500;
      color: #212121;
      border-left: 3px solid #3D5596;
      padding-left: 8px;
    }
    .input_item{
      width: 319px !important;
    }
    .tab{
      margin: 0 30px 20px;
    }
  }
  ::v-deep .has-gutter{
     .el-table-column--selection{
      .cell{
        text-align: center;
      }
    }
  }
  ::v-deep .el-table__row{
     .el-table-column--selection{
      .cell{
        text-align: center;
      }
    }
  }
.el-radio {
  ::v-deep .el-radio__input {
    width: 16px;
    height: 16px;

    .el-radio__inner {
      border: 1px solid #BDBDBD;
    }
  }
  ::v-deep .el-radio__label {
    font-size: 13px;
    color: #212121;
    padding-left: 5px;
    font-family: 'SourceHanSansCN';
  }
  ::v-deep .el-radio__input.is-disabled.is-checked  .el-radio__inner {
    background-color: #C4CCE0;
    border: 1px solid #C4CCE0;
  }
  ::v-deep .el-radio__input.is-disabled + span.el-radio__label {
    color: #707070;
  }
  ::v-deep.el-radio__input.is-disabled.is-checked .el-radio__inner::after {
    background-color: #FFFFFF
  }
  ::v-deep .el-radio__input.is-checked .el-radio__inner {
    border: 1px solid #3D5298;
    background: #3D5298;
  }
}
</style>
