<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input v-model="queryParams.key" placeholder="角色名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button type="primary" icon="plus" @click="handleOpenDialog()">新增</el-button>
        <!-- <el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()">
          删除
        </el-button> -->
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="roleList" highlight-current-row :border="true"
        @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="角色名称" prop="name" />
        <el-table-column label="角色级别" prop="level" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="创建日期" prop="createTime" />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button type="primary" size="small" link icon="position" @click="handleOpenAssignPermDialog(scope.row)">
              分配菜单
            </el-button>
            <el-button type="primary" size="small" link icon="edit" @click="handleOpenDialog(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" link icon="delete" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
        v-model:limit="queryParams.size" @pagination="handleQuery" />
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="handleCloseDialog">
      <el-form ref="addRequestRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色等级" prop="level">
          <el-input-number placeholder="角色等级" v-model="formData.level"></el-input-number>
        </el-form-item>

        <!-- <el-form-item label="数据菜单" prop="dataScope">
          <el-select v-model="formData.dataScope">
            <el-option :key="0" label="全部数据" :value="0" />
            <el-option :key="1" label="部门及子部门数据" :value="1" />
            <el-option :key="2" label="本部门数据" :value="2" />
            <el-option :key="3" label="本人数据" :value="3" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="formData.description" placeholder="描述" />
        </el-form-item>
        <el-alert title="角色菜单请点击角色列表的分配菜单按钮编辑" type="success" effect="dark" />
        <!-- <el-form-item label="菜单分配" prop="menuIdList">
          <menuSelect ref="refmenuSelect" v-model="formData.menuIdList"></menuSelect>
        </el-form-item> -->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配菜单弹窗 -->
    <el-drawer v-model="assignPermDialogVisible" size="500" @open="parentChildLinked = false">
      <template #header>
        <div>
          <div>
            <h3>
              {{ "【" + checkedRole.name + "】菜单分配" }}
            </h3>
          </div>
          <div>
            <el-form-item label="平台类型">
              <el-radio-group v-model="platformType" @change="handlePlatformTypeChange">
                <el-radio :value="0">管理端</el-radio>
                <el-radio :value="1">收银机</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="flex-x-between">
            <el-input v-model="permKeywords" clearable class="w-[150px]" placeholder="菜单名称">
              <template #prefix>
                <Search />
              </template>
            </el-input>

            <div class="flex-center ml-5">
              <el-button type="primary" size="small" plain @click="togglePermTree">
                <template #icon>
                  <Switch />
                </template>
                {{ isExpanded ? "收缩" : "展开" }}
              </el-button>
              <el-checkbox v-model="parentChildLinked" class="ml-5" @change="handleparentChildLinkedChange">
                父子联动
              </el-checkbox>

              <el-tooltip placement="bottom">
                <template #content>
                  如果只需勾选菜单菜单，不需要勾选子菜单或者按钮菜单，请关闭父子联动
                </template>
                <el-icon class="ml-1 color-[--el-color-primary] inline-block cursor-pointer">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </div>
        </div>
      </template>
      <div class="u-relative" style="overflow-x: hidden">
        <el-tree ref="permTreeRef" node-key="value" show-checkbox :data="menuPermOptions"
          :default-checked-keys="adminMenuIdList" :filter-node-method="handlePermFilter" :default-expand-all="true"
          :check-strictly="!parentChildLinked" class="mt-5">
          <template #default="{ data }">
            {{ data.label }}
          </template>
        </el-tree>
        <div class="cashMenuIdList" :style="{
          transform: `translateX(${(platformType == 1 ? 0 : 1) * 100}%)`,
        }">
          <el-checkbox-group v-model="cashMenuIdList">
            <el-checkbox v-for="(item, index) in casher_windows_menus" :key="index" :value="item.menuId">
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleAssignPermSubmit">确 定</el-button>
          <el-button @click="assignPermDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-drawer>
    <roleTemplateDialog ref="roleTemplateDialogRef" @success="handleQuery" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Role",
  inheritAttrs: false,
});
import { useUserStore } from "@/store/modules/user";
// import { casher_windows_menus } from "@/data/menus";
const shopUser = useUserStore();
import menuSelect from "./components/menus.vue";
import RoleApi, { SysRole, addRequest, getListRequest } from "@/api/account/role";
import MenuAPI, { type RouteVO, CashMenu } from "@/api/account/menu";
import roleTemplateDialog from "./components/roleTemplateDialog.vue";
import { roleTemplateList } from '@/api/account/roleTemplate'

