import { MyBetaModalFormProps, MyButtons } from '@/common';
import { Apis } from '@/gen/Apis';
import { ProCard } from '@ant-design/pro-components';
import { message, Space, Tree, TreeProps } from 'antd';
import { DataNode } from 'antd/es/tree';
import { useEffect, useState } from 'react';

export default function Index(props: MyBetaModalFormProps) {
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);

  const processTree = (item: any): DataNode => {
    return {
      ...item,
      key: item.id,
      title: item.id + '_' + item.name,
      children: item.children?.map(processTree),
    };
  };

  const getPermissions = () => {
    //获取已经配置的，菜单
    Apis.Company.CompanyPermissions.GetPermissions({
      companies_id: props?.item?.id || 0,
    }).then((res: any) => {
      console.log('res', res);
      setCheckedKeys(res?.data?.permissions_ids);
    });
  };

  const getPermissionTree = () => {
    //获取机构可配置菜单
    Apis.Company.CompanyPermissions.PermissionTree().then((res: any) => {
      const data = res.data?.map(processTree);
      setTreeData(data);
      getPermissions();
    });
  };

  useEffect(() => {
    getPermissionTree();
  }, []);

  const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys, info);
    const ids: string[] = [];
    info.checkedNodes?.forEach((item: DataNode) => {
      if (item.children?.length === 0) {
        ids.push(item.key as string);
      }
    });
    console.log('ids', ids);
    setCheckedKeys(ids);
    // props.onChange?.(ids);
  };

  return (treeData?.length ?? 0) > 0 ? (
    <ProCard
      extra={[
        <MyButtons.Default
          title="保存"
          size="middle"
          type="primary"
          key="save"
          onClick={() => {
            Apis.Company.CompanyPermissions.SetPermissions({
              companies_id: props?.item?.id || 0,
              permissions_ids: checkedKeys || [],
            }).then(() => {
              message.success('保存成功');
            });
          }}
        />,
      ]}
    >
      <Space direction="vertical">
        <Tree
          checkable
          defaultExpandAll
          treeData={treeData}
          onCheck={onCheck}
          checkedKeys={checkedKeys || []}
          {...props}
        />
      </Space>
    </ProCard>
  ) : (
    <></>
  );
}
