<template>
  <a-spin
    :spinning="spinning"
    :tip="tipContent"
  >
    <a-form
      :model="form"
      ref="formRef"
      label-align="left"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-row>
        <a-col :span="24">
          <a-form-item
            label="角色名称"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 12 }"
            name="roleName"
            required
            :rules="[{ required: true, message: '请输角色名称' }]"
          >
            <a-input
              v-model:value="form.roleName"
              placeholder="请输角色名称"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item
            label="角色描述"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 12 }"
            name="roleDescription"
          >
            <a-input
              v-model:value="form.roleDescription"
              placeholder="请输入角色描述"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item
            label="菜单权限配置"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 21 }"
            name="roleDescription"
          >
            <a-tabs v-model:activeKey="activeKey">
              <a-tab-pane
                key="1"
                tab="运营后台"
              >
                <div style="border: solid 1px #ddd;margin-top: -15px;">
                  <a-tree
                    v-if="treeDataByWeb.length"
                    defaultExpandAll
                    v-model:checkedKeys="checkedKeysByWeb"
                    @check="checkNodeByWeb"
                    v-model:tree-data="treeDataByWeb"
                    checkable
                  >
                    <template #title="{ description }">
                      {{ description }}
                    </template>
                  </a-tree>
                </div>

              </a-tab-pane>
              <a-tab-pane
                key="2"
                tab="运维小程序"
                force-render
              >
                <div style="border: solid 1px #ddd;margin-top: -15px;">
                  <a-tree
                    v-if="treeDataByApplet.length"
                    v-model:checkedKeys="checkedKeysByApplet"
                    @check="checkNodeByApplet"
                    :tree-data="treeDataByApplet"
                    defaultExpandAll
                    checkable
                  >
                    <template #title="{ description }">
                      {{ description }}
                    </template>
                  </a-tree>
                </div>
              </a-tab-pane>
            </a-tabs>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>
  
<script setup>
import { ref } from 'vue'
import { callUser } from '@/apis/call.js'
import { message } from 'ant-design-vue'
import _, { constant } from 'lodash'

const formRef = ref();
const form = ref({});
const activeKey = ref("1")
const checkedKeysByWeb = ref([])
const checkedKeysByApplet = ref([])
const treeDataByWeb = ref([])
const treeDataByApplet = ref([])
const treeDataList = ref([])
const roleIdRef = ref(null);
const isAdd = ref(true);
const spinning = ref(false);
const tipContent = ref("加载中...");

const openForm = (params = {}) => {
  isAdd.value = true;
  form.value = { ...params }
  loadPermissionsList(params['roleId']);
};

const loadPermissionsList = (roleId = null) => {
  callUser("/permissions/list", {}, "get").then((res) => {
    if (res.code != 200) {
      message.error(res.message)
      treeDataByWeb.value = []
      treeDataByApplet.value = []
      return
    }
    const dataList = res.data.map((item) => {
      return { ...item, key: item.permId }
    })
    treeDataList.value = dataList;
    const newDataListByWeb = buildTreeWithChildren(dataList, 1)
    const newDataList = buildTreeWithChildren(dataList, 2)
    treeDataByWeb.value = [{ description: "全部", key: "all", children: [...newDataListByWeb] }]
    treeDataByApplet.value = [{ description: "全部", key: "all", children: [...newDataList] }]
    if (roleId) {
      isAdd.value = false;
      roleIdRef.value = roleId
      callUser("/rolePermissions/getRolePermissionsByRoleId/" + roleId, {}, "get").then((res) => {
        if (res.code == 200) {
          const webKeys = res.data.filter(item => item['permType'] == "1").map(item => {
            return item['permId']
          });
          const appletKeys = res.data.filter(item => item['permType'] == "2").map(item => {
            return item['permId']
          });
          checkedKeysByWeb.value = webKeys;
          checkedKeysByApplet.value = appletKeys;
        }
      })
    } else {
      callOperate("/ebikesysrcostset/createSnowflakeId", {}, "get").then(res => {
        if (res.code == 200) {
          roleIdRef.value = res.data;
        }
      })
    }
  });
}

const checkNodeByWeb = (checkKeys, nodes) => {
  const checkNodes = nodes.checkedNodes.filter(item => item['key'] != "all")
  const leafKeys = getLeafKeys(checkNodes);
  checkedKeysByWeb.value = leafKeys
}

const checkNodeByApplet = (checkKeys, nodes) => {
  const checkNodes = nodes.checkedNodes.filter(item => item['key'] != "all")
  const leafKeys = getLeafKeys(checkNodes);
  checkedKeysByApplet.value = leafKeys
}

const getLeafKeys = (nodes) => {
  let leafKeys = [];
  nodes.forEach(node => {
    if (!node.children || node.children.length === 0) {
      leafKeys.push(node.key);
    } else {
      getLeafKeys(node.children)
    }
  });
  return leafKeys;
};

const buildTreeWithChildren = (data, where) => {
  const map = new Map();
  const roots = [];
  data.forEach(item => {
    map.set(item.permId, { ...item });
  });
  data.forEach(item => {
    if (item['permType'] == where) {
      const child = map.get(item.permId);
      child.code = child.permCode;
      if (item.parentId === null || item.parentId === undefined) {
        roots.push(child);
      } else {
        const parent = map.get(item.parentId);
        if (parent) {
          parent.children = parent.children || [];
          child.code = child.permCode.replace(parent.permCode + ".", '');
          parent.children.push(child);
        } else {
          roots.push(child);
        }
      }
    }
  });
  return roots;
}

const formSave = (callBack) => {
  formRef.value.validate().then((res) => {
    tipContent.value = "保存中..."
    spinning.value = true;
    let url = "rolePermissionsAdd";
    if (!isAdd.value) {
      url = "rolePermissionsUpdate"
    }
    isAdd.value = false;
    const params = _.cloneDeep(form.value);
    params['roleId'] = roleIdRef.value;
    params['rolePermissions'] = []
    checkedKeysByWeb.value.map(item => {
      params['rolePermissions'].push({ permId: item })
    })
    checkedKeysByApplet.value.map(item => {
      params['rolePermissions'].push({ permId: item })
    })
    callUser("/roles/" + url, params).then((res) => {
      if (res.code == 200) {
        message.success(res.message)
        if (callBack) {
          res.data = params;
          callBack(res);
        }
      } else {
        message.error(res.message)
        spinning.value = false;
      }
    })
  });
};

const resetAll = (callBack) => {
  formRef.value.resetFields();
  if (callBack) {
    callBack(true, form.value);
  }
}

defineExpose({ openForm, formSave, resetAll });
</script>
  