<template>
  <div>
    <div class="search flex justify-between bg-white rounded-md">
      <el-form :inline="true" class="demo-form-inline" size="default">
        <el-form-item>
          <el-input v-model="form_query.ue_jbxx_ju_sydw" placeholder="请输入事业单位" class="w-40" @change="initData" clearable />
          <!-- <el-select v-model="form_query.ue_jbxx_ju_sydw" placeholder="全部事业单位" class="w-40" @change="initData">
            <el-option v-for="item in sydwList" :key="item" :label="item" :value="item" />
          </el-select> -->
        </el-form-item>
        <el-form-item>
          <el-input v-model="form_query.ue_jbxx_ju_bm" placeholder="请输入部门" class="w-40" @change="initData" clearable />
          <!-- <el-select v-model="form_query.ue_jbxx_ju_bm" placeholder="全部部门" class="w-40" @change="initData">
            <el-option v-for="item in bmList" :key="item" :label="item" :value="item" />
          </el-select> -->
        </el-form-item>
        <el-form-item>
          <el-input v-model="form_query.ue_jbxx_ju_zw" placeholder="请输入职位" class="w-40" @change="initData" clearable />
          <!-- <el-select v-model="form_query.ue_jbxx_ju_zw" placeholder="全部职位" class="w-40" @change="initData">
            <el-option v-for="item in zwList" :key="item" :label="item" :value="item" />
          </el-select> -->
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="initData"> 查询 </el-button>
      </div>
    </div>
    <div class="bg-white rounded-md mt-4 px-23px py-16px">
      <div class="flex justify-between pb-4 btn">
        <div>
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="primary" @click="exportAll">导出</el-button>
          <import-button url="/user/main" :d="{ user_role_id: '3' }" @success="initData">
            <template #text>批量导入</template>
          </import-button>
          <el-button type="danger" @click="handleMulDelete" :disabled="multipleSelection.length == 0">删除</el-button>
        </div>
        <div class="flex content-center">
          <el-input v-model="form_query.keyword" class="w-40 mx-2" size="small" placeholder="请输搜索关键词" :suffix-icon="Search" clearable />

          <el-button type="primary" @click="initData">搜索</el-button>
        </div>
      </div>
      <el-table :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="user_id" label="ID" width="100"></el-table-column>
        <el-table-column prop="user_name" label="账号" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="user_realname" label="姓名" width="150"></el-table-column>
        <el-table-column prop="ue_jbxx_ju_sydw" label="事业单位">
          <template #default="scope">
            {{ scope.row.ext.ue_jbxx_ju_sydw }}
          </template>
        </el-table-column>
        <el-table-column prop="ue_jbxx_ju_bm" label="所属部门">
          <template #default="scope">
            {{ scope.row.ext.ue_jbxx_ju_bm }}
          </template>
        </el-table-column>
        <el-table-column prop="ue_jbxx_ju_zw" label="职位">
          <template #default="scope">
            {{ scope.row.ext.ue_jbxx_ju_zw }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="245">
          <template #default="scope">
            <el-button type="text" @click="handleDetail(scope.row.user_id)">详情 |</el-button>
            <el-button type="text" @click="handleEdit(scope.row)">编辑 |</el-button>
            <el-button type="text" @click="handleDelete(scope.row.user_id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-end my-10">
        <el-pagination v-model:current-page="form_query.page" v-model:page-size="form_query.limit" layout="total,sizes, prev, pager, next, jumper" :total="total" :background="true" @current-change="initData" :hide-on-single-page="false" />
      </div>
      <el-dialog v-model="dialogVisible" :title="title" width="780px">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize" status-icon>
          <h3 class="text-hex-00A3FF">账号信息</h3>
          <div class="flex">
            <el-form-item label="账号：" prop="user_name">
              <el-input class="rank" v-model="ruleForm.user_name" />
            </el-form-item>
            <el-form-item label="密码：" prop="user_password">
              <el-input class="rank" v-model="ruleForm.user_password" :disabled="isEdit" />
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item label="用户角色：" prop="user_role_id_sub">
              <el-select multiple collapse-tags v-model="userRoleData" filterable clearable @change="handleRoleChange">
                <el-option v-for="(item, index) in roleList" :key="index" :label="item.tur_role_name" :value="item.tur_id" />
              </el-select>
              <el-button type="primary" class="ml-100px" plain @click="setRoleDialogVisible = true">自定义角色</el-button>
            </el-form-item>
          </div>
          <h3 class="text-hex-00A3FF">基本信息</h3>
          <el-form-item label="头像：">
            <file-upload-progress v-if="dialogVisible" v-model:part="ruleForm.user_avatar" :limit="1" accept=".jpg,.jpeg,.webp,.png" :size-limit="500 * 1024">
              <el-button type="primary"> 点击上传 </el-button>

              <template #tip>
                <div class="mt-2 text-xs">
                  只能上传jpg/png文件，且不超过500kb，建议尺寸600x337
                </div>
              </template>
            </file-upload-progress>
          </el-form-item>
          <el-form-item label="头像地址：" prop="user_avatar" class="w-640px">
            <el-input v-model="ruleForm.user_avatar" />
          </el-form-item>
          <div class="flex">
            <el-form-item label="姓名：" prop="user_realname">
              <el-input class="rank" v-model="ruleForm.user_realname" />
            </el-form-item>
            <el-form-item label="性别：" prop="gender">
              <el-radio-group v-model="ruleForm.gender">
                <el-radio label="1">男</el-radio>
                <el-radio label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item label="事业单位：" prop="ue_jbxx_ju_sydw">
              <el-input class="rank" v-model="ruleForm.ue_jbxx_ju_sydw" />
              <!-- <el-select v-model="ruleForm.ue_jbxx_ju_sydw" placeholder="全部事业单位">
                <el-option v-for="item in sydwList" :key="item" :label="item" :value="item" />
              </el-select> -->
            </el-form-item>
            <el-form-item label="职位：" prop="ue_jbxx_ju_zw">
              <el-input class="rank" v-model="ruleForm.ue_jbxx_ju_zw" />
              <!-- <el-select v-model="ruleForm.ue_jbxx_ju_zw" placeholder="全部职位">
                <el-option v-for="item in zwList" :key="item" :label="item" :value="item" />
              </el-select> -->
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item label="所属部门：" prop="ue_jbxx_ju_bm">
              <el-input class="rank" v-model="ruleForm.ue_jbxx_ju_bm" />
              <!-- <el-select v-model="ruleForm.ue_jbxx_ju_bm" placeholder="全部部门">
                <el-option v-for="item in bmList" :key="item" :label="item" :value="item" />
              </el-select> -->
            </el-form-item>
          </div>
          <el-form-item label="特长：" prop="about" class="w-640px">
            <el-input type="textarea" v-model="ruleForm.about" />
          </el-form-item>
          <h3 class="text-hex-00A3FF">联系方式</h3>
          <div class="flex">
            <el-form-item label="联系电话：" prop="user_phone">
              <el-input class="rank" v-model="ruleForm.user_phone" />
            </el-form-item>
            <el-form-item label="电子信箱：" prop="user_email">
              <el-input class="rank" v-model="ruleForm.user_email" />
            </el-form-item>
          </div>
        </el-form>
        <div class="text-center">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :disabled="isButton" @click="handleSubmit(ruleFormRef)">
            确定
          </el-button>
        </div>
      </el-dialog>
      <el-dialog v-model="detailDialogVisible" class="_" width="778" title="详情">
        <img class="avatar" :src="ruleForm.user_avatar" />

        <el-form class="grid grid-cols-2" ref="ruleFormRef" label-position="right" label-width="90px" :model="detailForm">
          <el-form-item label="账号:">
            {{ detailForm.user_name }}
          </el-form-item>
          <el-form-item label="用户角色:">
            {{ detailForm.role_name }}
          </el-form-item>
          <el-form-item label="姓名:">
            {{ detailForm.user_realname }}
          </el-form-item>
          <el-form-item label="性别:">
            {{ detailForm.gender1 }}
          </el-form-item>
          <el-form-item label="事业单位:">
            {{ detailForm.ue_jbxx_ju_sydw }}
          </el-form-item>
          <el-form-item label="职位:">
            {{ detailForm.ue_jbxx_ju_zw }}
          </el-form-item>
          <el-form-item label="所属部门:" class="col-span-full">
            {{ detailForm.ue_jbxx_ju_bm }}
          </el-form-item>
          <el-form-item label="特长:" class="col-span-full">
            {{ detailForm.about }}
          </el-form-item>
          <el-form-item label="联系电话:">
            {{ detailForm.user_phone }}
          </el-form-item>
          <el-form-item label="电子邮件:">
            {{ detailForm.user_email }}
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="flex_center space-x-12">
            <el-button size="large" type="primary" @click="handleFormCancel">返回</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="setRoleDialogVisible" class="_" width="565" title="自定义角色" destroy-on-close @close="handleClose">
        <el-form class="table" ref="ruleFormRef1" :model="roleData" :rules="roleRules">
          <el-form-item label="角色名：" prop="tur_role_name" class="w-270px">
            <el-input v-model="roleData.tur_role_name" type="text" />
          </el-form-item>
          <el-form-item label="" prop="tur_role_menu">
            <div class="w-full">设置权限：</div>
            <menu-item v-model="roleData.tur_role_menu"></menu-item>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="flex_center space-x-12">
            <el-button size="large" @click="handleClose">取消</el-button>
            <el-button size="large" type="primary" @click="PermissionSubmit(ruleFormRef1)">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { useRouter } from "vue-router";
import { user } from "@/store/index";
import { Search } from "@element-plus/icons-vue";
import MenuItem from "~/pages/manage/yhxx/jsgl/MenuItem.vue";
import {
  yhxx_ju_list,
  yhxx_ju_del,
  yhxx_ju_edit,
  yhxx_ju_add,
  yhxx_ju_detail,
  role_list,
  role_add,
  role_edit,
  role_detail,
  sydw_list,
} from "./api";
const router = useRouter();
let detailForm = ref({});
const ruleFormRef = ref(null);
const ruleFormRef1 = ref(null);
const userRoleData = $ref([]);
let ruleForm = $ref({
  user_name: "",
  user_password: "",
  user_role_id_sub: "",
  user_avatar: "",
  user_realname: "",
  gender: "",
  ue_jbxx_ju_bm: "",
  ue_jbxx_ju_sydw: "",
  ue_jbxx_ju_zw: "",
  user_phone: "",
  user_email: "",
  about: "",
  user_role_id: "3",
});
let keyword = $ref("");
let tableData = $ref([]);

let rules = $ref({
  user_name: [{ required: true, message: "请输入账号", trigger: "submit" }],
  //user_password: [{ required: true, message: "请输入密码", trigger: "submit" }],
  user_realname: [{ required: true, message: "请输入姓名", trigger: "submit" }],
  gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
  sm_id: [{ required: true, message: "请选择学校", trigger: "blur" }],
  ue_jbxx_ju_sydw: [
    { required: true, message: "请选择事业单位", trigger: "blur" },
  ],
  ue_jbxx_ju_bm: [{ required: true, message: "请选择部门", trigger: "blur" }],
  ue_jbxx_ju_zw: [{ required: true, message: "请选择职位", trigger: "blur" }],
});
let roleRules = $ref({
  tur_role_name: [
    { required: true, message: "请输入角色名", trigger: "submit" },
  ],
  tur_role_menu: [{ required: true, message: "请选择菜单", trigger: "submit" }],
});
//角色列表
let roleList = $ref([]);
function initRoleData() {
  role_list({ limit: "100", M5jxrcL: "" }).then((res) => {
    if (res.code === "1") {
      roleList = res.data.page_data;
    }
  });
}

let sydwList = $ref([]);
let bmList = $ref([]);
let zwList = $ref([]);
function initSydwData() {
  let data1 = {
    type: "sydw",
  };
  sydw_list(data1).then((res) => {
    if (res.code === "1") {
      sydwList = res.data.list;
    }
  });
  let data2 = {
    type: "bm",
  };
  sydw_list(data2).then((res) => {
    if (res.code === "1") {
      bmList = res.data.list;
    }
  });
  let data3 = {
    type: "zw",
  };
  sydw_list(data3).then((res) => {
    if (res.code === "1") {
      zwList = res.data.list;
    }
  });
}
initSydwData();
let total = $ref(10);
let form_query = $ref({
  page: 1,
  limit: 6,
  keyword: "",
  user_role_id: "3",
});
//列表
function initData() {
  const data = {
    ...form_query,
  };
  yhxx_ju_list(data).then((res) => {
    if (res.code == "1") {
      tableData = res.data.page_data;
      total = res.data.total_rows * 1;
    }
  });
}
initData();
let multipleSelection = $ref([]);
let handleSelectionChange = (val) => {
  multipleSelection = [];
  val.forEach((i) => {
    multipleSelection.push(i.user_id);
  });
};
let roleData = $ref({
  tur_role_name: "",
  tur_role_menu: "",
});
//添加额外权限
let setRoleDialogVisible = $ref(false);

function handleRoleChange(val) {
  ruleForm.user_role_id_sub = val.join();
}

let detailDialogVisible = ref(false);
let detailData = ref({});
//详情
function handleDetail(id) {
  const data = {
    user_id: id,
  };
  yhxx_ju_detail(data).then((res) => {
    if (res.code === "1") {
      detailData = res.data;
      detailForm = {
        user_role_id: "3",
        user_role_id_sub: "",
        user_name: detailData.user_name,
        user_realname: detailData.user_realname,
        role_name: detailData.role_name,
        user_avatar: detailData.user_avatar,
        gender: detailData.gender,
        gender1:
          detailData.gender == 1
            ? "男"
            : detailData.gender == 2
              ? "女"
              : "保密",
        ue_jbxx_ju_sydw: detailData.ext.ue_jbxx_ju_sydw,
        ue_jbxx_ju_zw: detailData.ext.ue_jbxx_ju_zw,
        ue_jbxx_ju_bm: detailData.ext.ue_jbxx_ju_bm,
        about: detailData.about,
        user_phone: detailData.user_phone,
        user_email: detailData.user_email,
      };
      if (detailData.user_role_id_ext) {
        userRoleData = detailData.user_role_id_ext.split(",");
      }

      Object.keys(ruleForm).find((item) => {
        ruleForm[item] = detailForm[item];
      });
      if (!dialogVisible) {
        detailDialogVisible.value = true;
      }
    }
  });
}
//新增
let dialogVisible = $ref(false);
let title = $ref("");
let isEdit = $ref(false);
function handleAdd() {
  dialogVisible = true;
  initRoleData();
  title = "新增";
  isEdit = false;
  ruleForm = {
    user_name: "",
    user_password: "",
    user_role_id_sub: "",
    user_avatar: "",
    user_realname: "",
    gender: "",
    ue_jbxx_ju_bm: "",
    ue_jbxx_ju_sydw: "",
    ue_jbxx_ju_zw: "",
    user_phone: "",
    user_email: "",
    about: "",
    user_role_id: "3",
  };
}
let currentId = $ref("");
// 编辑弹窗
function handleEdit(row) {
  dialogVisible = true;
  initRoleData();
  title = "编辑";
  isEdit = true;
  currentId = row.user_id;
  handleDetail(row.user_id);
}

const handleSubmit = async (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let obj = {};
      Object.keys(ruleForm).find((item) => {
        obj[item] = ruleForm[item];
      });
      const data = {
        user_main: obj,
      };
      if (!isEdit) {
        if (!data.user_main.user_password) {
          return ElMessage({
            type: "warning",
            message: "请输入密码",
          });
        }
        yhxx_ju_add(data).then((res) => {
          if (res.code == 1) {
            ElMessage({
              message: "添加成功",
              type: "success",
            });
            dialogVisible = false;
            initData();
          } else {
            ElMessage({
              message: res.msg,
              type: "error",
            });
          }
        });
      } else {
        data.user_id = currentId;
        yhxx_ju_edit(data).then((res) => {
          if (res.code == 1) {
            ElMessage({
              message: "编辑成功",
              type: "success",
            });
            dialogVisible = false;
            initData();
          } else {
            ElMessage({
              message: res.msg,
              type: "error",
            });
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 批量删除
function handleMulDelete() {
  ElMessageBox.confirm("确认删除这些数据?", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = { user_id: multipleSelection };
      yhxx_ju_del(data).then((res) => {
        if (res.code == 1) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          initData();
        } else {
          ElMessage({
            message: res.msg,
            type: "error",
          });
        }
      });
    })
    .catch(() => { });
}
// 单个删除
function handleDelete(id) {
  ElMessageBox.confirm("确认删除?", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = { user_id: id };
      yhxx_ju_del(data).then((res) => {
        if (res.code == 1) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          initData();
        } else {
          ElMessage({
            message: res.msg,
            type: "error",
          });
        }
      });
    })
    .catch(() => { });
}
function exportAll() {
  let ids = multipleSelection.join(",");
  let link =
    window.GLOBAL_CONFIG.api +
    "/user/main/index?user_role_id=3&api=xls&page=1&limit=10000&token=" +
    user.value.token +
    "&user_id=" +
    ids;
  console.log(link);
  window.open(link, "_blank");
}
function handleFormCancel() {
  detailDialogVisible.value = false;
}

const PermissionSubmit = async (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const data = {
        txwx_user_role: {
          tur_role_name: roleData.tur_role_name,
          tur_role_menu: roleData.tur_role_menu,
        },
      };
      role_add(data).then((res) => {
        if (res.code == 1) {
          ElMessage({
            message: "添加成功",
            type: "success",
          });
          handleClose();
          initRoleData();
        } else {
          ElMessage({
            message: res.msg,
            type: "error",
          });
        }
      });
    }
  });
};

const handleClose = () => {
  setRoleDialogVisible = false;
  roleData = {
    tur_role_name: "",
    tur_role_menu: "",
  };
};
</script>
<style lang="scss" scoped>
.search {
  height: 72px;
  line-height: 85px;
  padding: 0 29px;
}
.avatar {
  width: 82px;
  height: 82px;
  background: #c4c4c4;
  border-radius: 8px;
  margin: 30px auto 50px;
}
:deep() .el-dialog__body {
  padding-left: 60px;
  border-top: 1px solid #f3f3f3;
}
.btn {
  border-bottom: 1px solid #e3e3e3;
}
</style>