<template>
  <div class="guns-layout">
    <div class="guns-layout-sidebar p-t-12 bgColor" style="width: 292px">
      <div class="sidebar-content">
        <package-tree @treeSelect="treeSelect"></package-tree>
      </div>
    </div>
    <div class="guns-layout-content" style="width: calc(100% - 292px)">
      <div class="guns-layout">
        <div class="guns-layout-content-application">
          <div class="content-mian">
            <div class="content-mian-body">
              <div class="table-content">
                <a-spin :spinning="authLoading" :delay="100">
                  <div v-if="packageId && permissionData" class="use-content">
                    <div class="content-header">
                      <a-checkbox v-model:checked="permissionData.checked" @click="el => allPermissionChange(el, permissionData)"
                        >所有权限</a-checkbox
                      >
                    </div>
                    <div class="content-bottom">
                      <div class="bottom-item" v-for="(perItem, perIndex) in permissionData.appPermissionList" :key="perIndex">
                        <div class="bottom-item-name">
                          <span class="title">应用：{{ perItem.nodeName }}</span>
                          <a-checkbox v-model:checked="perItem.checked" @click="el => perItemChange(el, perItem)">全选</a-checkbox>
                        </div>
                        <div class="table">
                          <a-table
                            :dataSource="perItem.children"
                            :columns="columns"
                            v-model:expandedRowKeys="expandedRowKeys"
                            :pagination="false"
                            :checkStrictly="true"
                            rowKey="nodeId"
                            bordered
                            size="small"
                          >
                            <template #bodyCell="{ column, record }">
                              <template v-if="column.dataIndex === 'page'">
                                <a-checkbox
                                  v-model:checked="record.checked"
                                  v-if="record.leafFlag"
                                  @change="pageChange($event, record, perItem)"
                                >
                                  {{ record.nodeName }}
                                </a-checkbox>
                                <span v-else>{{ record.nodeName }}</span>
                              </template>
                              <template v-else-if="column.dataIndex === 'use' && record.functionList">
                                <a-checkbox
                                  v-model:checked="chlItem.checked"
                                  @change="useChange($event, chlItem, perItem)"
                                  v-for="chlItem in record.functionList"
                                  :key="chlItem.nodeId"
                                >
                                  {{ chlItem.nodeName }}
                                </a-checkbox>
                              </template>
                            </template>
                          </a-table>
                        </div>
                      </div>
                    </div>
                  </div>
                  <a-empty v-show="!packageId && !permissionData" class="right-empty"></a-empty>
                </a-spin>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="TenantPackage">
import { message } from 'ant-design-vue/es';
import { ref } from 'vue';
import { PackageApi } from './api/PackageApi';
import PackageTree from './components/package-tree.vue';

defineOptions({
  name: 'TenantPackage'
});

// 功能包列表
const packageId = ref('');
// 功能列表数据
const permissionData = ref(null);
// 展开行
const expandedRowKeys = ref([]);
// 加载动画
const authLoading = ref(false);

// 表格配置
const columns = ref([
  {
    title: '页面',
    width: 200,
    dataIndex: 'page'
  },
  {
    title: '功能',
    dataIndex: 'use'
  }
]);

// 左侧树选中
const treeSelect = id => {
  packageId.value = id;
  if (id) {
    getBindPermission();
  } else {
    permissionData.value = null;
  }
};

// 获取功能包绑定的权限列表
const getBindPermission = () => {
  authLoading.value = true;
  PackageApi.getPackageAuth({ packageId: packageId.value })
    .then(res => {
      setData(res.appPermissionList);
      permissionData.value = res;
    })
    .finally(() => (authLoading.value = false));
};

const setData = arr => {
  if (arr?.length > 0) {
    arr.forEach(item => {
      if (item?.children?.length > 0) {
        expandedRowKeys.value.push(item.nodeId);
        setData(item.children);
      }
    });
  }
};

// 所有权限改变
const allPermissionChange = (el, data) => {
  setAndSaveValue(el, data, 'appPermissionList', true);
};

// 全选改变
const perItemChange = (el, data) => {
  setAndSaveValue(el, data, '', true, true);
};

// 页面选中改变
const pageChange = (el, data, perItem) => {
  setAndSaveValue(el, data, '', true, true, perItem);
};

// 功能改变
const useChange = (el, data, perItem) => {
  setAndSaveValue(el, data, '', false, true, perItem);
};

/**
 * 设置和保存值
 * @param {*} el 当前dom，获取选中状态
 * @param {*} data 当前行数据
 * @param {*} setName 子菜单的名称
 * @param {*} flag 是否改变子级的选中状态
 * @param {*} isPermissionData 是否改变所有数据的选中状态
 * @param {*} perItem 是否改变全选的状态
 */
const setAndSaveValue = (el, data, setName, flag, isPermissionData, perItem) => {
  data.checked = el.target.checked;
  const recordSelectList = flattenTree([perItem]);

  if (flag) {
    setCheckout(el.target.checked, setName ? data[setName] : [data]);
  }

  //全选
  if (perItem) {
    if (recordSelectList.find(item => item.checked == false)) {
      perItem.checked = false;
    } else {
      perItem.checked = true;
    }
  }

  //所有
  if (isPermissionData) {
    if (permissionData.value.appPermissionList.find(item => item.checked == false)) {
      permissionData.value.checked = false;
    } else {
      permissionData.value.checked = true;
    }
  }
  //保存
  savePermission(data);
};

const flattenTree = tree => {
  const result = [];
  function traverse(node) {
    if (node?.leafFlag) {
      result.push(node);
      if (node?.functionList && Array.isArray(node.functionList)) {
        result.push(...node.functionList);
      }
    }
    if (node?.children && Array.isArray(node.children)) {
      node.children.forEach(traverse);
    }
  }
  tree.forEach(traverse);
  return result;
};

// 保存功能权限
const savePermission = data => {
  authLoading.value = true;
  let params = {
    checked: data.checked,
    packageId: packageId.value,
    nodeId: data.nodeId ? data.nodeId : '',
    permissionNodeType: data.permissionNodeType
  };
  PackageApi.setPackagePermission(params)
    .then(res => {
      message.success(res.message);
    })
    .finally(() => (authLoading.value = false));
};

// 设置选中
const setCheckout = (checked, list) => {
  if (list && list.length > 0) {
    list.forEach(item => {
      item.checked = checked;
      if (item.functionList && item.functionList.length > 0) {
        setCheckout(checked, item.functionList);
      }
      if (item.children && item.children.length > 0) {
        setCheckout(checked, item.children);
      }
    });
  }
};
</script>

<style scoped lang="less">
.permission {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}
.right-empty {
  padding-top: 350px;
}
.use-content {
  width: 100%;
  height: 100%;
  .content-header {
    height: 22px;
  }
  .content-bottom {
    width: 100%;
    margin-top: 20px;
    overflow-y: auto;
    height: calc(100% - 32px);
    .bottom-item {
      margin-bottom: 20px;
      .bottom-item-name {
        .title {
          font-size: 16px;
          font-weight: bold;
          margin-right: 10px;
        }
      }
    }
  }
}
</style>
