<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"
                show-checkbox
                node-key="code"
                :render-after-expand="false"
                :data="treeData"
                :props="treeProps"
                @node-click="clickNode"
                @check-change="checkNode"
              />
            </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, computed, nextTick } 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, _, __) {
    if (tree.code in featurePermissionMap) {
      selectedNodeKey.value = tree.code;
      isAll.value = featurePermissionMap[tree.code].length >= modeList.value.length;
      modeTreeRef.value.setCheckedKeys(featurePermissionMap[tree.code]);
    } else {
      isAll.value = false;
      selectedNodeKey.value = '';
    }
  }

  const checkNode = (checkedNodes, checkedKeys) => {
    if (checkedKeys) {
      if (checkedNodes.isShop && !(checkedNodes.code in featurePermissionMap)) {
        selectedNodeKey.value = checkedNodes.code;
        isAll.value = true;
        handleCheckAll(true);
      }
    } else {
      if (checkedNodes.isShop && checkedNodes.code in featurePermissionMap) {
        delete featurePermissionMap[checkedNodes.code];
      }
      selectedNodeKey.value = '';
      isAll.value = false;
      handleCheckAll(false);
    }
  };

  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;
    const selectLength = tree.checkedKeys.length;
    if (selectLength === 0) {
      delete featurePermissionMap[selectedNodeKey.value];
      treeRef.value!.setCheckedKeys(Object.keys(featurePermissionMap));
    }
  }

  function openDrawer(roleId?) {
    isAll.value = false;
    selectedNodeKey.value = '';
    Object.keys(featurePermissionMap).forEach((key) => {
      delete featurePermissionMap[key];
    });

    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();
    Object.keys(featurePermissionMap).forEach((key) => {
      delete featurePermissionMap[key];
    });
    formParams.value = Object.assign(formParams.value, defaultValueRef());
    treeRef.value!.setCheckedKeys([]);
    modeTreeRef.value!.setCheckedNodes([]);
    isAll.value = false;
    selectedNodeKey.value = '';
  }
  function setFeaturePermission(permissionList) {
    for (const item of permissionList) {
      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);
      const treeSelectData = Object.keys(featurePermissionMap);
      isAll.value = false;
      selectedNodeKey.value = '';

      // const modeTreeSelectData = Object.values(featurePermissionMap)[0] as Array<string>;
      // isAll.value = modeTreeSelectData.length >= modeTreeData.value.length;

      // nextTick(() => {
      //   selectNodes.value = res.permissionMap.map((item) => item.workshopCode);
      //   // 将匹配到的节点的键值数组传递给 setCheckedKeys 方法
      //   treeRef.value.setCheckedKeys(selectNodes.value);
      // });
      nextTick(() => {
        treeRef.value?.setCheckedKeys(treeSelectData, true);
        modeTreeRef.value?.setCheckedKeys([]);
      });
    });
  }

  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>
