<template>
  <div class="user-list-page">
    <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.userName"
            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>
          <el-button type="success" @click="handleFilter">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="reset()"> 重置 </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>
    </div>
    <div class="tabBox">
        <el-table
          ref="multipleTableRef"
          @selection-change="handleSelectionChange"
          :data="tableData"
          border
          :height="tableHeight"
          :key="keyCount"
          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="Yes"
                cancel-button-text="No"
                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>
        <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>

    <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/ChooseList/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,onMounted,onUnmounted,getCurrentInstance } from "vue";
import {
  selectUnAccreditPage,
  batchUnboundUserRole,
  getRoleUserList,
  grantUserToRole
} from "@/api/user-manage";
const { proxy } = getCurrentInstance();
const route = useRoute();
const searchBox = ref()
const keyCount = ref(0); //tabel组件刷新值
const tableHeight = 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 }), //邮箱
  packageSelect: [
    {
      required: true,
      message: "请选择",
      trigger: "change"
    }
  ],
  other: [
    {
      required: true,
      message: "自由发挥哦",
      trigger: "blur"
    }
  ]
});

//查询参数
const total = ref(0);
const page = ref(1);
const size = ref(20);
const currentRow = ref({});
const listQuery = ref({
  page: 1,
  size: 20,
  userName: '',
  phone: ''
});
const isEdit = ref(true);
const dialogForm = ref({
  userName: ""
});
//分配角色
const currentUserId = ref("");
const roleDialogVisible = ref(false);
const multipleTableRef = ref(null);
const multipleSelection = ref([]);
const chooseUserVisible = ref(false);
// 数据相关
const tableData = ref([]);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";


onMounted(() => {
  getListData();
  tabHeightFn();
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});

// 获取数据的方法
const getListData = async () => {
  const params = listQuery.value;
  params.current = params.page;
  params.roleId = route.params.id;
  const res = await getRoleUserList(params);
  tableData.value = res?.records;
  total.value = Number(res.total);
};

const reset = () => {
  listQuery.value = {
    page: 1,
    size: 5,
    userName: "",
    phone: ""
  };
  getListData();
};
const handleFilter = () => {
  listQuery.value.page = 1;
  getListData();
};


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

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

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

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


const assignRoles = (row) => {
  roleDialogVisible.value = true;
  currentUserId.value = row.id;
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

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();
    });
  }
};

// 高度计算
const tabHeightFn = () => {
  tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 200;
    window.onresize = function () {
    tabHeightFn();
  };
};

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

</script>

<style lang="scss" scoped>
@import "@/assets/css/layout.scss";
@import "@/assets/css/element-plus.scss";
</style>