const roleTemplateDialogRef = ref(null)

const queryFormRef = ref();
const addRequestRef = ref();
const refmenuSelect = ref();
const permTreeRef = ref();

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<getListRequest>({
  page: 1,
  size: 10,
  key: "",
});

// 角色表格数据
const roleList = ref<SysRole[]>();
// 菜单菜单下拉
const menuPermOptions = ref<RouteVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
  row: {},
});
// 角色表单
const formData = reactive<addRequest>({
  // sort: 1,
  // status: 1,
  id: null,
  name: "",
  level: 0,
  menuIdList: [],
  description: "",
});
const cashMenuIdList = ref<number[]>([]);
const rules = reactive({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  level: [{ required: false, message: "请输入角色等级", trigger: "blur" }],
});

// 选中的角色
interface CheckedRole {
  id?: number;
  name?: string;
}
const checkedRole = ref<CheckedRole>({});
const assignPermDialogVisible = ref(false);

const permKeywords = ref("");
const isExpanded = ref(true);

const parentChildLinked = ref(false);

const platformType = ref(0);
function handlePlatformTypeChange(e: string | number | boolean | undefined) {
  const value = Number(e); // Ensure the value is cast to a number
  console.log("handlePlatformTypeChange");
  platformType.value = value;
  handleOpenAssignPermDialog(dialog.row);
}

