<template>
  <div>
    <div class="titleBox">
      <div class="title">用户管理</div>
      <div class="btnBox">
        <el-button type="primary" @click="addUserHander">
          <el-icon>
            <CirclePlus />
          </el-icon>
          <span>新增</span>
        </el-button>
      </div>
    </div>
    <div class="searchBox" ref="searchBox">
      <el-form :model="listQuery" class="mosty-from-wrap" :inline="true">
        <el-form-item label="用户名">
          <el-input placeholder="请输入用户名" v-model="listQuery.loginName" clearable></el-input>
        </el-form-item>
        <el-form-item label="移动电话">
          <el-input placeholder="请输入移动电话" v-model="listQuery.phone" clearable></el-input>
        </el-form-item>

        <el-form-item label="身份证号">
          <el-input placeholder="请输入身份证号" v-model="listQuery.idEntityCard" clearable></el-input>
        </el-form-item>
        <el-form-item label="警号">
          <el-input placeholder="请输入警号" v-model="listQuery.inDustRialId" clearable></el-input>
        </el-form-item>
        <el-form-item label="是否包含下级">
          <el-select v-model="listQuery.isChild">
            <el-option v-for="item in D_BZ_SF" :key="item" :label="item.label" :value="item.value">{{ item.label
              }}</el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="handleFilter">查询</el-button>
          <el-button @click="reset()"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-box" style="background: #fff">
      <div class="treeBox" :style="{ height: treeHeight }" >
        <MOSTY.DepartmentTree width="280px" placeholder="管理部门ID" clearable filterable :isBmId="true"
          v-model="listQuery.deptId" />
      </div>
      <div class="tabBox">
        <el-table :data="tableData" border style="width: 100%" :height="tableHeight" :key="keyCount">
          <el-table-column sortable prop="userName" align="center" label="用户名"></el-table-column>
          <el-table-column sortable prop="idEntityCard" align="center" label="身份证号"></el-table-column>
          <el-table-column sortable prop="deptName" label="部门"></el-table-column>
          <el-table-column sortable prop="inDustRialId" align="center" label="警号">
          </el-table-column>
          <el-table-column sortable prop="mobile" align="center" label="电话号码"></el-table-column>
          <el-table-column align="center" sortable label="性别" width="80">
            <template #default="{ row }">
              <dict-tag :options="D_BZ_XB" :value="row.sex" :tag="false" />
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" fixed="right" width="250">
            <template #default="{ row }">
              <el-button @click="updateDict(row)" size="small">编辑</el-button>
              <el-dropdown style="margin-left: 12px; margin-right: 12px" @command="dropdownAction">
                <el-button style="" size="small" @click="handleClick">
                  更多<el-icon class="el-icon--right">
                    <arrow-down />
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="commandValue('assignRoles', row)">分配角色</el-dropdown-item>
                    <el-dropdown-item :command="commandValue('restPwd', row)">重置密码</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                @confirm="delRole(row)">
                <template #reference>
                  <el-button type="danger" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="fenye" :style="{ top: tableHeight + 'px' }">
          <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="listQuery.page" :page-sizes="[10, 20, 50, 100]" :page-size="listQuery.size"
            layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
        </div>
      </div>
    </div>
    <div v-if="dialogFormVisible" class="dialog">
      <div class="head_box">
        <span class="title">{{ isEdit ? "修改" : "新增" }}</span>
        <div>
          <!-- 修改 -->
          <el-button v-if="isEdit" type="primary" size="small" @click="onSave" :loading="buttonLoading">修改</el-button>
          <!-- 新增 -->
          <el-button v-else type="primary" size="small" @click="onAdd">保存</el-button>
          <el-button size="small" @click="closeDialog">关闭</el-button>
        </div>
      </div>
      <el-form class="mosty-from-wrap" ref="elform" :model="dialogForm" :inline="true" label-position="top"
        :rules="rules">
        <el-form-item label="部门:" prop="ssbmdm">
          <MOSTY.Department :placeholder="dialogForm.ssbm" width="280px" clearable filterable
            v-model="dialogForm.ssbmdm" />
        </el-form-item>
        <el-form-item label="用户昵称:" prop="userName">
          <MOSTY.Other width="280px" placeholder="请输入用户昵称" clearable v-model="dialogForm.userName" />
        </el-form-item>
        <el-form-item label="登录账号:" prop="loginName">
          <MOSTY.Other width="280px" placeholder="请输入登录账号" clearable v-model="dialogForm.loginName" />
        </el-form-item>
        <el-form-item label="密码:" v-if="!isEdit" prop="password">
          <MOSTY.Other width="280px" placeholder="请输入密码" show-password v-model="dialogForm.password" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idEntityCard">
          <MOSTY.IdentityCard width="280px" v-model="dialogForm.idEntityCard" @change="fn" clearable>
          </MOSTY.IdentityCard>
        </el-form-item>
        <el-form-item label="警号" prop="inDustRialId">
          <MOSTY.Other width="280px" placeholder="请输入警号" v-model="dialogForm.inDustRialId" />
        </el-form-item>
        <el-form-item label="岗位选择">
          <MOSTY.StationSelect width="300px" clearable filterable v-model="dialogForm.positionId" />
        </el-form-item>

        <el-form-item label="用户类型:" prop="userType">
          <el-select style="width: 100%" v-model="dialogForm.userType" placeholder="请选择用户类型">
            <el-option v-for="dict in D_BZ_YHLX" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="虚拟用户:" prop="isVirtualUser">
          <el-select style="width: 100%" v-model="dialogForm.isVirtualUser" placeholder="请选择">
            <el-option v-for="dict in D_BZ_XNYH" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="电话号码:" prop="telePhone">
          <MOSTY.Phone width="280px" v-model="dialogForm.telePhone" maxlength="11" clearable></MOSTY.Phone>
        </el-form-item>
        <el-form-item label="移动电话:" prop="mobile">
          <MOSTY.Phone width="280px" v-model="dialogForm.mobile" maxlength="11" clearable></MOSTY.Phone>
        </el-form-item>
        <el-form-item label="民族:" prop="nation">
          <MOSTY.PackageSelect width="280px" v-model="dialogForm.nation" dictEnum="NATION" clearable filterable />
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-select style="width: 100%" v-model="dialogForm.sex" placeholder="请选择性别">
            <el-option v-for="(item, index) in D_BZ_XB" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文化程度:" prop="whcd">
          <MOSTY.PackageSelect dictEnum="EDUCATION" width="280px" v-model="dialogForm.whcd" clearable filterable />
        </el-form-item>
        <el-form-item label="E-mail" prop="email">
          <MOSTY.Email v-model="dialogForm.email" width="280px" clearable></MOSTY.Email>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker style="width: 100%" v-model="dialogForm.birthday" type="date" placeholder="出生日期"
            format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="所属模块:" prop="politic">
          <el-select style="width: 100%" v-model="dialogForm.politic" placeholder="请选择">
            <el-option v-for="dict in D_BZ_ZZMM" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="婚姻状况:" prop="marital">
          <el-select style="width: 100%" v-model="dialogForm.marital" placeholder="请选择婚姻状况">
            <el-option v-for="dict in D_BZ_HYZK" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="人员类别:" prop="type">
          <el-select style="width: 100%" v-model="dialogForm.type" placeholder="请选择人员类别">
            <el-option v-for="dict in D_BZ_RYLB" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期:" prop="endTime">
          <el-date-picker style="width: 100%" v-model="dialogForm.endTime" type="datetime" placeholder="请选择有效期"
            format="YYYY/MM/DD hh:mm:ss" value-format="x" />
        </el-form-item>

        <el-form-item label="是否融合">
          <el-select style="width: 100%" v-model="dialogForm.sfrh" placeholder="请选择">
            <el-option v-for="dict in D_BZ_SF" :label="dict.label" :value="dict.value" :key="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item style="width: 100%" label="备注">
          <el-input v-model="dialogForm.bz" show-word-limit maxlength="200" :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <RolesDialog v-model="roleDialogVisible" :userId="currentUserId" @updateRole="handleFilter"></RolesDialog>
  </div>
