<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>
      <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="exportAll">导出</el-button>
          <import-button url="/txwx/user_role" @success="initData">
            <template #text>批量导入</template>
          </import-button>
          <el-button type="primary" @click="addPermission()">新增自定义角色</el-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="tur_role_name" label="角色名" width="500" show-overflow-tooltip></el-table-column>
        <el-table-column prop="user_grade_num" label="注册时间">
          <template #default="scope">
            {{ scope.row.ex.create_dateline }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="245">
          <template #default="scope">
            <el-button type="text" @click="Staffing(scope.row)">配置人员 |</el-button>
            <el-button type="text" @click="editPermission(scope.row.tur_id)">编辑 |</el-button>
            <el-button type="text" @click="handleDelete(scope.row.tur_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="setRoleDialogVisible" width="565" destroy-on-close :title="title">
        <el-form ref="ruleFormRef" :model="roleData" :rules="roleRules">
          <el-form-item label="角色名：" prop="tur_role_name" class="w-270px">
            <el-input size="small" 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="setRoleDialogVisible = false">取消</el-button>
            <el-button size="large" type="primary" @click="PermissionSubmit(ruleFormRef)">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 配置人员对话框 -->
      <el-dialog v-model="StaffingDialogVisible" class="_" width="565" title="配置人员">
        <el-form ref="ruleFormRef" :model="userForm" label-position="right" label-width="90px">
          <el-form-item label="角色名：" prop="tur_role_name" class="w-295px">
            {{ roleName }}
          </el-form-item>
          <el-form-item label="配置人员：">
            <el-select v-model="userForm.user_id" multiple>
              <el-option v-for="item in userData" :key="item.user_id" :label="item.user_realname" :value="item.user_id" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="flex_center space-x-12">
            <el-button size="large" @click="StaffingDialogVisible = false">取消</el-button>
            <el-button size="large" type="primary" @click="handleSubmit(ruleFormRef)">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import MenuItem from "~/pages/manage/yhxx/jsgl/MenuItem.vue";
import { user } from "@/store/index";
import {
  role_list,
  role_add,
  role_edit,
  role_del,
  role_detail,
  yhxx_ju_list,
  assign_person,
} from "./api";
import { Search } from "@element-plus/icons-vue";
const ruleFormRef = ref(null);

let userForm = $ref({
  tur_role_name: "",
  user_realname: "",
});
const userData = $ref([]);
function getUserData() {
  const data = {
    user_role_id: "3",
  };
  yhxx_ju_list(data).then((res) => {
    if (res.code == "1") {
      userData = res.data.page_data;
      // total = res.data.total_rows * 1;
    }
  });
}
getUserData();

let tableData = $ref([]);
let total = $ref(10);
let form_query = $ref({
  page: 1,
  limit: 6,
  keyword: "",
  user_role_id: "3",
  M5jxrcL: ""
});

//列表
function initData() {
  const data = {
    ...form_query,
  };
  role_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.tur_id);
  });
  console.log(multipleSelection, 555555555);
};

function exportAll() {
  let ids = multipleSelection.join(",");

  let link =
    window.GLOBAL_CONFIG.api +
    "/txwx/user_role/index?api=xls&page=1&limit=10000&token=" +
    user.value.token +
    "&tur_id=" +
    ids;

  window.open(link, "_blank");
}

// 批量删除
function handleMulDelete() {
  ElMessageBox.confirm("确认删除这些数据?", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = { tur_id: multipleSelection };
      role_del(data).then((res) => {
        if (res.code == 1) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          initData();
        }
      });
    })
    .catch(() => { });
}
//单个删除
function handleDelete(id) {
  ElMessageBox.confirm("确认删除?", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = { tur_id: id };
      role_del(data).then((res) => {
        if (res.code == 1) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          initData();
        }
      });
    })
    .catch(() => { });
}

let roleData = $ref({
  tur_role_name: "",
  tur_role_menu: "",
});
const roleRules = ref({
  tur_role_name: [
    { required: true, message: "请输入角色名", trigger: "submit" },
  ],
  tur_role_menu: [{ required: true, message: "请选择菜单", trigger: "submit" }],
});

//添加额外权限
let setRoleDialogVisible = $ref(false);
function handleDetail(id) {
  const data = {
    tur_id: id,
    M5jxrcL: ""
  };
  role_detail(data).then((res) => {
    if (res.code === "1") {
      for (let key in roleData) {
        roleData[key] = res.data.one_info[key];
      }
    }
  });
}
let title = $ref("");
let isEdit = $ref(false);
function addPermission() {
  setRoleDialogVisible = true;
  title = "新增";
  isEdit = false;
  roleData = {
    tur_role_name: "",
    tur_role_menu: "",
  };
  currentId = "";
}
let currentId = $ref("");
function editPermission(id) {
  handleDetail(id);
  setRoleDialogVisible = true;
  title = "编辑";
  isEdit = true;
  currentId = id;
}

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,
        },
      };

      if (!isEdit) {
        role_add(data).then((res) => {
          if (res.code == 1) {
            ElMessage({
              message: "添加成功",
              type: "success",
            });
            setRoleDialogVisible = false;
            roleData = {
              tur_role_name: "",
              tur_role_menu: "",
            };
            initData();
          } else {
            ElMessage({
              message: res.msg,
              type: "error",
            });
          }
        });
      } else {
        data.tur_id = currentId;
        role_edit(data).then((res) => {
          if (res.code == 1) {
            ElMessage({
              message: "编辑成功",
              type: "success",
            });
            setRoleDialogVisible = false;
            roleData = {
              tur_role_name: "",
              tur_role_menu: "",
            };
            initData();
          } else {
            ElMessage({
              message: res.msg,
              type: "error",
            });
          }
        });
      }
    }
  });
};

let roleName = $ref("");
let tur_id = $ref("");
let StaffingDialogVisible = $ref(false);
function Staffing(val) {
  roleName = val.tur_role_name;
  StaffingDialogVisible = true;
  tur_id = val.tur_id;
}

const handleSubmit = async (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const data = {
        tur_id: tur_id,
        user_id: userForm.user_id.join(","),
      };
      console.log(data, 123);
      assign_person(data).then((res) => {
        if (res.code == 1) {
          ElMessage({
            message: "设置成功",
            type: "success",
          });
          StaffingDialogVisible = false;
          initData();
        } else {
          ElMessage({
            message: res.msg,
            type: "error",
          });
        }
      });
    }
  });
};
</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;
}
</style>