<script lang="ts">
export default {
  name: "user",
};
</script>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import {
  getTreelist,
  gettableData,
  DataStatus,
  deltableData,
  getRole,
  addUsers,
  updataUser,
  setpass,
  delChoise,
  viewUserInfo,
  unlockUser
} from "@/api/user";
import { ElMessageBox, ElMessage } from "element-plus";
import { useAppStore } from '@/store/modules/app';
import Page from '@/components/Pagination/page.vue'
import Eldialog from '@/components/seccmsdialog/eldialog.vue';
import { encrypt, decrypt } from '@/utils/sm4';
// import { constant } from "lodash";
//左侧树形控件
interface Tree {
  [x: string]: any;
  label: string;
  children?: Tree[];
}
// 表格加载
const loading = ref(false);
// 搜索框
const queryParams = ref({
  current: 1,
  size: 10,
  querystr: '',
  status: ''
});
//分页 总条数
const total = ref()
const treedata: any = ref([]);
const dialog = ref(false)
const treeRef = ref();
const infoForm = ref();
//获取企业树形信息
const treeloading = ref(true)
function getTree() {
  const params = {
    parentid: "0",
  };
  getTreelist(params).then((res: any) => {
    treedata.value = res
    treeloading.value = false
    orgId.value = res[0].childList[0].id
    nextTick(() => {
      treeRef.value?.setCurrentKey(orgId.value);
    });
    getdata()
  })
    .catch((error: any) => {
      treeloading.value = false
    })

}
const currentNodeKey = ref("")
function handleNodeClick(data: Tree, node: any) {
  orgId.value = data.id;
  dialog.value = true
  getdata();
}


const defaultProps = {
  children: "childList",
  label: "orgname"
};