</template>

<script setup>
import * as rule from "@/utils/rules.js";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import {
  ref,
  reactive,
  computed,
  watch,
  onMounted,
  getCurrentInstance,
  onUnmounted
} from "vue";
import RolesDialog from "./components/roles.vue";
import {
  getSysUserList,
  editSysUser,
  addUser,
  getUserInfoToId,
  resetPassword,
  deleteSysUser,
  selectDeptPage,
  getUserRoleList
} from "@/api/user-manage";
const { proxy } = getCurrentInstance();
const {
  D_BZ_XB,
  D_BZ_YHLX,
  D_BZ_XNYH,
  D_BZ_RYLB,
  D_BZ_SF,
  D_BZ_HYZK,
  D_BZ_ZZMM
} = proxy.$dict(
  "D_BZ_XB",
  "D_BZ_YHLX",
  "D_BZ_XNYH",
  "D_BZ_RYLB",
  "D_BZ_SF",
  "D_BZ_HYZK",
  "D_BZ_ZZMM"
);
const searchBox = ref(null); // 搜索盒子
const keyCount = ref(0); //tabel组件刷新值
const tableHeight = ref(); // 表格高度
const treeHeight = ref(""); // 树高度
const rules = ref({
  // ...rule.phoneRule({ validator: true }, "mobile"), // 是否必填 是否进行校验
  // ...rule.phoneRule({ validator: true }, "telePhone"), // 是否必填 是否进行校验 如果props与from里面数据不一致，可以传第二个参数
  // ...rule.identityCardRule({ validator: true }), //身份证校验
  // ...rule.addressSelectRule({ require: true }), //地址
  // ...rule.emailRule({ validator: true }), //邮箱
  userName: [{ required: true, message: "请填写用户昵称" }],
  loginName: [{ required: true, message: "请填写登录账号" }],
  password: [{ required: true, message: "请填写密码" }],
  // nation: [{ required: true, message: "请选择民族" }],
  // sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  // whcd: [{ required: true, message: "请选择文化程度" }],
  // birthday: [{ required: true, message: "请选择出生日期" }],
  ssbmdm: [{ required: true, message: "请选择部门" }],
  inDustRialId: [{ required: true, message: "请填写警号" }],
  managerOrgId: [{ required: true, message: "请选择岗位" }],
  positionId: [{ required: true, message: " " }],
  userType: [{ required: true, message: "请选择用户类型" }],
  isVirtualUser: [{ required: true, message: "请选择虚拟用户" }],
  idEntityCard: [{ required: true, message: "请输入身份证号码" }],
  packageSelect: [
    {
      required: true,
      message: "请选择",
      trigger: "change"
    }
  ],
  other: [
    {
      required: true,
      message: "自由发挥哦",
      trigger: "blur"
    }
  ]
});
const elform = ref(null);
const buttonLoading = ref(false);
//查询参数
const total = ref(0);
const page = ref(1);
const size = ref(20);
const currentRow = ref({});
const listQuery = ref({
  page: 1,
  size: 20,
  loginName: "",
  phone: ""
});
const isEdit = ref(true);
const dialogForm = ref({
  userName: ""
});
// 数据相关
const tableData = ref([]);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
// 获取数据的方法
const getListData = async () => {
  const params = listQuery.value;
  params.current = params.page;
  const res = await getSysUserList(params);
  tableData.value = res?.records;
  total.value = Number(res.total);
};
getListData();
const reset = () => {
  listQuery.value = {
    page: 1,
    size: 20,
    loginName: "",
    phone: ""
  };
  getListData();
};
const handleFilter = () => {
  listQuery.value.page = 1;
  getListData();
};
const handleSizeChange = (currentSize) => {
  listQuery.value.size = currentSize;
  getListData();
};

