<template>
  <el-drawer
    v-model="isDrawer"
    :width="width"
    placement="right"
    :title="title"
    @close="handleReset"
  >
    <el-form
      :model="formParams"
      :rules="rules"
      ref="formRef"
      label-placement="left"
      :label-width="80"
    >
      <el-form-item label="角色编码" prop="roleCode">
        <el-input
          placeholder="请输入角色编码"
          v-model="formParams.roleCode"
          :disabled="formParams.roleId ? true : false"
        />
      </el-form-item>

      <el-form-item label="角色名称" prop="roleName">
        <el-input placeholder="请输入角色名称" v-model="formParams.roleName" />
      </el-form-item>
      <el-form-item label="角色权限" prop="permissionIds">
        <div class="mark-left"></div>
        <el-card shadow="hover" class="permission-card">
          <div class="permission-name">场景权限</div>
          <el-space>
            <el-checkbox v-model:checked="isSpread" @change="packHandle">展开/收起</el-checkbox>
          </el-space>
          <el-divider />
          <div style="height: 25vh">
            <el-scrollbar>
              <el-tree
                ref="treeRef"
                node-key="code"
                :highlight-current="true"
                :data="treeData"
                :props="treeProps"
                @node-click="clickNode"
              />
            </el-scrollbar>
          </div>
        </el-card>
        <div style="position: relative; margin-top: 10px; width: 100%">
          <div class="mark-left"></div>
          <el-card shadow="hover" class="permission-card">
            <div class="permission-name">功能权限</div>
            <el-space>
              <el-checkbox v-model="isAll" @change="handleCheckAll">全选/全不选</el-checkbox>
            </el-space>
            <el-divider />
            <div style="height: 10vh">
              <el-scrollbar>
                <el-tree
                  ref="modeTreeRef"
                  show-checkbox
                  node-key="key"
                  :data="modeTreeData"
                  @check="checkedModeTree"
                />
              </el-scrollbar>
            </div>
          </el-card>
        </div>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" placeholder="请输入备注" v-model="formParams.remark" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-space>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" :loading="subLoading" @click="formSubmit">提交</el-button>
      </el-space>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted, nextTick, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import type { userFormParamsType } from './types';

  import { addRole, getFeaturePermissions, roleUserInfo, updateRole } from '@/api/system/role';
  import useScene from '@/views/system-config/scene-manage/use-scene';
  import { storeToRefs } from 'pinia';

  const sceneInfos = useScene();
  const { tableData } = storeToRefs(sceneInfos);
  const { getSceneDetail } = sceneInfos;

  // 默认功能权限全部勾选，有未勾选的添加至excludeFeaturePermissionMap中：[workdshopCode]: [permission数组]
  const featurePermissionMap = {};

  const rules = {
    roleCode: {
      required: true,
      message: '角色编码不能为空',
      trigger: 'blur',
    },
    roleName: {
      required: true,
      message: '角色名称不能为空',
      trigger: 'blur',
    },
  };

  const treeProps = { label: 'name' };

  const treeData = computed(() => {
    const newList: any[] = [];
    if (tableData.value && tableData.value.length) {
      for (let i = 0; i < tableData.value.length; i++) {
        const data = tableData.value[i];
        if (data.children && data.children.length) {
          const treeItem = {
            id: data.id,
            code: data.id,
            name: data.name,
            children: data
              .labelList!.map((item) => {
                return {
                  id: item.id,
                  code: item.code,
                  name: item.name,
                  children: data
                    .children!.filter((children) => children.sceneLabelId === item.id)
                    .map((children) => {
                      return {
                        id: children.id,
                        code: children.code,
                        name: children.name,
                        isShop: true,
                      };
                    }),
                };
              })
              .filter((label) => label.children.length),
          };
          newList.push(treeItem);
        }
      }
    }
    return newList;
  });

  const modeList = ref<{ key: number; label: string }[]>([]);

  const emit = defineEmits(['change']);

  const props = defineProps({
    title: {
      type: String,
      default: '添加角色',
    },
    width: {
      type: Number,
      default: 450,
    },
    permissionList: {
      type: Array,
    },
  });

  const defaultValueRef = () => ({
    roleId: null,
    roleName: '',
    roleCode: '',
    remark: '',
    permissions: [],
    permissionKeys: [],
  });

  const defaultTreeValueRef = () => ({
    roleId: null,
    roleName: '',
    roleCode: '',
    remark: '',
    permissionList: [],
    permissionKeys: [],
  });

  const message = ElMessage;
  const formRef: any = ref(null);
  const modeTreeRef = ref();
  const isDrawer = ref(false);
  const subLoading = ref(false);
  const isSpread = ref(false);
  const isAll = ref(false);
  const treeRef = ref();
  const expandedKeys = ref();
  const selectedNodeKey = ref<string>('');
  const modeTreeData = computed(() => (selectedNodeKey.value ? modeList.value : []));

  const formParams = ref<userFormParamsType>(defaultTreeValueRef());

  function clickNode(tree, nodeInfo, _, __) {
    console.log('tree', tree);
    console.log('nodeInfo', nodeInfo.data.isShop);

    if (nodeInfo.data.isShop) {
      selectedNodeKey.value = tree.code;
      const checkedNodes = featurePermissionMap[selectedNodeKey.value] || [];
      isAll.value = checkedNodes.length >= modeList.value.length;
      modeTreeRef.value.setCheckedKeys(checkedNodes);
    } else {
      selectedNodeKey.value = '';
    }
  }

  function treeNodeExpand(status) {
    for (var i = 0; i < treeRef.value.store._getAllNodes().length; i++) {
      treeRef.value.store._getAllNodes()[i].expanded = status;
    }
  }

  function packHandle(value) {
    if (value) {
      treeNodeExpand(true);
      expandedKeys.value = props?.permissionList?.map((item: any) => item.key as string) as [];
    } else {
      expandedKeys.value = [];
      treeNodeExpand(false);
    }
  }

  function handleCheckAll(value) {
    // if (!value) {
    //   formParams.value.permissions = [];
    //   treeRef.value!.setCheckedKeys([]);
    // } else {
    //   const allTreeNodes = treeRef.value.store._getAllNodes().map((item) => item.data.code);
    //   console.log('allTreeNodes', allTreeNodes.length);

    //   treeRef.value!.setCheckedKeys(allTreeNodes);
    // }
    if (!value) {
      featurePermissionMap[selectedNodeKey.value] = [];
      modeTreeRef.value.setCheckedKeys(featurePermissionMap[selectedNodeKey.value]);
    } else {
      featurePermissionMap[selectedNodeKey.value] = modeList.value.map((item) => item.key);
      modeTreeRef.value.setCheckedKeys(featurePermissionMap[selectedNodeKey.value]);
    }
  }

  // function checkedTree(tree, checkedInfo) {
  //   console.log(tree);
  //   console.log(checkedInfo);

  //   const nodes = checkedInfo.checkedNodes;
  //   console.log('nodes', nodes);

  //   const halfKeys = checkedInfo.halfCheckedKeys;
  //   formParams.value.permissionList = checkedInfo.halfCheckedKeys;
  //   formParams.value.permissionList = nodes
  //     .filter((item) => item.isShop)
  //     .map((node) => {
  //       return {
  //         workshopCode: node.code,
  //         permissionId: '0',
  //       };
  //     });
  //   formParams.value.permissionKeys = halfKeys;
  //   const allTreeNodes = treeRef.value.store._getAllNodes().map((item) => item.data.code);
  //   if (nodes.length < allTreeNodes.length) {
  //     isAll.value = false;
  //   } else {
  //     isAll.value = true;
  //   }
  // }

  const getPermissionList = () => {
    const newPerm = [] as any[];
    Object.entries(featurePermissionMap).forEach((item) => {
      if (item[0]) {
        (item[1] as number[]).forEach((key) => {
          newPerm.push({
            workshopCode: item[0],
            permissionId: key + '',
          });
        });
      }
    });
    console.log(newPerm);

    return newPerm;
  };

  function checkedModeTree(_, tree) {
    isAll.value = tree.checkedKeys.length >= modeList.value.length;
    featurePermissionMap[selectedNodeKey.value] = tree.checkedKeys;
  }

  function openDrawer(roleId?) {
    isAll.value = false;
    selectedNodeKey.value = '';
    if (roleId) {
      formParams.value.roleId = roleId;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit() {
    formRef.value.validate((valid) => {
      if (!valid) {
        return message.error('请填写完整信息');
      }
      formParams.value.permissionList = getPermissionList();

      if (formParams.value.roleId) {
        const updateData = {
          permissionList: formParams.value.permissionList,
          remark: formParams.value.remark,
          roleName: formParams.value.roleName,
          roleCode: formParams.value.roleCode,
          roleType: 3,
          roleId: formParams.value.roleId,
        };
        updateRole(updateData).then((_) => {
          message.success('编辑成功');
          emit('change');
          handleReset();
          closeDrawer();
        });
      } else {
        const addData = {
          permissionList: formParams.value.permissionList,
          remark: formParams.value.remark,
          roleName: formParams.value.roleName,
          roleCode: formParams.value.roleCode,
          roleType: 3,
        };
        addRole(addData).then((_) => {
          message.success('添加成功');
          emit('change');
          handleReset();
          closeDrawer();
        });
      }
    });
  }

  function handleReset() {
    formRef.value.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
    treeRef.value!.setCheckedKeys([]);
    // isAll.value = false;
  }
  function setFeaturePermission(permissionList) {
    for (const item of permissionList) {
      console.log(item);

      if (featurePermissionMap[item.workshopCode]) {
        featurePermissionMap[item.workshopCode].push(item.permissionId);
      } else {
        featurePermissionMap[item.workshopCode] = [item.permissionId];
      }
    }
  }
  // const selectNodes = ref<string[]>([]);
  function getInfo() {
    roleUserInfo({ roleId: formParams.value.roleId }).then((res) => {
      const info = {
        roleId: res.id,
        roleName: res.roleName,
        roleCode: res.roleCode,
        remark: res.remark,
        permissionList: res.permissionIds || [],
        permissionKeys: res.permissionKeys || [],
      };
      formParams.value = info;
      isDrawer.value = true;
      setFeaturePermission(res.permissionMap);
      // nextTick(() => {
      //   selectNodes.value = res.permissionMap.map((item) => item.workshopCode);
      //   // 将匹配到的节点的键值数组传递给 setCheckedKeys 方法
      //   treeRef.value.setCheckedKeys(selectNodes.value);
      // });
    });
  }

  onMounted(() => {
    getSceneDetail();
    getFeaturePermissions().then((res) => {
      if (res[0]?.children) {
        modeList.value = res[0].children;
      }
    });
  });

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>

<style scoped>
  .mark-left {
    position: absolute;
    width: 4px;
    height: 28px;
    top: 0;
    background-color: #1890ff;
  }

  .permission-name {
    height: 28px;
    font-weight: 500;
    display: flex;
    align-items: center;
  }

  :deep(.el-divider--horizontal) {
    margin: 12px 0;
  }

  .permission-card {
    width: 100%;
  }

  :deep(.permission-card .el-card__body) {
    padding-top: 0;
  }
  :deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
    color: #409eff;
  }
</style>
