import { PlusOutlined } from '@ant-design/icons';
import {
  ProTable,
  ProForm,
  ProFormText,
  ModalForm,
} from '@ant-design/pro-components';
import { Button, Card, } from 'antd';
import { useRef, useState, useEffect } from 'react';
import { adminRolesConnect, adminUserRoleIdConnect, adminRolassignPermissionConnect, adminResourceConnect, adminResourceChildConnect, adminResourceRootConnect } from '@/services/Limits/index';
import { Popconfirm, message } from 'antd';
import React from 'react';
import { Tree } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { curdSet } from '@/utils/index';  //页面权限配置表


export default () => {

  const formRef = useRef<any>();
  const [modalVisit, setModalVisit] = useState(false);
  const [modalVisit1, setModalVisit1] = useState(false);
  const [addVis, setAddVis] = useState(true);
  const [removeVis, setRemoveVis] = useState(true);
  const [editVis, setEditVis] = useState(true);
  const [searchVis, setSearchVis] = useState(true);
  const [limitsVis, setLimitsVis] = useState(true);
  const [treeData, setTreeData] = useState([]);
  //设置是否选中
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  //设置是否展开
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([1, 2, 3, 4, 5, 6, 7]);
  const [roleId, setRoleId] = useState<any>(null);


  const columns = [
    { align: 'center', search: false, title: "序号", width: 68, render: (text, record, index) => `${index + 1}`, },
    {
      dataIndex: 'code',
      title: '角色名称',
      align: 'center',
    },
    {
      dataIndex: 'roleType',
      title: '角色类型',
      align: 'center',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'x',
      align: 'center',
      valueType: 'option',
      render: (_, record) => {
        return [
          <>
            <Button
              key="limits"
              type="primary"
              style={!limitsVis ? {} : { background: '#87d068', border: 'none' }}
              disabled={!limitsVis}
              onClick={async (e) => {
                setModalVisit(true);
                setRoleId(record.id)
                let defaultKey = [] as any
                await adminUserRoleIdConnect(record.code).then((res: any) => {

                  for (let index = 0; index < res.length; index++) {
                    const element = res[index];

                    adminResourceConnect(element?.id).then((res: any) => {
                      let { data } = res
                      for (let index = 0; index < data.length; index++) {
                        const element = data[index];
                        console.log(element?.id);
                        defaultKey.push(element?.id)
                      }
                    })
                    console.log(defaultKey);
                    setCheckedKeys(defaultKey)
                  }
                })


              }}
            >
              权限设置
            </Button>
          </>,
          <> <Button
            key="editable"
            type="primary"
            style={!editVis ? {} : { background: '#2db7f5', border: 'none' }}
            disabled={!editVis}
            onClick={async (e) => {
              setModalVisit1(true);
              await onView(record);
            }}
          >
            修改
          </Button> </>,
          <>
            <Popconfirm
              title="确认删除？"
              onConfirm={() => { }}
              onCancel={() => { }}
              disabled={!removeVis}
            >

              <Button
                key="remove"
                type="primary"
                danger
                disabled={!removeVis}
              >
                删除
              </Button>
            </Popconfirm>
          </>
        ];
      },
    },
  ];




  useEffect(() => {
    // 设置权限
    limitsSet('角色管理')
    searchRoot()  // 查询根目录
  }, [])

  // 查询根目录
  const searchRoot = () => {
    adminResourceRootConnect().then((res: any) => {
      setTreeData(res?.data)
    })
  }


  // 设置权限
  const limitsSet = (name: String) => {
    let obj = curdSet(name)
    return
    if (obj) {
      setAddVis(obj.filter((item: any) => item.name === '添加')[0].select)
      setRemoveVis(obj.filter((item: any) => item.name === '删除')[0].select)
      setEditVis(obj.filter((item: any) => item.name === '修改')[0].select)
      setSearchVis(obj.filter((item: any) => item.name === '查看')[0].select)
    }
  }



  // 查看详情
  const onView = (record: any) => {
    setTimeout(() => {
      formRef?.current?.setFieldsValue(record);
    }, 100)
  };


  // 权限修改
  const finshlimits = () => {
    adminRolassignPermissionConnect({ roleId, permissionId: checkedKeys }).then((res: any) => {
      console.log(res);
      message.success('权限设置成功');
    })
  };


  const getAllChildrenID = (arr: any) => {
    let result = [];

    // 遍历传入的数组  
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];

      if (item.children && item.select) {
        // 将当前项添加到结果数组中  
        result.push(item.id);
      }

      // 如果当前项有children属性且是一个数组  
      if (item.children && Array.isArray(item.children)) {
        // 递归调用getAllChildrenID函数，并将返回的数组与当前结果合并  
        result = result.concat(getAllChildrenID(item.children));
      }
    }

    return result;
  }



  const onCheck = (checkedKeysValue: React.Key[]) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };




  const updateTreeData = (list: any[], key: React.Key, children: any[]): any[] =>


    list.map((node) => {
      if (node.id === key) {
        return {
          ...node,
          children,
        };
      }
      if (node.children) {
        return {
          ...node,
          children: updateTreeData(node.children, key, children),
        };
      }
      return node;
    });


  const onLoadData = (note: any) =>

    new Promise<void>((resolve) => {
      if (note?.children) {
        resolve();
        return;
      }

      adminResourceChildConnect(note?.key).then((res: any) => {

        let { data } = res

        for (let index = 0; index < data.length; index++) {
          const element = data[index];
          element.name = element.note
        }

        setTreeData((origin: any) =>
          updateTreeData(origin, note?.key, data),
        );
        resolve();
      })

    });

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={adminRolesConnect}
        rowKey="id"
        cardBordered
        pagination={{
          showQuickJumper: true,
        }}
        search={searchVis ? {
          labelWidth: 'auto',
        } : false}
        toolBarRender={() => [
          <>
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              disabled={!addVis}
              onClick={() => {
                setModalVisit1(true);
              }}
            >
              新建
            </Button>
          </>
        ]}
      />

      {/* 权限设置 */}
      <ModalForm
        title="权限设置"
        visible={modalVisit}
        onVisibleChange={setModalVisit}
        layout={"horizontal"}
        onFinish={() => {
          finshlimits()   // 权限修改
          return true;
        }}
      >
        <Tree
          checkable
          defaultExpandedKeys={expandedKeys}
          onCheck={onCheck}
          checkedKeys={checkedKeys}
          treeData={treeData}
          loadData={onLoadData}
          fieldNames={{ title: 'note', key: 'id', children: 'children' }}
        />
      </ModalForm>

      {/* 角色新建和修改 */}
      <ModalForm
        formRef={formRef}
        title="角色设置"
        visible={modalVisit1}
        onVisibleChange={setModalVisit1}
      >

        <Card>
          <ProForm.Group>
            <ProFormText width="md" name="roleName" label="角色名" placeholder="请输入角色名" />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText width="md" name="roleCode" label="角色编码" placeholder="请输入角色编码" />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText width="md" name="note" label="备注" placeholder="请输入角色备注" />
          </ProForm.Group>
        </Card>
      </ModalForm>
    </PageContainer>
  );

};