<template>
  <div class="app-container">
    <el-card>
      <div class="cardbox">
        <div class="top">
          <div class="l">成员</div>
          <div class="r">
            <el-input
              style="width: 240px"
              placeholder="输入姓名/电话"
              :suffix-icon="Search"
              v-model="queryParams.userName"
              @clear="listSearch"
              @keydown="listSearch"
              clearable
            />
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
               @clear="listSearch"
               @change="listSearch"
               show-confirm="true"
              
            />
            <el-button
              type="primary"
              @click="handleAdd"
              :icon="CirclePlus"
              >添加成员</el-button
            >
          </div>
        </div>
        <div class="container">
          <div class="l">
            <el-tree
              :data="data"
              :props="defaultProps"
              class="tree"
              :check-on-click-leaf="false"
              :default-expand-all="true"
            >
              <template #default="{ node, data }">
                <div class="treeitem">
                  <div
                    class="icon"
                    v-if="data.children && data.children.length"
                  >
                    <el-icon :size="10" class="iocnPlus"><Plus /></el-icon>
                    <el-icon :size="10" class="iocnMinus"><Minus /></el-icon>
                  </div>
                  <div
                    class="title"
                    :class="{ on: name == node.label && deptId == data.deptId }"
                    @click.stop="screen(data)"
                  >
                    {{ node.label }}
                  </div>
                </div>
              </template>
            </el-tree>
          </div>

          <div class="r">
            <el-table
              :data="tableData"
              class="table"
              border
              v-loading="loading"
              style="width: 100%"
            >
              <el-table-column
                type="index"
                label="序号"
                width="120"
                align="center"
              >
                <template #default="{ row, $index }">
                  {{
                    (queryParams.pageNum - 1) * queryParams.pageSize +
                    $index +
                    1
                  }}
                </template>
              </el-table-column>
              <el-table-column
                label="用户编号"
                align="center"
                key="userId"
                prop="userId"
              />
              <el-table-column
                prop="userName"
                label="账号"
                width="120"
                align="center"
              />
              <el-table-column prop="nickName" label="姓名" />
              <el-table-column prop="dept.deptName" label="部门名称" />
              <el-table-column prop="remark" label="备注" />
              <el-table-column
                prop="createTime"
                label="添加时间"
                sortable
                align="center"
                width="180"
              />
              <el-table-column
                fixed="right"
                label="操作"
                width="120"
                align="center"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="handleUpdate(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    link
                    type="primary"
                    size="small"
                   @click="handleDelete(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getusertlist"
            />
          </div>
        </div>
      </div>
    </el-card>
  </div>
  <!-- 添加弹框 -->
  <el-dialog
    v-model="dialogVisible"
    width="500"
    :title="form.id ? '编辑部门' : '添加部门'"
    header-class="dialogheader"
    :align-center="true"
    center
  >
    <el-form :model="form" ref="formEl" label-width="auto" :rules="rules">
      <el-form-item label="成员姓名" prop="nickName">
        <el-input v-model="form.nickName" />
      </el-form-item>
      <el-form-item label="成员账号" prop="userName" >
        <el-input v-model="form.userName"  autocomplete="off"/>
      </el-form-item>
      <el-form-item
        v-if="form.userId == undefined"
        label="用户密码"
        prop="password"
      >
        <el-input
          v-model="form.password"
          autocomplete="off"
          placeholder="请输入用户密码"
          type="password"
          maxlength="20"
          show-password
        />
      </el-form-item>
      <el-form-item label="选择部门" prop="deptId">
         <el-tree-select v-model="form.deptId" :data="enabledDeptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属部门" clearable check-strictly />
         
      </el-form-item>
      <el-form-item label="选择角色" prop="roleIds">
        <el-radio-group v-model="form.roleIds" >
           <el-radio  :key="item.roleId"  :value="item.roleId" :disabled="item.status == 1" v-for="item in roleOptions">{{ item.roleName }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm(formEl)">取消</el-button>
        <el-button type="primary" @click="submitForm(formEl)"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  listDepttree,
  getDept,
  levelOptions,
  addDept,
  updateDept,
  delDept,
} from "@/api/system/SysSpeedingDept.js";
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
} from "@/api/system/user";
import { CirclePlus, Search, Plus, Minus } from "@element-plus/icons-vue";
import { ref } from "vue";

import { ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex"
);

const userdata = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined,
  },
  rules: {
    userName: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "用户名称长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" },
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        min: 5,
        max: 20,
        message: "用户密码长度必须介于 5 和 20 之间",
        trigger: "blur",
      },
      {
        pattern: /^[^<>"'|\\]+$/,
        message: "不能包含非法字符：< > \" ' \\\ |",
        trigger: "blur",
      },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phonenumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(userdata);
const formEl=ref()
const loading = ref(false);
const roleOptions = ref([])
const dialogVisible = ref(false);
const deptId = ref("");
const dateRange = ref([]);
const total = ref(0);
const title=ref("")
const tableData = ref([]);
const deptOptions = ref(undefined)
const enabledDeptOptions = ref(undefined)
const postOptions=ref([])
const initPassword = ref(undefined)
const defaultProps = {
  children: "children",
  label: "deptName",
  class: "custtree",
};
const data = ref([]);
function screen(item) {
  deptId.value = item.deptId;
  pageNum.value = 1;
  serchKey.value = "";
  getDeptlist();
}

const resetForm = (formEl) => {
  if (!formEl) return;
  dialogVisible.value = false;
  formEl.resetFields();
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      dialogVisible.value = false;
      if (form.value.userId != undefined) {
        updateUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          dialogVisible.value = false
          getusertlist()
        })
      } else {
        addUser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          dialogVisible.value = false
          getusertlist()
        })
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
function remove(item) {
  ElMessageBox.confirm("确定删除该部门？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delDept(item.deptId).then((r) => {
        getthreedata(false);
      });
    })
    .catch(() => {});
}

