<template>
  <com-head :options="headList" >
    <el-form label-width="84px" inline="true">
      <el-form-item label="所属架构：">
        <com-company :checkStrictly="true" v-model="search.state.departmentId" />
      </el-form-item>
      <el-form-item label="用户账户：">
        <el-input v-model="search.state.userName" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="用户姓名：">
        <el-input v-model="search.state.nickName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select v-model="search.state.status" placeholder="全部">
          <el-option label="全部" :value="''"></el-option>
          <el-option label="可用" :value="1"></el-option>
          <el-option label="禁用" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="searh-btns">
        <el-button type="primary" @click="search.submit">查询</el-button>
        <el-button type="primary" plain @click="search.reset">重置</el-button>
      </el-form-item>
    </el-form>
  </com-head>

  <div class="body-layer" style="padding-top: 8px">
    <div class="body-head">
      <!-- <h3 style="visibility: hidden;">用户列表</h3> -->
    </div>

    <el-table
      class="user-table"
      ref="multipleTable"
      :data="dataList.state"
      tooltip-effect="dark"
      style="width: 100%"
      @row-click="selectRow"
    >
      <el-table-column label="序号" width="55" v-slot:default="{ $index }">
        <div style="text-align: center">{{ pag.state.size * (pag.state.currPage - 1) + $index + 1 }}</div>
      </el-table-column>
      <el-table-column label="手机号（账号）" prop="userName"></el-table-column>
      <el-table-column label="用户姓名" prop="nickName"></el-table-column>
      <el-table-column label="所属架构" prop="departmentName"></el-table-column>
      <el-table-column label="角色" prop="roleName"></el-table-column>
      <el-table-column label="状态" v-slot:default="{ row }">
        {{row.status ? '可用': '禁用'}}
      </el-table-column>
      <el-table-column label="操作" v-slot:default="{ row }" v-if="auth.update || auth.updatePwd || auth.delete">
        <template v-if="row.id !== ADMIN_USER_ID && row.id !== user.info.id">
          <span class="oper-span" @click="updateInfo(row)" v-if="auth.update">修改</span>
          <span class="oper-span" @click="changeUserStatus(row)" v-if="auth.delete" style="color: var(--primaryColor)">
            {{ row.status ? '禁用' : '启用' }}
          </span>
          <span class="oper-span" @click="detailInfo(row)" v-if="auth.update" style="color: var(--primaryColor)">删除</span>
        </template>
      </el-table-column>
    </el-table>
    <com-pagination
      @size-change="pag.sizeChange"
      @current-change="pag.currentChange"
      :current-page="pag.state.currPage"
      :page-size="pag.state.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pag.state.total"/>
  </div>
  

  <com-dialog
    :title="(operRoleId ? '修改架构' : '启用')"
    v-model:show="oper.state.show"
    @submit="operItem"
    width="540"
  >
    <el-form ref="form" :model="form" label-width="90px" class="user-from">
      <el-form-item label="用户姓名：" class="roleName">
        <el-input ref="groupName" v-model="oper.state.nickName" :maxlength="usermaxlength" @input="changeValue"  placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="所属架构：" class="mandatory"  v-show="operRoleId">
        <com-company v-model="oper.state.departmentId" @update:data="({level}) => (oper.state.roleId = level)" style="width: 100%" hideAll />
      </el-form-item>
      <el-form-item label="角色：" class="roleName">
        <com-role v-model="oper.state.roleId" style="width: 100%" allText="请选择" hideAll :notDefault="true" :disabled="true" />
      </el-form-item>
      <el-form-item v-if="!operRoleId">
        <p class="maker">注：首次启用，需设置用户角色；用户被启用后，可正常登录使用。</p>
      </el-form-item>
    </el-form>
  </com-dialog>
  
</template>


<script>
import { ref } from "vue";
import getTableState from "@/state/tableRef";
import comDialog from "@/components/dialog";
import comHead from "@/components/head";
import comCompany from "@/components/company-select";
import comPagination from "@/components/pagination";
import roleCompany from "@/components/role-select";
import auth from "@/state/viewAuth";
import user from "@/state/user";
import axios from 'axios'
import {encryption} from '@/util'
import {PSW, PHONE} from '@/constant/REG'
import {ADMIN_USER_ID} from "@/constant";

import {
  getUserList,
  updateUser,
  changeUserStatus,
  remove
} from '@/request/config'
import { getApp } from '../../app';


