<template>
  <div class="user-list-page">
    <el-card class="table-header-wrap">
      <el-form :model="listQuery" class="mosty-from-wrap" :inline="true">
        <el-form-item label="用户ID">
          <el-input
            placeholder="请输入用户ID"
            v-model="listQuery.userId"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleFilter">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="unbundleRole()"
            >批量取消授权</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addUser()">添加用户</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="main-box">
      <el-card class="user-main-wrap">
        <el-table
          ref="multipleTableRef"
          @selection-change="handleSelectionChange"
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            prop="loginName"
            align="center"
            label="用户名"
          ></el-table-column>
          <el-table-column
            prop="userName"
            align="center"
            label="用户昵称"
          ></el-table-column>
          <el-table-column
            prop="mobile"
            width="120px"
            label="移动电话"
          ></el-table-column>

          <el-table-column prop="xtZhxgsj" align="center" label="录入时间">
            <template #default="{ row }">{{
              $filters.dateFilter(row.xtLrsj)
            }}</template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
                icon-color="red"
                title="确定要删除?"
                @confirm="unbundleRole(row)"
              >
                <template #reference>
                  <el-button type="danger" size="small">取消授权</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-card>
    </div>

    <el-dialog
      width="900px"
      custom-class="way"
      v-model="dialogFormVisible"
      @closed="closeDialog"
      :title="isEdit ? '修改' : '新增'"
    >
      <p>{{ dialogForm }}</p>
      <el-form
        ref="formRef"
        :model="dialogForm"
        label-width="120px"
        class="mosty-from-wrap twoLine"
        :rules="rules"
      >
        <el-form-item label="用户昵称:" prop="">
          <MOSTY.Other
            width="280px"
            placeholder="用户昵称"
            clearable
            v-model="dialogForm.userName"
          />
        </el-form-item>
        <el-form-item label="登录账号:" prop="">
          <MOSTY.Other
            width="280px"
            placeholder="登录账号"
            clearable
            v-model="dialogForm.loginName"
          />
        </el-form-item>
        <el-form-item label="密码:" prop="">
          <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"
            clearable
          ></MOSTY.IdentityCard>
        </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="">
          <MOSTY.Sex width="220px" v-model:sex="dialogForm.sex" />
        </el-form-item>
        <el-form-item label="文化程度:" prop="">
          <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="email">
          <el-date-picker
            v-model="dialogForm.birthday"
            type="date"
            placeholder="出生日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="有效期:" prop="">
          <el-date-picker
            v-model="dialogForm.endTime"
            type="datetime"
            placeholder="Select date and time"
            format="YYYY/MM/DD hh:mm:ss"
            value-format="x"
          />
        </el-form-item>
        <el-form-item label="行业号码:" prop="">
          <MOSTY.Other
            width="280px"
            placeholder="行业号码"
            v-model="dialogForm.inDustRialId"
          />
        </el-form-item>
        <el-form-item label="管理部门名称:" prop="">
          <MOSTY.Other
            width="280px"
            placeholder="管理部门名称"
            v-model="dialogForm.managerOrgName"
          />
        </el-form-item>
        <el-form-item label="管理部门ID:" prop="">
          <MOSTY.Department
            placeholder="管理部门ID"
            width="280px"
            clearable
            filterable
            multiple
            v-model="dialogForm.managerOrgId"
          />
        </el-form-item>
        <el-form-item label="岗位名称:" prop="">
          <MOSTY.Other
            width="280px"
            placeholder="岗位名称"
            v-model="dialogForm.positionName"
          />
        </el-form-item>
        <el-form-item label="岗位ID:" prop="">
          <MOSTY.Other
            width="280px"
            placeholder="岗位ID"
            v-model="dialogForm.positionId"
          />
        </el-form-item>

        <el-form-item label="用户类型:" prop="">
          <el-select v-model="dialogForm.userType" placeholder="请选择">
            <el-option label="系统用户默认" value="00" />
            <el-option label="注册用户" value="01" />
          </el-select>
        </el-form-item>
        <el-form-item label="虚拟用户:" prop="">
          <el-select v-model="dialogForm.isVirtualUser" placeholder="请选择">
            <el-option label="是" value="1" />
            <el-option label="不是" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="dialogForm.bz"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" v-if="isEdit" @click="onSave"
            >保存</el-button
          >
          <el-button type="primary" v-else @click="onAdd">新增</el-button>
        </span>
      </template>
    </el-dialog>
    <ChooseUser
      v-model="chooseUserVisible"
      :roleId="route.params.id"
      @choosedUsers="saveUsers"
    ></ChooseUser>
  </div>
</template>

<script setup>
import ChooseUser from "@/components/MyComponents/ChooseUser";
import { useRoute } from "vue-router";
import * as rule from "@/utils/rules.js";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import { ref, reactive, computed, watch } from "vue";
import {
  selectUnAccreditPage,
  batchUnboundUserRole,
  selectUserPageByDept,
  grantUserToRole
} from "@/api/user-manage";
const route = useRoute();
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 }), //邮箱
  packageSelect: [
    {
      required: true,
      message: "请选择",
      trigger: "change"
    }
  ],
  other: [
    {
      required: true,
      message: "自由发挥哦",
      trigger: "blur"
    }
  ]
});

//查询参数
const total = ref(0);
const currentRow = ref({});
const listQuery = ref({
  current: 1,
  size: 20
});
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;
  params.deptId = route.params.id;
  const res = await selectUserPageByDept(params);
  tableData.value = res?.records;
  total.value = Number(res.total);
};

const handleFilter = () => {
  listQuery.value.current = 1;
  getListData();
};

// 分页相关
/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.size = currentSize;
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.current = currentPage;
  getListData();
};

const unbundleRole = (row) => {
  let params = {
    roleId: route.params.id,
    userIdList: []
  };
  if (row) {
    params.userIdList.push(row.id);
  } else {
    if (multipleSelection.value.length <= 0) return false;
    multipleSelection.value.forEach((item) => {
      params.userIdList.push(item.id);
    });
  }
  batchUnboundUserRole(params).then((res) => {
    ElMessage.success("操作成功");
    handleFilter();
  });
};

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

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

const multipleTableRef = ref(null);
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const chooseUserVisible = ref(false);
const addUser = () => {
  chooseUserVisible.value = true;
};

//批量添加用户
const saveUsers = (users) => {
  if (users.length > 0) {
    let userIds = users.map((item) => item.id);
    let params = {
      roleId: route.params.id,
      userIds: userIds
    };
    grantUserToRole(params).then((res) => {
      ElMessage.success("修改成功");
      handleFilter();
    });
  }
};

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

watch(
  listQuery.value,
  () => {
    handleFilter();
  },
  {
    immediate: true
  }
);
</script>

<style lang="scss" scoped>
.user-list-page {
  .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;
    }
  }

  .main-box {
    padding-top: 20px;
    display: flex;
    justify-content: space-between;

    .departmentTree-box {
      overflow: auto;
    }

    .user-main-wrap {
      overflow: hidden;
      // width: calc(100% - 260px);
      width: 100%;

      .el-table--fit {
        float: right;
        width: 800px;
      }
    }
  }
}
</style>
