<template>
  <div class="gl-page-content-grey-full">
    <div class="content">
      <FileTree
        ref="fileTreeRef"
        :api="dataTreeListDirApi"
        :param="{
          dirType,
        }"
        @choseNode="choseNodeFun"
        @updateNav="updateNavFun"
      >
        <template #options>
          <div class="options">
            <el-select v-model="dirType" @change="changedirTypeFun">
              <el-option
                v-for="item in dirTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </template>
        <template #table>
          <BaseTable
            tableName="USER_FILE_PERMISSION"
            ref="baseTableRef"
            :api="getUserFilePermissionFun"
            showCheckbox
            fullHeight
            :params="{
              parentPath: parentPath,
              fileName: currentTreeNodeInfo.originalName,
              userId: '',
              userName: filterUserName,
              fileId: currentTreeNodeInfo.id,
            }"
          >
            <template #leftOptions>
              <div>
                <el-form :model="userRoleForm" class="user-role-form" @submit.prevent>
                  <el-form-item class="user-role-form-item">
                    <el-checkbox v-model="userRoleForm.read" label="读" />
                    <el-checkbox v-model="userRoleForm.write" label="写" />
                    <el-checkbox v-model="userRoleForm.delete" label="删除" />
                    <el-checkbox v-model="userRoleForm.input" label="导入" />
                    <el-checkbox v-model="userRoleForm.output" label="导出" />
                  </el-form-item>
                  <el-form-item class="user-role-form-item">
                    <el-input v-model="filterUserNameCopy" placeholder="请输入筛选内容">
                      <template #suffix>
                        <el-icon
                          class="el-input__icon current-icon"
                          @click="filterUserPermissionFun"
                        >
                          <search />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item class="user-role-form-item">
                    <el-button type="" @click="filterUserPermissionFun">搜索</el-button>

                    <el-button type="primary" @click="saveUserPermissionFun">保存</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </template>
            <template #read="{ row }">
              <el-checkbox disabled v-model="row.read" label="" />
            </template>
            <template #write="{ row }">
              <el-checkbox disabled v-model="row.write" label="" />
            </template>
            <template #delete="{ row }">
              <el-checkbox disabled v-model="row.delete" label="" />
            </template>
            <template #input="{ row }">
              <el-checkbox disabled v-model="row.input" label="" />
            </template>
            <template #output="{ row }">
              <el-checkbox disabled v-model="row.output" label="" />
            </template>
          </BaseTable>
        </template>
      </FileTree>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import FileTree from '@/components/common/fileTree/index.vue';
import {
  dataTreeListDirApi,
  queryUserFilePermissionApi,
  updateUserFilePermissionApi,
} from '@/api/data/data';
import { ElMessage } from 'element-plus';

const fileTreeRef = ref<any>();
const baseTableRef = ref<any>();
const navList = ref<any>([]);
const tableData = ref<any>([]);
const filterUserName = ref<string>('');
const filterUserNameCopy = ref<string>('');
const currentTreeNodeInfo = ref<any>({});

const dirType = ref(1);

const dirTypeList = ref<any>([
  {
    label: '知识库',
    value: 1,
  },
  {
    label: '项目数据',
    value: 2,
  },
]);

//
const changedirTypeFun = async () => {
  currentTreeNodeInfo.value = {};
  await fileTreeRef.value.reloadFun();
  await baseTableRef.value.setDataFun([]);
};

tableData.value = [
  // {
  //   id: 1,
  //   userName: '张三',
  //   read: true,
  //   write: false,
  //   delete: false,
  //   input: false,
  //   output: false,
  // },
  // {
  //   id: 2,
  //   userName: '李四',
  //   read: true,
  //   write: true,
  //   delete: true,
  //   input: true,
  //   output: true,
  // },
  // {
  //   id: 3,
  //   userName: '王五',
  //   read: true,
  //   write: true,
  //   delete: true,
  //   input: true,
  //   output: true,
  // },
];

const userRoleForm = reactive<any>({
  read: true,
  write: false,
  delete: false,
  input: false,
  output: false,
});

