<template>
  <div>
    <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-but">
          <el-button type="primary" @click="newAddclick">新增用户</el-button>
        <!-- <h3 style="visibility: hidden;">用户列表</h3> -->
      </div>

      <el-table
        class="user-table"
        ref="multipleTable"
        :data="dataList.state"
        tooltip-effect="dark"
        style="width: 100%;max-height:480px"
        @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"  v-if="auth.update"-->
           <!-- row.roleKey == roleKey[user.roleKey] -->
          <template v-if="user.roleKey !== 'admin-ordinary'">
            <span class="oper-span" @click="updateInfo(row)" 
            v-power="'edit'">编辑</span
            >
              <!-- v-if="auth.delete" -->
            <span
              class="oper-span"
              v-power="'disabled'"
              @click="changeUserStatus(row)"
              style="color: var(--primaryColor)"
            >
              {{ row.status ? "禁用" : "启用" }}
            </span>
            
            <span class="oper-span" style="color: var(--primaryColor)" @click="delInfo(row)"  v-power="'del'">删除</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="编辑用户"
      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="mandatory" >
          <el-input
            v-model.trim="editName"
            placeholder="请输入"
            maxlength="30"
          ></el-input>
        </el-form-item>
      </el-form>
    </com-dialog>

    <com-dialog
      title="新增用户"
      @quit="newData = {};deptIdList=[]"
      v-model:show="newShow"
      @submit="newSubmit"
      width="540"
    >
      <el-form ref="form" :model="form" label-width="90px" class="user-from">
        <el-form-item label="用户姓名" class="mandatory" >
          <el-input
            maxlength="30"
            v-model="newData.nickName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属架构："  v-if="user.roleKey !== 'admin-ordinary'">
          <el-cascader
            style="width: 100%"
            v-model="deptIdList"
            @change="changeDeptId"
            :options="treedata"
            :props="{ checkStrictly: true, label: 'name', value: 'id' }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="用户角色" class="roleName mandatory">
         <com-role v-model="newData.roleId" style="width: 100%" allText="请选择" hideAll :notDefault="true" />
        </el-form-item>
        <el-form-item label="用户账号" class="mandatory">
          <el-input
            v-model.trim="newData.userName"
            placeholder="请输入11位手机号码作为用户账号"
          ></el-input>
        </el-form-item>
        <el-form-item label="登录密码" class="mandatory">
          <el-input
            v-model="newData.psw"
            placeholder="请输入8-16位数字、英文大小写组合密码"
            :type="flag?'password':'text'"
          >
            <template v-slot:suffix>
              <img v-if="flag" @click="flag = !flag" style="width:20px; margin: 10px;" src="@/assets/image/pasword.png" alt="">
              <i  v-else class="icon-style el-icon-view" style="font-size:20px;margin: 10px;" size="20"  @click="flag = !flag"></i>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </com-dialog>
  </div>
</template>


<script>
import { reactive, ref, toRefs,onMounted } 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 comSelect from "@/components/company-select";
import auth from "@/state/viewAuth";
import user from "@/state/user";
import axios from "axios";
// import { encryption } from "@/util";
import {PHONE,EPSW} from '@/constant/REG'
import { ADMIN_USER_ID } from "@/constant";

import { getTreeselect,getUserList, updateUser, deleUser, changeUserStatus,userAdd,userEdit } from "@/request/config";
import { getApp } from "../../app";