const handleCurrentChange = (currentPage) => {
  listQuery.value.page = currentPage;
  getListData();
};

/**修改字典 */
const updateDict = async (row) => {
  getUserInfoToId(row.id).then((res) => {
    dialogForm.value = { ...res };
    dialogForm.value.nation = "" + res.nation;
    dialogForm.value.isVirtualUser = "" + res.isVirtualUser;
    isEdit.value = true;
    dialogFormVisible.value = true;
  });
};
//身份证号计算出生日期
function getBirthdayFromIdCard(idCard) {
  var birthday = "";
  if (idCard != null && idCard != "") {
    if (idCard.length == 15) {
      birthday = "19" + idCard.substr(6, 6);
    } else if (idCard.length == 18) {
      birthday = idCard.substr(6, 8);
    }

    birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
  }
  return birthday;
}
function fn(e) {
  let text = 0;
  if (e.length >= 17) {
    dialogForm.value.birthday = getBirthdayFromIdCard(e);
    text = e[e.length - 2] * 1;
    if (text % 2 === 0) {
      dialogForm.value.sex = "2";
    } else {
      dialogForm.value.sex = "1";
    }
  }
}

const commandValue = (type, command) => {
  return {
    type: type,
    command: command
  };
};
const dropdownAction = (item) => {
  const { type, command } = item;
  if (type === "assignRoles") {
    assignRoles(command);
  } else if (type === "restPwd") {
    restPwd(command);
  }
};