const parentPath = ref<any>('');
const choseNodeFun = async (data: any) => {
  currentTreeNodeInfo.value = data;
  parentPath.value = currentTreeNodeInfo.value.objectKey.replace(
    currentTreeNodeInfo.value.originalName + '/',
    ''
  );
};

const updateNavFun = (data: any) => {
  navList.value = data;
};

/**
 * 保存用户权限变更
 */
const saveUserPermissionFun = async () => {
  let userPermissionNum: any = [];
  for (const key in userRoleForm) {
    userPermissionNum.push(Number(userRoleForm[key]));
  }
  userPermissionNum = userPermissionNum.reverse().join('');

  const permissionLevel: any = binaryToDecimalFun(userPermissionNum);

  // 判断是否选择了文件进行授权

  if (!currentTreeNodeInfo.value.id) {
    ElMessage.warning('未选择文件进行用户权限更新！');
    return;
  }

  // 最低用户有看的权限

  if (userRoleForm.read === false) {
    ElMessage.warning('用户最低需要有查看权限！');
    return;
  }

  // 判断是否勾选了用户
  const checkUserList = baseTableRef.value.tableRef.getCheckboxRecords() || [];
  if (!checkUserList.length) {
    ElMessage.warning('未选择用户进行权限更新！');
    return;
  }

  const obj: any = {};

  for (let i = 0; i < checkUserList.length; i++) {
    obj[checkUserList[i].userId || checkUserList[i].id] = permissionLevel;
  }

  const param = {
    permission: permissionLevel,
    userPermissions: obj,
  };

  await updateUserFilePermissionFun(param);

  await baseTableRef.value.resetFun();
  // await filterUserPermissionFun();
};

/**
 * 二进制转化为十进制
 * @param binary 二进制字符串
 */
const binaryToDecimalFun = (binary: string) => {
  return parseInt(binary, 2);
};

/**
 * 十进制转二进制
 * @param num
 */
const ConversionStrToNum = (num: any) => {
  const result = num.toString(2);

  let str = '';
  for (let i = result.length; i < 5; i++) {
    str = str + 0;
  }
  return str + result;
};
/**
 * 筛选过滤表单内容
 */
const filterUserPermissionFun = async () => {
  filterUserName.value = filterUserNameCopy.value;
};

/**
 * 获取用户对文件的综合权限
 */
const getUserFilePermissionFun = async (data: any) => {
  const params: any = {
    ...data,
  };

  if (!params.fileId) {
    return {
      code: 500,
    };
  }

  const res: any = await queryUserFilePermissionApi(params);
  if (res && res.code === 200) {
    res.data.data = res.data.data.map((item: any) => {
      const permissionStr = ConversionStrToNum(item.permission);
      return {
        ...item,
        nickname: item.nickname || item.userName,
        read: true,
        write: permissionStr[3] === '1',
        delete: permissionStr[2] === '1',
        input: permissionStr[1] === '1',
        output: permissionStr[0] === '1',
      };
    });

    // return res.data;
    return res;
  }
};

/**
 * 更新用户文件权限信息
 */
const updateUserFilePermissionFun = async (data: any) => {
  const res: any = await updateUserFilePermissionApi({
    parentPath: currentTreeNodeInfo.value.objectKey.replace(
      currentTreeNodeInfo.value.originalName + '/',
      ''
    ),
    fileId: currentTreeNodeInfo.value.id,
    fileName: currentTreeNodeInfo.value.originalName,
    userId: '',
    jobNumber: '',
    userName: '',
    type: 0,
    effectiveTime: '',
    permission: data.permission,
    userPermissions: data.userPermissions,
  });
  if (res.code === 200) {
    ElMessage.success('用户权限更新成功！');
  } else {
  }
};

onMounted(() => {
  if (baseTableRef.value) {
    baseTableRef.value.setDataFun(tableData.value);
  }
});
</script>

<style lang="scss" scoped>
.gl-page-content-grey-full {
  .content {
    height: 100%;
    .options {
      margin-bottom: var(--margin-small);
    }
    .user-role-form {
      display: flex;
      .user-role-form-item {
        margin-bottom: 0 !important;
        margin-right: 30px;
        .responsive-input {
          width: 150px;
        }
      }
    }
  }
  .current-icon {
    cursor: pointer;
  }
}
</style>