export default {
  name: "user",
  setup() {
    const flag = ref(true)
    const state = getTableState({
      getUrl: getUserList,
      updateUrl: updateUser,
      operAttr: {
        nickName: "",
        userName: "",
        deptId: "",
        password: "",
        confirmPwd: "",
        roleId: "",
        maxlevel: 1,
      },
      searchAttr: { nickName: "", status: "", deptId: "" },
    });
    const headList = ref([{ name: "用户管理", value: 2 }]);
    const roleKey = ref({ 'admin': "admin-dept", 'admin-dept': 'admin-ordinary' });
    const operRoleId = ref("");
    const updateInfo = (row) => {
      if (!row.status) {
        return getApp().$message.error("请先启用用户", "提示");
      }
      data.editName = row.nickName
      operRoleId.value = row.roleId;
      state.oper.value.readyUpdate(row);
    };
    const delInfo =  async (row) => {
      let isOk = await getApp().$confirm('用户被删除后，无法登陆使用，无法编辑场景（可将该用户关联的相机绑定到其他管理员），确认要删除组织吗？', '删除')
      if (isOk) {
        await axios.post(deleUser, { id:row.id, });
        getApp().$message({message: '操作成功', type: 'success'});
        state.search.value.submit();
      }
    }
    const getTreedata = async () => {
      let res = await axios.get(getTreeselect, {});
      data.treedata = res.data;
      console.log('data.treedata',data.treedata);
      // getApp().$ref.treeBox.setCurrentKey(user.info.id)
    };
    const newAddclick = () =>{
      data.newShow = true
    }
    const data = reactive({
      newShow: false,
      editName:'',//修改编辑用户名称
      deptIdList:[],
      treedata:[],
      newData:{
        userName: "",
        userId: "",
        password: "",
        userRole: "",
      }
    });
    onMounted(async () => {
      getTreedata();
    });
    return {
      ...state,
      ...toRefs(data),
      flag,
      getTreedata,
      headList,
      delInfo,
      updateInfo,
      auth,
      user,
      operRoleId,
      ADMIN_USER_ID,
      roleKey,
      newAddclick
    };
  },
  methods: {
    changeDeptId(val){
      this.newData.deptId = val && val[val.length - 1];
    },
    async newSubmit(){
      console.log('newSubmit',this.user,this.newData);
      if (!this.newData.nickName) {
        return this.$message.error("请输入用户姓名", "提示");
      }
      if (!this.newData.roleId) {
        return this.$message.error("请选择用户角色", "提示");
      }
      console.log(PHONE.REG.test(this.newData.userName),this.newData.userName)
      if (!this.newData.userName) {
        return this.$message.error("请选择用户账户", "提示");
      }else if(!PHONE.REG.test(this.newData.userName)){
        return this.$message.error(PHONE.tip, "提示");
      }
      if (!this.newData.psw) {
        return this.$message.error("请输入登录密码", "提示");
      }else if(!EPSW.REG.test(this.newData.psw)){
        return this.$message.error(EPSW.tip, "提示");
      }
      let apiinfo = await axios.post(userAdd, {
        nickName:this.newData.nickName,
        password:this.newData.psw,
        userName:this.newData.userName,
        roleId:this.newData.roleId,
        deptId:this.newData.deptId
            // ...this.newData
      });
      this.$message({message: apiinfo.msg || '成功', type: 'success'});
      // await this.$confirm('每个组织只能创建一个总管理员~', '新增用户')
      this.newData = {}
      this.deptIdList = []
      this.newShow = false
      this.dataList.refer();
    },
    async operItem() {
      if (!this.editName) {
        return this.$message.error("请输入用户名称", "提示");
      }
      console.log('state.oper',this.oper);
      await axios.post(userEdit, {
          id:this.oper.state.id,
          nickName:this.editName,
      });
      this.$message({message: '编辑成功', type: 'success'});
      this.oper.reset();
      this.editName = ''
      this.dataList.refer();
    },
    async changeUserStatus(row, d) {
      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;
      }
    },
  },
  components: {
    "com-dialog": comDialog,
    "com-head": comHead,
    "com-company": comCompany,
    "com-role": roleCompany,
    "com-pagination": comPagination,
    // "com-select": comSelect
  },
};
</script>

<style lang="scss" scoped>
.body-layer{
  .body-but{
    text-align: right;
    margin-bottom: 15px;
  }
}
.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>
