<template>
  <div class="gyq_container">
    <div class="content">
      <div class="row">
        <el-button type="primary" @click="addTempateDialogRef.show(1)">添加</el-button>
      </div>
      <div class="row mt14">
        <el-table :data="tableData.list" v-loading="tableData.loading" stripe border row-key="id"
          :tree-props="{ children: 'children' }" default-expand-all style="width: 100%;">
          <el-table-column label="ID" prop="id" width="80"></el-table-column>
          <el-table-column label="模版名称" prop="name"></el-table-column>
          <el-table-column label="启用状态" prop="isEnable" width="120">
            <template v-slot="scope">
              <el-switch v-model="scope.row.isEnable" :active-value="1" :inactive-value="0"
                @change="isEnableChange($event, scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="排序值" prop="sort"></el-table-column>
          <el-table-column label="创建时间" prop="createTime"></el-table-column>
          <!-- <el-table-column label="操作人" prop=""></el-table-column> -->
          <el-table-column label="操作" width="250">
            <template v-slot="scope">
              <el-button link type="success" @click="handleOpenAssignPermDialog(scope.row)"
                v-if="scope.row.pid !== null">分配权限</el-button>
              <el-button link type="primary" @click="addTempateDialogRef.show(2, scope.row)" v-else>添加角色</el-button>
              <el-button link type="primary" @click="addTempateDialogRef.show(2, scope.row, 2)"
                v-if="scope.row.pid">编辑</el-button>
              <el-button link type="primary" @click="addTempateDialogRef.show(1, scope.row, 2)" v-else>编辑</el-button>
              <el-popconfirm title="确认要删除吗？" @confirm="deleteHandle(scope.row)">
                <template #reference>
                  <el-button type="danger" link>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- <div class="row mt14">
        <el-pagination v-model:current-page="tableData.page" v-model:page-size="tableData.size"
          :page-sizes="[10, 30, 50, 100]" background layout="total" :total="tableData.total" />
      </div> -->
    </div>
    <!-- 添加模板/角色 -->
    <addTempateDialog ref="addTempateDialogRef" @success="roleTemplateListAjax" />
    <!-- 分配菜单弹窗 -->
    <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>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import addTempateDialog from './components/addTempateDialog.vue';
import MenuAPI from "@/api/account/menu";
import RoleApi from "@/api/account/role";
import { roleTemplateList, roleTemplateDel, roleTemplateAdd } from '@/api/account/roleTemplate'

const addTempateDialogRef = ref(null)

const tableData = reactive({
  loading: false,
  page: 1,
  size: 10,
  total: 0,
  list: []
})

const assignPermDialogVisible = ref(false)

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
  row: {},
});

const checkedRole = ref({})

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

// 打开分配菜单菜单弹窗
async function handleOpenAssignPermDialog(row) {
  const roleId = row.roleId;
  dialog.row = row;
  if (roleId) {
    assignPermDialogVisible.value = true;
    loading.value = true;
    checkedRole.value.id = roleId;
    checkedRole.value.name = row.name;
    getMenuIds(roleId);
  }
}

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

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

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

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

//获取收银机菜单
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);
}

const adminMenuIdList = ref([]);

function handlePermFilter(value, data) {
  if (!value) return true;
  return data.label.includes(value);
}

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

// 回显角色已拥有的菜单
function getMenuIds(roleId) {
  console.log('回显角色已拥有的菜单===', roleId);


  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 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([]);

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

const loading = ref(false)
const permTreeRef = ref(null)

// 分配菜单菜单提交
async function handleAssignPermSubmit() {
  try {
    const roleId = checkedRole.value.id;
    const name = checkedRole.value.name;

    console.log(roleId, name);

    if (roleId) {
      const checkedMenuIds = permTreeRef
        .value.getCheckedNodes(false, true)
        .map((node) => 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;
          roleTemplateListAjax();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  } catch (error) {
    console.log(error);
  }
}

// 获取角色模板列表
async function roleTemplateListAjax() {
  try {
    tableData.loading = true
    const res = await roleTemplateList()
    tableData.list = res
    tableData.total = res.length
    // console.log('tableData.list===', JSON.stringify(tableData.list));
    // console.log('tableData.list===', tableData.list);
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    tableData.loading = false
  }, 500);
}

// 展开懒加载
async function loadChildNodes(row, treeNode, resolve) {
  try {
    const res = await roleTemplateList({ pid: row.id })
    resolve(res)
  } catch (error) {
    console.log(error);
  }
}

// 删除
async function deleteHandle(row) {
  try {
    await roleTemplateDel(row.id)
    ElNotification({
      title: '注意',
      message: '已删除',
      type: 'success'
    })

    roleTemplateListAjax()
  } catch (error) {
    console.log(error);
  }
}

// 状态变化
async function isEnableChange(e, row) {
  console.log('isEnableChange.e===', e);
  console.log('isEnableChange.row===', row);
  try {
    await roleTemplateAdd(row)
    roleTemplateListAjax()
  } catch (error) {
    console.log(error);
  }
}

onMounted(() => {
  getMenuPermOptions();
  getCashMenus();
  roleTemplateListAjax()
})

</script>

<style scoped lang="scss">
.gyq_container {
  width: 100%;
  padding: 14px;
}

.content {
  border-radius: 8px;
  background-color: #fff;
  padding: 14px;
}

.row {
  &.mt14 {
    margin-top: 14px;
  }
}

.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>