export default {
  name: 'user',
  setup() {
    const state = getTableState({
      getUrl: getUserList,
      updateUrl: updateUser,
      operAttr: {
        nickName: "",
        userName: "",
        departmentId: "",
        password: '',
        confirmPwd: '',
        roleId: "",
        maxlevel: 1,
      },
      searchAttr: { nickName: "", status: '', departmentId: '',userName: '' },
    });
    const headList = ref([{ name: "用户管理", value: 2 }]);
    const operRoleId = ref('')
    const usermaxlength = ref(30)
    const updateInfo = (row) => {

      if (!row.status) {
        return getApp().$message.error('请先启用用户', '提示')
      }
      operRoleId.value = row.roleId
      state.oper.value.readyUpdate(row)
    }
    
    console.log(user)
    return { ...state, headList, updateInfo, auth, user, operRoleId, ADMIN_USER_ID,usermaxlength };
  },
  methods: {
    changeValue () {
        let leng = this.validateTextLength(this.oper.state.nickName)
        if (leng >= 15) {
          this.usermaxlength = leng
        } else {
          this.usermaxlength = 30
        }
      },
    validateTextLength (value) {
        // 中文、中文标点、全角字符按1长度，英文、英文符号、数字按0.5长度计算
        let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g
        let mat = value.match(cnReg)
        let length
        if (mat) {
          length = (mat.length + (value.length - mat.length) * 0.5)
          return length
        } else {
          return value.length * 0.5
        }
    },
    async operItem() {
      const updatePhone = this.oper.state.__oldData ? this.oper.state.__oldData.userName !== this.oper.state.userName : true
      
      if (updatePhone && !PHONE.REG.test(this.oper.state.userName)) {
        return this.$message.error(PHONE.tip, '提示')
      }
      if (this.oper.state.password !== this.oper.state.confirmPwd) {
        return this.$message.error('两次密码不一致！', '提示')
      }

      if (!this.oper.state.roleId) {
        return this.$message.error('请选择用户角色', '提示')
      }

      if (!this.operRoleId && !(await this.$confirm('用户被启用后，可正常登录使用。确定要启用吗？', '提示'))) {
        return;
      }

      if (this.oper.state.id) {
        let updateState = {...this.oper.state, password: void 0, confirmPwd: void 0, updatePwd: void 0, userId: this.oper.state.id}
        if (!updatePhone) {
          delete updateState.userName
        }
        let state = {...this.oper.state}
        await this.oper.update(updateState)
        await this.changeUserStatus(state, true)
      } else if (this.oper.state.password === this.oper.state.confirmPwd) {
        if (PSW.REG.test(this.oper.state.password)) {
          let cryPsw = encryption(this.oper.state.password)
          this.oper.insert({
            ...this.oper.state,
            password: cryPsw,  
            confirmPwd: cryPsw,  
            updatePwd: void 0
          })
        } else {
          this.$message.error(PSW.tip, '提示')
        }
      }

    },
    async changeUserStatus (row, d) {
      if (!d && (!row.roleId && !row.status)) {
        this.operRoleId = row.roleId
        return this.oper.readyUpdate(row)
      }
      let msg = row.status ? `用户被禁用后，无法登录使用。确定要禁用吗？` : `用户被启用后，可正常登录使用。确定要启用吗？`
      try {
        if (d || (await this.$confirm(msg, '提示'))) {
          await axios.post(changeUserStatus, {status: Number(!row.status), userId: row.id})
          this.dataList.refer()
        }
        return true
      } catch {
        return false
      }
    },
    async detailInfo (row){
      let msg = `用户被删除后，无法登录使用。 确定要删除吗？`
      try {
        if (await this.$confirm(msg, '提示')) {
          await axios.get(remove+row.id,{id:row.id})
          this.dataList.refer()
        }
        return true
      } catch {
        return false
      }
    }
  },
  components: {
    "com-dialog": comDialog,
    "com-head": comHead,
    "com-company": comCompany,
    "com-role": roleCompany,
    "com-pagination": comPagination
  },
};

</script>

<style lang="scss" scoped>
.table-ctrl-right {
  .search-scene {
    margin: 0 20px 0 26px;
  }
  i {
    margin-left: 20px;
    font-size: 1.7rem;
    vertical-align: middle;
    cursor: pointer;

    &.active {
      color: var(--primaryColor);
    }
  }
}

.user-from {
  // width: 380px;
  margin: 0 auto;
}

.tip {
  position: fixed;
  left: 50%;
  top: 50%;
  z-index: 999;

  &::before {
    content: '密码重置为Fcb20210225，可登录修改';
    position: absolute;
    width: 205px;
    left: 50%;
    transform: translateX(-50%);
    bottom: 100%;
    border-radius: 4px;
    padding: 10px;
    z-index: 2000;
    font-size: 12px;
    line-height: 1.2;
    min-width: 10px;
    word-wrap: break-word;
    background: #303133;
    color: #fff;
    margin-bottom: 6px;
    
  }

  &::after {
    content: '';
    position: absolute;
    display: block;
    width: 0;
    height: 0;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%);
    border-color: transparent;
    border-style: solid;
    border-width: 6px;
    border-top-color: #303133;
    border-bottom-width: 0;
  }
}

.maker {
  font-weight: 400;
  color: #969799;
  line-height: 20px;
}

</style>

<style>
.user-table.el-table .cell {
  overflow: inherit;
}
</style>