const addUserHander = (row) => {
  isEdit.value = false;
  dialogForm.value = {};
  dialogFormVisible.value = true;
};
const onSave = () => {
  elform.value.validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      dialogForm.value.positionName = "";
      editSysUser({
        ...dialogForm.value
      })
        .then((res) => {
          dialogFormVisible.value = false;
          ElMessage.success("修改成功");
          buttonLoading.value = false;
          handleFilter();
        })
        .finally(() => {
          buttonLoading.value = false;
        });
    } else {
      ElMessage.error("请填写完必填项!");
      return false;
    }
  });
};
//新增人员
const onAdd = () => {
  elform.value.validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      addUser({
        ...dialogForm.value
      })
        .then((res) => {
          dialogFormVisible.value = false;
          ElMessage.success("新增成功");
          buttonLoading.value = false;
          handleFilter();
        })
        .finally(() => {
          buttonLoading.value = false;
        });
    } else {
      ElMessage.error("请填写完必填项!");
      return false;
    }
  });
};

const delRole = (row) => {
  deleteSysUser({
    id: Number(row.id)
  }).then((res) => {
    ElMessage.success("删除成功");
    handleFilter();
  });
};

const closeDialog = () => {
  dialogForm.value = {};
  dialogFormVisible.value = false;
};

const moreAction = (e, item) => { };

//分配角色
const currentUserId = ref("");
const roleDialogVisible = ref(false);
const assignRoles = (row) => {
  roleDialogVisible.value = true;
  currentUserId.value = row.id;
};

const restPwd = (row) => {
  resetPassword({ userId: row.id }).then((res) => {
    dialogFormVisible.value = false;
    ElMessage.success("操作成功");
    handleFilter();
  });
};
const handleClick = (e) => { };

//watch监听路由变化
watch(roleDialogVisible, (val) => {
  if (!val) currentUserId.value = "";
});

watch(
  () => listQuery.value.deptId,
  () => {
    handleFilter();
  },
  {
    immediate: true
  }
);
// 表格高度计算
const tabHeightFn = () => {
  tableHeight.value =
    window.innerHeight - searchBox.value.offsetHeight - 250;
};
// 树高度计算
const treeHeightFn = () => {
  treeHeight.value = window.innerHeight - searchBox.value.offsetHeight - 213 + "px";
};
onMounted(() => {
  tabHeightFn();
  treeHeightFn();
  window.onresize = function () {
    treeHeightFn();
    tabHeightFn();
  };
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";
// .user-list-page {
//   .userListDialog {
//     .el-input__inner {
//       min-width: 260px;
//     }
//   }

//   .table-header-wrap {
//     margin-bottom: 22px;
//   }

//   ::v-deep .avatar {
//     width: 60px;
//     height: 60px;
//     border-radius: 50%;
//   }

//   ::v-deep .el-tag {
//     margin-right: 6px;
//   }

//   .pagination {
//     margin-top: 20px;
//   }

//   .twoLine {
//     display: flex;
//     align-items: flex-start;
//     flex-flow: wrap;

//     .el-form-item {
//       width: 380px;
//     }
//   }
// }</style>
