<template>

  

  <BasicDrawer v-bind="$attrs" @register="registerDrawer" width="650px" destroyOnClose showFooter>
    <template #title>
      区域标签配置
    </template>

    <div>
      <a-card title="基础功能">
        <a-row  v-for="(item,index) in treeData" :key="index">  
          <template v-if="item.code === 'hldy' && areaFlag == 1">
              <a-col :span="24" v-for="itemOne in item.children">
                <a-checkbox :checked="true"  disabled style="margin-top:10px;">{{ itemOne.slotTitle }}</a-checkbox>
              </a-col>
          </template>
          <template v-else-if="item.code === 'kf' && areaFlag == 3">
              <a-col :span="24" v-for="itemOne in item.children">
                <a-checkbox :checked="true"  disabled style="margin-top:10px;">{{ itemOne.slotTitle }}</a-checkbox>
              </a-col>
          </template>
        </a-row>
      </a-card>

      <a-card title="扩展功能" style="margin-top: 20px;">
        <a-row  v-for="(item,index) in treeData" :key="index">  
          <template v-if="item.code === 'kzgn'">
            <a-checkbox-group v-model:value="formData.kzgn">
              <a-col :span="24" v-for="itemOne in item.children">
                <a-checkbox :value="itemOne.key" style="margin-top:10px;">{{ itemOne.slotTitle }}</a-checkbox>
              </a-col>
            </a-checkbox-group>
          </template>
        </a-row>
      </a-card>
    </div>


    <template #footer>
      <a-button @click="closeDrawer">取消</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">保存</a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, reactive, computed, unref, onMounted } from 'vue';
  import { BasicDrawer, useDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { PopConfirmButton } from '/@/components/Button';
  import { queryTreeListForRole, queryRolePermission, saveRolePermission } from '../NuBaseInfo.api';
  import { useI18n } from "/@/hooks/web/useI18n";
  import { ROLE_AUTH_CONFIG_KEY } from '/@/enums/cacheEnum';
  const emit = defineEmits(['register']);
  //树的信息
  const treeData = ref<TreeItem[]>([]);
  //树的全部节点信息
  const allTreeKeys = ref([]);
  //树的选择节点信息
  const checkedKeys = ref<any>([]);
  const defaultCheckedKeys = ref([]);
  //树的选中的节点信息
  const selectedKeys = ref([]);
  const roleId = ref('');
  const areaFlag = ref('');
  //树的实例
  const treeRef = ref(null);
  const loading = ref(false);

const formData = reactive<Record<string, any>>({
  id: '',
  jcgn: '',
  nuId: '',
  kzgn: '',
});
  //展开折叠的key
  const expandedKeys = ref<any>([]);
  //父子节点选中状态是否关联 true不关联，false关联
  const checkStrictly = ref<boolean>(false);
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await reset();
    setDrawerProps({ confirmLoading: false, loading: true });
    roleId.value = data.roleId;
    areaFlag.value = data.areaFlag;
    console.log("🚀 ~ areaFlag.value:", areaFlag.value)
    //初始化数据
    const roleResult = await queryTreeListForRole();
    // update-begin--author:liaozhiyang---date:20240228---for：【QQYUN-8355】角色权限配置的菜单翻译
    treeData.value = translateTitle(roleResult.treeList);
    // update-end--author:liaozhiyang---date:20240228---for：【QQYUN-8355】角色权限配置的菜单翻译
    allTreeKeys.value = roleResult.ids;
    // update-begin--author:liaozhiyang---date:20240531---for：【TV360X-590】角色授权弹窗操作缓存
    const localData = localStorage.getItem(ROLE_AUTH_CONFIG_KEY);
    if (localData) {
    } else {
      expandedKeys.value = roleResult.ids;
    }
    // update-end--author:liaozhiyang---date:20240531---for：【TV360X-590】角色授权弹窗操作缓存
    //初始化角色菜单数据
    const permResult = await queryRolePermission({ nuId: unref(roleId) });
    formData.kzgn = permResult;
    // if(areaFlag.value == 1){
    //   var jcgn = "";
    //   treeData.value.forEach(function(item) {
    //     if(item.code == 'hldy'){
    //       var list = item.children;
    //       list.forEach(function(itemOne) {
    //           jcgn = jcgn+itemOne.key+",";
    //       });
    //     }
    //   });
    //   formData.jcgn = jcgn.substring(0,jcgn.length-1);
    // }else if(areaFlag.value == 3){
    //   var jcgn = "";
    //   treeData.value.forEach(function(item) {
    //     if(item.code == 'kf'){
    //       var list = item.children;
    //       list.forEach(function(itemOne) {
    //           jcgn = jcgn+itemOne.key+",";
    //       });
    //     }
    //   });
    //   formData.jcgn = jcgn.substring(0,jcgn.length-1);
    // }
    checkedKeys.value = permResult;
    defaultCheckedKeys.value = permResult;
    setDrawerProps({ loading: false });
  });
  /**
  * 2024-02-28
  * liaozhiyang
  * 翻译菜单名称
   */
  function translateTitle(data) {
    if (data?.length) {
      data.forEach((item) => {
        if (item.slotTitle) {
          const { t } = useI18n();
          if (item.slotTitle.includes("t('") && t) {
            item.slotTitle = new Function('t', `return ${item.slotTitle}`)(t);
          }
        }
        if(item.code.indexOf('kzgn') > -1){
          item.checked = false;
        }else{
          item.checked = true;
        }
        if (item.children?.length) {
          translateTitle(item.children);
        }
      });
    }
    return data;
  }

  /**
   * 数据重置
   */
  function reset() {
    treeData.value = [];
    allTreeKeys.value = [];
    checkedKeys.value = [];
    defaultCheckedKeys.value = [];
    selectedKeys.value = [];
    roleId.value = '';
  }
  /**
   * 提交
   */
  async function handleSubmit(exit) {
  var kzgn = formData.kzgn;

    let params = {
      roleId: unref(roleId),
      permissionIds: unref(kzgn).join(','),
      lastpermissionIds: unref(defaultCheckedKeys).join(','),
    };
    //update-begin-author:taoyan date:2023-2-11 for: issues/352 VUE角色授权重复保存
    if(loading.value===false){
      await doSave(params)
    }else{
      console.log('请等待上次执行完毕!');
    }
    if(exit){
      closeDrawer();
    }else{
      const permResult = await queryRolePermission({ nuId: unref(roleId) });
      defaultCheckedKeys.value = permResult;
    }
  }
  
  // VUE角色授权重复保存 #352
  async function doSave(params) {
    console.log("🚀 ~ doSave ~ params:", params)
    loading.value = true;
    await saveRolePermission(params);
    setTimeout(()=>{
      loading.value = false;
    }, 500)
  }
  //update-end-author:taoyan date:2023-2-11 for: issues/352 VUE角色授权重复保存

</script>

<style lang="less" scoped>
  /** 固定操作按钮 */
  .jeecg-basic-tree {
    position: absolute;
    width: 618px;
  }
  //update-begin---author:wangshuai ---date:20230202  for：抽屉弹窗标题图标下拉样式------------
  .line {
    height: 1px;
    width: 100%;
    border-bottom: 1px solid #f0f0f0;
  }
  .more-icon {
    font-size: 20px !important;
    color: black;
    display: inline-flex;
    float: right;
    margin-right: 2px;
    cursor: pointer;
  }
  :deep(.jeecg-tree-header) {
    border-bottom: none;
  }
  //update-end---author:wangshuai ---date:20230202  for：抽屉弹窗标题图标下拉样式------------
</style>