//新建
const dialogVisible = ref(false);
const title = ref("");
function addClick() {
  title.value = "新增用户";
  dialogVisible.value = true;
  info.value = {
    id: "",
    username: "",
    nickname: "",
    email: "",
    phone: "",
    roleinfo: "",
    pwdvalidperiod: 90,
    loginip: ""
  };
  getrole();
}
//用户列表
const multipleSelection: any = ref([]);
const tableData = ref([]);
const orgId = ref("");
//获取用户列表信息
function getdata() {
  const params = {
    current: queryParams.value.current,
    size: queryParams.value.size,
    orgid: orgId.value,
    username: queryParams.value.querystr,
    status: queryParams.value.status
  }
  loading.value = true;
  gettableData(params).then((res => {
    total.value = res.data.total
    tableData.value = res.data.records
    queryParams.value.size = res.data.size
    queryParams.value.current = res.data.current
    dialog.value = true
    loading.value = false;
  })).catch(() => {
    loading.value = false;
  })
}
function secureLock(row: any) {
  console.log(row.roleinfo)
  ElMessageBox.confirm("确定解除该用户的账号锁定吗？", "提示信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let params = {
        status: 1,
        failednum: 0,
        failedlocktime: dateFormat(new Date()),
        id: row.id,
      };

      unlockUser(params).then((res: any) => {
        if (res.code == '0') {
          getdata();
          ElMessage({
            type: "success",
            message: "解除锁定成功！",
          });
        }

      });
    })
    .catch(() => {
      getdata();
    });
}
//禁用启用
function switchChange(row: any) {
  const elmassage = ref('')
  if (row.status == '0') {
    elmassage.value = '确定停用该账号吗？'
  } else if (row.status == '1') {
    elmassage.value = '确定启用该账号吗？'
  }
  ElMessageBox.confirm(elmassage.value, "提示信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let status = 0
      if (row.status == 2) {
        status = 1
      } else {
        status = row.status
      }
      let params = {
        status: status,
        id: row.id,
      };
      DataStatus(params).then((res: any) => {
        if (res.code == '0') {
          getdata();
          ElMessage({
            type: "success",
            message: "改变成功",
          });
        }

      });
    })
    .catch(() => {
      getdata();
    });
}
//新建用户弹窗
const info: any = ref({
  id: "",
  username: "",
  nickname: "",
  email: "",
  phone: "",
  pwdvalidperiod: 90,
  loginip: "",
  roleinfo: "",
});
//修改-用户
function editdepartment(row: any) {
  const selectID: any = []
  row.roles.forEach((item: any) => {
    selectID.push(item.id)
  })
  info.value = JSON.parse(JSON.stringify(row));
  info.value.roleinfo = selectID.join(",");
  rolesdata.value = row.roles
  title.value = "修改用户";
  dialogVisible.value = true;




  getrole();
}
//用户弹窗-所属角色
const rolesdata: any = ref([]);
function validMail(value: any) {
  const reg = /^(([^<>()\]\\.,;:\s@"]+(\.[^<>()\]\\.,;:\s@"]+)*)|(".+"))@(([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  if (!reg.test(value)) {
    return '邮箱格式错误'
  } else {
    return true
  }
}
function phoneRules(value: any) {
  const phone = value.replace(/\s/g, "");
  let regs = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/;
  if (!regs.test(phone)) {
    return '手机号输入不合法';
  } else {
    return true;
  }
}
//用户弹窗-保存
function confirmClick(formEl: any) {

  formEl.validate((valid: any) => {
    if (valid) {
      if (info.value.id) {
        const params = {
          id: info.value.id,
          username: info.value.username,
          nickname: info.value.nickname,
          email: info.value.email,
          phone: info.value.phone,
          orgid: orgId.value,
          pwdvalidperiod: info.value.pwdvalidperiod,
          loginip: info.value.loginip
        };
        if (params.email) {
          if (params.email.indexOf('****') != -1) {
            delete params.email;
          }
        }
        if (params.phone.indexOf('****') != -1) {
          delete params.phone;
        }


        const roleids = String(info.value.roleinfo)
        updataUser(params, roleids).then((res: any) => {
          if (res.code == '0') {
            getdata();
            dialogVisible.value = false;
            ElMessage({
              type: "success",
              message: "修改成功",
            });
          }

        });
      } else {
        const params = {
          username: info.value.username,
          nickname: info.value.nickname,
          email: info.value.email,
          phone: info.value.phone,
          orgid: orgId.value,
          pwdvalidperiod: info.value.pwdvalidperiod,
          loginip: info.value.loginip

        };
        const roleids = info.value.roleinfo;
        addUsers(params, roleids).then((res: any) => {
          getdata();
          dialogVisible.value = false;
          ElMessage({
            type: 'success',
            message: res.data.msg,
          });
        });
      }
    }
  })
}
//用户弹窗规则定义
const moderules: any = ref({
  username: [{ required: true, message: "请输入用户账号", trigger: "blur" }, { validator: stringlength, trigger: 'blur' }],
  nickname: [{ required: true, message: "请输入用户名称", trigger: "blur" },
  { validator: stringlength, trigger: 'blur' }],
  pwdvalidperiod: [{ required: true, message: "请输入密码有效天数", trigger: "blur" }, { required: true, message: "请输入数字", type: "number" }],
  loginip: [{ pattern: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/, message: "请输入用户指定登录IP", trigger: "blur" }],
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  // phone: [{ required: true, pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
  // email: [{ pattern: /^(([^<>()\]\\.,;:\s@"]+(\.[^<>()\]\\.,;:\s@"]+)*)|(".+"))@(([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: '邮箱格式错误', trigger: 'blur' }],
  // loginip:[{}]
});
//区域名称长度
function stringlength(rule: any, value: any, callback: any) {
  if (value.length > 20) {
    return callback(new Error('字符最大长度不超过20'))
  }
  callback()
}
//弹窗关闭
function handleClose() {
  infoForm.value.resetFields();
  dialogVisible.value = false;
}

//重置密码
const userid = ref("");
function setpassword(row: any) {
  ElMessageBox.confirm(
    '确定将该账号密码重置为QAZ13579test@吗？',
    '重置密码',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const params = {
        id: userid.value
      }
      setpass(params).then((res: any) => {
        if (res.code == '0') {
          ElMessage({
            type: 'success',
            message: '密码重置成功',
          })
        }

      })
    })
  userid.value = row.id
}
//删除用户
function delclick(row: any) {
  ElMessageBox.confirm("确定删除此用户吗？", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const params = {
        id: row.id,
      };
      deltableData(params).then((res: any) => {
        if (res.code == '0') {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getdata();
        }

      });
    })
}
//获取角色
function getrole() {
  const params = {
    rolename: "",
  };
  getRole(params).then((res) => {
    rolesdata.value = res;
    rolesdata.value.forEach((row: any, index: any) => {
      if (row.isvaild == 0) {
        rolesdata.value.splice(index, 1)
      }
    })
  });
}
//表格多选样式
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  if (rowIndex % 2 === 0) {
    return 'warning-row'
  } else if (rowIndex % 2 === 1) {
    return 'success-row'
  }
  return ''
}
//多选删除
const ids = ref([])
function handleSelectionChange(val: any) {
  multipleSelection.value = val;
  ids.value = val
}