// 查询
function handleQuery() {
  loading.value = true;
  RoleApi.getList(queryParams)
    .then(async (data) => {
      roleList.value = data.records;
      total.value = data.totalRow;

      console.log('data===', data);

      const res = await roleTemplateList({ isEnable: 1 })

      console.log('roleTemplateList===', res);


      if (data.records.length == 0 && res.length > 0) {
        roleTemplateDialogRef.value.show()
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  queryParams.size = 10;
  queryParams.key = "";
  handleQuery();
}

// 行复选框选中
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 打开角色弹窗
async function handleOpenDialog(row: SysRole) {
  dialog.visible = true;
  dialog.row = row;
  if (row && row.id) {
    dialog.title = "修改角色";
    //获取角色菜单列表
    const data = await RoleApi.getMenu(row.id, platformType.value);
    // const data = await RoleApi.getList(row.id, platformType.value);
    console.log(data);
    Object.assign(formData, row);
    formData.menuIdList = data;
    setTimeout(() => {
      // refmenuSelect.value.setChecked(data);
    }, 300);
    console.log(formData);
  } else {
    dialog.title = "新增角色";
  }
}

// 提交角色表单
function handleSubmit() {
  addRequestRef.value.validate((valid: any) => {
    if (valid) {
      // const checkedMenuIds: number[] = refmenuSelect.value.getPerms();
      loading.value = true;
      const roleId = formData.id;
      if (roleId) {
        // RoleApi.update(roleId, { ...formData, menuIdList: checkedMenuIds })
        RoleApi.update(roleId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        delete formData.id;

        RoleApi.add({ ...formData, menuIdList: [] })
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  addRequestRef.value?.resetFields();
  addRequestRef.value?.clearValidate();
  refmenuSelect.value?.reset();
  formData.id = undefined;
  formData.sort = 1;
  formData.status = 1;
  dialog.visible = false;
}

// 删除角色
function handleDelete(roleId?: number) {
  const roleIds = [roleId || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      RoleApi.delete({ id: roleId ?? null })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

interface typeRoute extends RouteVO {
  label: string | number;
  value: string | number;
  children: typeRoute[];
}

function returnMenu(menu) {
  return menu.map((v) => {
    return {
      ...v,
      label: v.title,
      value: v.menuId,
      children: v.children ? returnMenu(v.children) : [],
    };
  });
}

const casher_windows_menus = ref<CashMenu[]>([]);
//获取收银机菜单
async function getCashMenus() {
  const res = await MenuAPI.getCashMenus();
  console.log(res);
  casher_windows_menus.value = res;
}
// 获取所有的菜单
async function getMenuPermOptions() {
  // let arr = shopUser.userInfo.account === "admin" ? await MenuAPI.getList() : await MenuAPI.getRoutes();
  let arr = await MenuAPI.getList();
  menuPermOptions.value = returnMenu(arr);
}
getMenuPermOptions();
getCashMenus();

const adminMenuIdList = ref<number[]>([]);
// 打开分配菜单菜单弹窗
async function handleOpenAssignPermDialog(row: SysRole) {
  const roleId = row.id;
  dialog.row = row;
  if (roleId) {
    assignPermDialogVisible.value = true;
    loading.value = true;
    checkedRole.value.id = roleId;
    checkedRole.value.name = row.name as string;
    getMenuIds(roleId);
  }
}

// 回显角色已拥有的菜单
function getMenuIds(roleId: number) {
  roleId = roleId ? roleId : dialog.row.id;
  if (!roleId) {
    return;
  }
  RoleApi.getMenu(roleId, platformType.value)
    .then((data) => {
      if (platformType.value == 0) {
        const checkedMenuIds = data;
        adminMenuIdList.value = data;
        // checkedMenuIds.forEach((menuId) => permTreeRef.value!.setChecked(menuId, true, false));
      }
      if (platformType.value == 1) {
        cashMenuIdList.value = data;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

// 分配菜单菜单提交
function handleAssignPermSubmit() {
  const roleId = checkedRole.value.id;
  const name = checkedRole.value.name;
  if (roleId) {
    const checkedMenuIds: number[] = permTreeRef
      .value!.getCheckedNodes(false, true)
      .map((node: any) => node.value);

    loading.value = true;
    RoleApi.update(roleId, {
      name,
      adminMenuIdList: checkedMenuIds,
      cashMenuIdList: cashMenuIdList.value.filter((id) =>
        casher_windows_menus.value.find((v) => v.menuId == id)
      ),
    })
      .then(() => {
        ElMessage.success("分配菜单成功");
        assignPermDialogVisible.value = false;
        handleResetQuery();
      })
      .finally(() => {
        loading.value = false;
      });
  }
}

// 展开/收缩 菜单菜单树
function togglePermTree() {
  isExpanded.value = !isExpanded.value;
  if (permTreeRef.value) {
    Object.values(permTreeRef.value.store.nodesMap).forEach((node: any) => {
      if (isExpanded.value) {
        node.expand();
      } else {
        node.collapse();
      }
    });
  }
}
function editTogglePermTree() {
  isExpanded.value = !isExpanded.value;
  if (permTreeRef.value) {
    Object.values(permTreeRef.value.store.nodesMap).forEach((node: any) => {
      if (isExpanded.value) {
        node.expand();
      } else {
        node.collapse();
      }
    });
  }
}

// 菜单筛选
watch(permKeywords, (val) => {
  permTreeRef.value!.filter(val);
});

watch(
  () => assignPermDialogVisible.value,
  (val) => {
    if (!val) {
      permTreeRef.value.setCheckedKeys([]);
      platformType.value = 0;
      cashMenuIdList.value = [];
      adminMenuIdList.value = [];
    }
  }
);

function handlePermFilter(
  value: string,
  data: {
    [key: string]: any;
  }
) {
  if (!value) return true;
  return data.label.includes(value);
}

// 父子菜单节点是否联动
function handleparentChildLinkedChange(val: any) {
  parentChildLinked.value = val;
}

onMounted(() => {
  handleQuery();
});
</script>
<style scoped lang="scss">
.cashMenuIdList {
  position: absolute;
  box-sizing: border-box;
  padding: var(--el-drawer-padding-primary);
  inset: 0;
  background-color: #fff;
  z-index: 2;
  transition: all 0.3s ease-in-out;
}
</style>