// 左边数据
function getthreedata(type = true) {
  listDepttree().then((res) => {
    data.value = res.data;
    if (res.data.length && type) {
      deptId.value = 0;
    }
    getusertlist();
  });
}
getthreedata();
 getDeptTree()
/** 查询用户列表 */
function getusertlist() {
  loading.value = true;
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      console.log();
      loading.value = false;
      tableData.value = res.rows;
      total.value = res.total;
    }
  );
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
  })
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

// 编辑数据
function editshow(item) {
  console.log(item.parentId);
  form.value = {
    deptId: item.deptId,
    parentId: item.parentId,
    deptName: item.deptName,
    deptLevel: item.deptLevel,
    remark: item.remark,
  };
  dialogVisible.value = true;
  elradiogroup(false);
}

/** 新增按钮操作 */
function handleAdd() {

  reset()
  getUser().then(response => {
    postOptions.value = response.posts
    roleOptions.value = response.roles
    dialogVisible.value = true
    title.value = "添加用户"
    form.value.password = initPassword.value
  })
}
/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: []
  }
  proxy.resetForm("userRef")
}
// 搜索
function listSearch(e) {
  console.log(e);
  if ((e &&  e.keyCode && e.keyCode == 13) || !e) {
    queryParams.value.pageNum = 1;
    getusertlist();
  }
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const userId = row.userId || ids.value
  getUser(userId).then(response => {
    form.value = response.data
    postOptions.value = response.posts
    roleOptions.value = response.roles
    form.value.postIds = response.postIds
    form.value.roleIds = response.roleIds
    dialogVisible.value = true
    title.value = "修改用户"
    form.password = ""
  })
}
/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || ids.value
  proxy.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
    return delUser(userIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
onMounted(() => {
  getDeptTree()
  getusertlist()
  proxy.getConfigKey("sys.user.initPassword").then(response => {
    initPassword.value = response.msg
  })
})
</script>
<style lang="scss" scoped>
.top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 15px;
  .l {
    font-weight: 500;
    font-size: 16px;
    color: #333333;
  }
  .r {
    display: flex;
    gap: 20px;
  }
}
.cardbox {
  height: calc(100vh - 84px - 30px - 30px - 30px);
}

.container {
  border-top: 1px solid #eee;
  height: calc(100% - 47px);
  display: flex;
  .l {
    width: 350px;
    padding: 15px;
    overflow: auto;
    flex-shrink: 0;
    height: 100%;
    :deep(.tree) {
      --el-tree-node-content-height: 35px;
      height: 100%;
      overflow: auto;
      .is-focusable .el-tree-node__content {
        background: transparent;
      }
      .el-tree-node > .el-tree-node__children {
        overflow: inherit;
      }
      .custtree {
        .custtree {
          padding-left: 25px;
          position: relative;
          &::before {
            content: "";
            position: absolute;
            height: calc(100% + 12px);
            width: 1px;
            top: 0px;
            left: 7px;
            border-right: 1px dashed #979797;
          }

          .el-tree-node__content {
            padding: 0px !important;
            position: relative;
            &::after {
              content: "";
              position: absolute;
              height: 1px;
              width: 10px;
              top: 13px;
              left: -15px;
              border-top: 1px dashed #979797;
            }
            &::before {
              content: "";
              position: absolute;
              height: 14px;
              width: 1px;
              top: 0px;
              left: -18px;
              border-left: 1px dashed #979797;
            }
          }

          &:nth-last-of-type(1) {
            &::before {
              display: none;
            }
          }
        }

        & > .el-tree-node__content {
          .el-tree-node__expand-icon {
            display: none;
          }
          .icon .iocnPlus {
            display: block;
          }
          .icon .iocnMinus {
            display: none;
          }
        }
      }
      .is-expanded {
        & > .el-tree-node__content {
          .icon .iocnPlus {
            display: none !important;
          }
          .icon .iocnMinus {
            display: block !important;
          }
        }
      }
    }
    .tree {
      width: fit-content;
      min-width: 100%;
      .treeitem {
        display: flex;
        align-items: center;
        width: 100%;
      }
      .icon {
        color: #4d7bff;
        border: 1px solid;
        padding: 2px;
        border-radius: 2px;
        margin-right: 10px;
      }
      .title {
        white-space: nowrap;
        padding: 5px 3px;
        width: 100%;

        display: block;
        &.on {
          background: #ecf1ff;
          color: #000;
        }
      }
    }
  }
  .r {
    flex: 1;
    .table {
      height: calc(100% - 60px);
    }
  }
}
</style>