function delchoice() {
  const choice: any = []
  ids.value.forEach((item: any) => {
    choice.push(item.id)
  })
  ElMessageBox.confirm("确定删除此用户吗？", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const params = {
        id: String(choice)
      };
      delChoise(params).then((res: any) => {
        if (res.code == '0') {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getdata();
        }

      });
    })
}

function dateFormat(row: any) {
  const daterc = row;
  if (daterc != null) {
    var date = new Date(daterc);
    var year = date.getFullYear();
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    // 拼接
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  }
}

//分页

onMounted(() => {
  getTree();
});
const vMove = {
  mounted(el: any) {
    el.onmousedown = function (e: any) {
      var init = e.clientX;
      var parent: any = document.getElementById("silderLeft");
      const initWidth: any = parent.offsetWidth;
      document.onmousemove = function (e) {
        var end = e.clientX;
        var newWidth = end - init + initWidth;
        parent.style.width = newWidth + "px";
      };
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;
      };
    };
  }
}
const dataarr = ref([
  {
    name: '停用',
    id: 0
  },
  {
    name: '启用',
    id: 1
  }, {
    name: '锁定',
    id: 2
  },
])
//查看邮箱和手机号
const control = ref(false)
const inputTrue = ref(false)
const password = ref()
const Type = ref()
function inImg(type: any) {
  control.value = true
  Type.value = type
  password.value = ''
}
function secondPass() {
  viewUserInfo({ type: Type.value, id: info.value.id, password: encrypt(password.value) }).then((res: any) => {

    if (res.code == '0') {
      if (Type.value == 1) {
        info.value.email = res.data
      } else {
        info.value.phone = res.data
      }
      inputTrue.value = false
      control.value = false
    }
    if (res.msg == '密码输入错误') {
      inputTrue.value = true
    } else {
      inputTrue.value = false
    }
  })
}
function inputCLOse() {
  control.value = false
  inputTrue.value = false
}
</script>

