<template>
  <div class="gl-page-content-grey-full">
    <div class="content">
      <FileTree ref="fileTreeRef" :api="dataListDirApi" @choseNode="choseNodeFun" @updateNav="updateNavFun">
        <template #table>
          <!-- :head="headData" -->

          <BaseTable
            tableName="USER_FILE_PERMISSION"
            ref="baseTableRef"
            :api="getUserFilePermissionFn"
            showCheckbox
            :params="{
              parentPath: parentPath,
              fileName: currentTreeNodeInfo.originalName,
              userId: '',
              // type: 0,
              userName: filterUserName,
              fileId: currentTreeNodeInfo.id,

            }"
          >
            <template #leftOptions>
              <div>
                <el-form :model="userRoleForm" class="user-role-form">
                  <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="filterUserPermissionFn">
                          <search />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item class="user-role-form-item">
                    <el-button type="primary" @click="saveUserPermissionFn">保存</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </template>
            <template #read="{ row }">
              <el-checkbox v-model="row.read" label="" />
            </template>
            <template #write="{ row }">
              <el-checkbox v-model="row.write" label="" />
            </template>
            <template #delete="{ row }">
              <el-checkbox v-model="row.delete" label="" />
            </template>
            <template #input="{ row }">
              <el-checkbox v-model="row.input" label="" />
            </template>
            <template #output="{ row }">
              <el-checkbox 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 {
  dataListDirApi,
  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>({});

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 + '/', '');
  console.log(data, 'data');

  // const res = await getUserFilePermissionFn({
  //   current: 1,
  //   size: 10,
  // });
  // tableData.value = res.data.data;
  // if (baseTableRef.value) {
  //   baseTableRef.value.setDataFun(tableData.value);
  // }

};

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

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

  const permissionLevel: any = binaryToDecimalFn(userPermissionNum);

  const str = ConversionStrToNum(permissionLevel);

  console.log(userPermissionNum, 'userPermissionNum');
  console.log(permissionLevel, 'userPermissionNum');
  console.log(str, 'str');

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

  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;
  }

  console.log(checkUserList, 'checkUserList');

  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 updateUserFilePermissionFn(param);

  await filterUserPermissionFn();

};

/**
 * 二进制转化为十进制
 * @param binary 二进制字符串
 */
const binaryToDecimalFn = (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 filterUserPermissionFn = async () => {

  filterUserName.value = filterUserNameCopy.value;
  // const res = await getUserFilePermissionFn({
  //   current: 1,
  //   size: 10,
  // });
  // tableData.value = res.data.data;
  // if (baseTableRef.value) {
  //   baseTableRef.value.setDataFun(tableData.value);
  // }
};

/**
 * 获取用户对文件的综合权限
 */
const getUserFilePermissionFn = async (data: any) => {

  if (!currentTreeNodeInfo.value.id) {
    return;
  }
  const params: any = {
    parentPath: parentPath.value,
    fileName: currentTreeNodeInfo.value.originalName,
    userId: '',
    // type: 0,
    userName: filterUserName.value,
    fileId: currentTreeNodeInfo.value.id,
  };

  if (data) {
    params.current = data.current;
    params.size = data.size;
  }

  const res: any = await queryUserFilePermissionApi(params);
  if (res && res.code === 200) {
    console.log(res, 'resresres');
    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;
  } else {

  }

};

/**
 * 更新用户文件权限信息
 */
const updateUserFilePermissionFn = 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%;

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