<template>
  <div class="faulttemplate-box">
    <aside id="silderLeft">
      <el-tree ref="treeRef" :class="useAppStore().size === 'default' ? 'silderLeft-large' : 'silderLeft-default'"
        node-key="id" :data="treedata" :current-node-key="currentNodeKey" :highlight-current="true" :props="defaultProps"
        v-loading="treeloading" @node-click="handleNodeClick" style="height: calc(88vh); overflow: auto">
      </el-tree>
      <div class="moveBtn" v-move>
        <div class="moveBtn-line"></div>
      </div>
    </aside>
    <section class="silderRight">
      <el-row>
        <el-col :span="24">
          <div
            style="margin-bottom:10px;display: flex;display: -webkit-flex; justify-content: space-between;-webkit-justify-content: space-between; width: 100%;">
            <div>
              <el-input v-model="queryParams.querystr" placeholder="请输入登录账号" clearable style="width: 200px"
                @clear="getdata" @keyup.enter="getdata" />
              <el-select style="margin-left: 10px;" v-model="queryParams.status" placeholder="账号状态" @change="getdata"
                clearable>
                <el-option v-for="item in dataarr" :key="item.id" :label="item.name" :value="item.id">
                  <!-- <span v-if="item.isvaild == '0'" style="float: left">{{ item.rolenames }}</span> -->
                </el-option>
              </el-select>
              <el-button class="searchButton" type="primary" style="margin-left: 10px;" @click="getdata">搜索</el-button>
            </div>
            <div>
              <el-button class="searchButton" v-hasPerm="['add:user']" type="primary" @click="addClick">
                新增</el-button>
              <el-button class="searchButton" v-hasPerm="['del:user']" @click="delchoice"
                :disabled="multipleSelection.length <= 0"
                :type="multipleSelection.length > 0 ? 'primary' : ''">删除</el-button>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-table :data="tableData" style="width: 100%;margin-bottom: 20px;height: calc(78vh);
                    overflow: auto;" row-key="id" default-expand-all :v-loading="dialog"
        @selection-change="handleSelectionChange" :row-class-name="tableRowClassName"
        :header-cell-style="{ background: '#002b6a', color: '#B5D7FF', height: '50px'}">
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="nickname" label="用户姓名" width="100"></el-table-column>
        <!-- <el-table-column prop="avatar" label="头像"></el-table-column> -->
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="90"></el-table-column>
        <el-table-column prop="username" label="登录账号" width="120"></el-table-column>
        <!-- <el-table-column prop="custom1" label="登录账号"></el-table-column> -->
        <el-table-column prop="rolename" label="所属角色" width="120">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.roles" :key="index">{{ item.rolename }} <span></span> </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="账号状态" align="center" width="120">
          <template #default="scope">
            <el-switch v-if="scope.row.status == 2" v-model="scope.row.status" active-value="2" inactive-value="0"
              @change="switchChange(scope.row)" style="margin-right: 4px;"></el-switch>
            <el-switch v-else v-model="scope.row.status" active-value="1" inactive-value="0"
              @change="switchChange(scope.row)" style="margin-right: 4px;"></el-switch>
            <span v-if="scope.row.status == 1" class="effective">启用</span>
            <span v-else-if="scope.row.status == 2" class="effective">锁定</span>
            <span v-else style="color:#D7D7D7">停用</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastmodifier" label="最近修改者" width="120"></el-table-column>
        <el-table-column prop="lastmodifydate" label="最近修改日期" width="205">
          <template #default="scope">
            {{ dateFormat(scope.row.lastmodifydate) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <span
              style="display: flex;display: -webkit-flex;justify-content: space-around;-webkit-justify-content: space-around; ">
              <img src="@/assets/newimg/ht_xg.png" alt="" title="修改" @click="editdepartment(scope.row)"
                style="cursor: pointer;">
              <img src="@/assets/newimg/ht_czmm.png" alt="" title="重置密码" @click="setpassword(scope.row)"
                style="cursor: pointer;">
              <img v-if="scope.row.status == 2" src="@/assets/newimg/ht_jsyh.png" alt="" title="解除锁定"
                @click="secureLock(scope.row)" style="cursor: pointer;">
              <img v-else src="@/assets/newimg/ht_jsyh1.png" alt="" style="cursor: pointer;">
              <img v-hasPerm="['del:role']" src="@/assets/newimg/ht_sc.png" v-if="scope.row.status == 0" alt="" title="删除"
                @click="delclick(scope.row)" style="cursor: pointer;">
              <img v-hasPerm="['del:role']" v-if="scope.row.status == 1 || scope.row.status == 2"
                src="@/assets/newimg/ht_sc1.png" title="删除" @click="" style="cursor: pointer;">
            </span>
          </template>
        </el-table-column>
      </el-table>
      <Page :total="total" v-model:size="queryParams.size" v-model:current="queryParams.current" @pagination="getdata()">
      </Page>
    </section>
    <!-- 用户 弹框-->
    <Eldialog v-if="dialogVisible" :title="title" :zIndex="2000" :width="'620px'" :height="'600px'"
      @before-close="handleClose">
      <template v-slot:PopFrameContent>
        <el-form ref="infoForm" :model="info" :rules="moderules" label-width="140px" style="margin-top: 15px;">
          <el-form-item label="用户姓名" prop="nickname">
            <el-input v-model="info.nickname" style="width: 85%" placeholder="请输入用户姓名"></el-input>
          </el-form-item>
          <el-form-item label="联系邮箱" prop="email">

            <el-input v-model="info.email" style="width: 85%" placeholder="请输入联系邮箱" clearable>
              <template #append v-if="info.id && info.email"><img src="@/assets/newimg/xsjk_ckxq.png" alt="" title="查看邮箱"
                  @click="inImg(1)"></template>
            </el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">

            <el-input v-model="info.phone" style="width: 85%" placeholder="请输入联系电话" clearable>
              <template #append v-if="info.id && info.phone"><img src="@/assets/newimg/xsjk_ckxq.png" alt="" title="查看电话"
                  class="looknum" @click="inImg(2)"></template>
            </el-input>
          </el-form-item>
          <el-form-item label="登录账号" prop="username">
            <el-input v-model="info.username" style="width: 85%" placeholder="请输入登录账号"></el-input>
          </el-form-item>
          <el-form-item label="所属角色">
            <el-select v-model="info.roleinfo" placeholder=" " style="width: 85%">
              <el-option v-for="item in rolesdata" :key="item.id" :label="item.rolename" :value="item.id">
                <!-- <span v-if="item.isvaild == '0'" style="float: left">{{ item.rolenames }}</span> -->
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="密码有限期（天）" prop="pwdvalidperiod">
            <el-input v-model.number="info.pwdvalidperiod" style="width: 85%" placeholder=""></el-input>
          </el-form-item>
          <el-form-item label="用户指定登录IP" prop="loginip">
            <el-input v-model="info.loginip" style="width: 85%" placeholder=""></el-input>
          </el-form-item>

        </el-form>
        <span class="dialog-footer"
          style="display: flex;display: -webkit-flex; justify-content: center;-webkit-justify-content: center;margin: 10px 0px 5px 0px ;">
          <div class="details-button" @click="handleClose">取消</div>
          <div class="details-button" @click="confirmClick(infoForm)">确定</div>
        </span>
      </template>
    </Eldialog>
    <Eldialog v-if="control" :title="'二次密码验证'" :zIndex="2000" :width="'400px'" @before-close="inputCLOse">
      <template v-slot:PopFrameContent>
        <div style="width: 100%;display: flex;justify-content: center;">
          <el-input v-model="password" placeholder="请输入账号密码" style="margin-top:20px;width: 350px;" type="password"
            show-password />
        </div>
        <div style="height:19px">
          <div v-if="inputTrue" style="color:red;">密码错误，请重新输入</div>
        </div>
        <span class="dialog-footer"
          style="display: flex;display: -webkit-flex; justify-content: flex-end;-webkit-justify-content: flex-end;margin-top: 1px;">
          <div class="details-button" @click="inputCLOse">取消</div>
          <div class="details-button" @click="secondPass">确定</div>
        </span>
      </template>
    </Eldialog>
    <!-- <el-dialog v-model="dialogVisible" :close-on-click-modal="false" :before-close="handleClose" :title="title"
      append-to-body width="620px" draggable>
      
    </el-dialog> -->
  </div>
</template>

<style scoped lang="scss">
.looknum {
  cursor: pointer;
}

.silderLeft-default {
  :deep(.el-tree-node__label) {
    font-size: 16px !important;
  }
}

.faulttemplate-box {
  height: 100%;
  display: flex;
  display: -webkit-flex;
  background-color: #f2f4f900;
  padding: 15px 15px 0px 15px;

}

#silderLeft {
  width: 300px;
  padding: 5px 0px 10px;
  box-sizing: border-box;
  border-radius: 3px;
  position: relative;
  background: url(@/assets/navigation/ty_260x988.png);
  background-size: 100% 100%;

  &:hover {
    .moveBtn {
      opacity: 1;
    }
  }
}

/* 拖动条 */
.moveBtn {
  height: 100%;
  width: 15px;
  padding: 0 6px;
  opacity: 0;
  position: absolute;
  right: -15px;
  top: 0;
}

.moveBtn-line {
  width: 100%;
  height: 100%;
  cursor: col-resize;
  user-select: none;
  background-color: #60bfff;
}

.silderRight {
  flex: 1;
  width: 100%;
  height: calc(100vh - 160px);
  overflow: auto;
  background-color: rgba(255, 255, 255, 0);
  border-radius: 3px;
  padding: 15px;
  padding-bottom: 0px;
  box-sizing: border-box;
  margin-left: 15px;
  background: url(@/assets/newimg/cjrw_1890.png);
  background-size: 100% 100%;
}

.avatar {
  width: 86px;
  height: 86px;
  display: block;
}

:deep(.el-tree-node.is-current>.el-tree-node__content) {
  width: 100%;
  height: 40px;
  // color: #fff !important;
}

:deep(.el-tree) {
  background-color: #ffffff00 !important;
  --el-tree-node-hover-bg-color: #0099ff09;
}



:deep(.el-tree-node__content) {
  width: 100% !important;
  height: 40px !important;
  margin: auto !important;
}

.el-message-box {
  width: 300px !important;
}

:deep(.el-table:not(.el-table--border) .el-table__cell) {
  border: none;
  color: #fff;
}

:deep(.el-tree) {
  background-color: #ffffff00 !important;
  --el-tree-node-hover-bg-color: #0099ff09;
}

:deep(.el-input) {
  --el-input-bg-color: #ffffff00 !important;
}

:deep(.el-input-group__append) {
  background: #ffffff00 !important;
}
</style>


