import {
  PlusOutlined,
  ExclamationCircleOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  FileAddOutlined,
  PlusCircleOutlined,
  AppleOutlined
} from '@ant-design/icons';

import { PageLoading } from '@ant-design/pro-layout';

import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProDescriptions, { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import MenuForm from './components/MenuForm';
import CreateRoleForm from './components/CreateRoleForm';
import UpdateRoleForm from './components/UpdateRoleForm';
import type { MenuItem, RoleInfo, RoleListItem, RoleParams } from './data.d';
import {
  queryRole,
  updateRule,
  addRole,
  removeRole,
  updateRoleMenu,
  queryAllRelations,
  getPrivilegeTree,
  updateAuthRole,
} from './service';

import type { RadioChangeEvent } from 'antd';

import { Button, Divider, message, Drawer, Modal, Radio, Tabs, Tooltip, Space, Row, Col, Checkbox } from 'antd';
import Title from 'antd/lib/typography/Title';
import { CheckboxValueType } from 'antd/lib/checkbox/Group';
import { CheckboxChangeEvent } from 'antd/lib/checkbox';
import CheckboxList from './components/CheckboxList';

type TargetKey = React.MouseEvent | React.KeyboardEvent | string;

// const defaultPanes = new Array(2).fill(null).map((_, index) => {
//   const id = String(index + 1);
//   return { label: `Tab ${id}`, children: `Content of Tab Pane ${index + 1}`, key: id };
// });

const defaultPanes = [
  {
    label: (
      <span>
        Tab 1
        <Button type="text" icon={<EditOutlined />} />
      </span>
    ), children: 'Content of Tab 1', key: '1'
  },
  { label: 'Tab 2', children: 'Content of Tab 2', key: '2' },
  {
    label: 'Tab 3',
    children: 'Content of Tab 3',
    key: '3',
    closable: false,
  },
];

type TabPosition = 'left' | 'right' | 'top' | 'bottom';

const { confirm } = Modal;



/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: RoleListItem) => {
  const hide = message.loading('正在添加');
  try {

    console.log(fields)
    await addRole({ ...fields });
    hide();
    message.success('添加成功');

    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: RoleInfo) => {
  const hide = message.loading('正在更新');
  try {
    await updateRule(fields);
    hide();

    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};


/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (roleName: string) => {
  const hide = message.loading('正在删除');
  if (!roleName) return true;
  try {
    await removeRole(roleName);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
interface StateType {
  [key: string]: string[];
}


/**
 * 更新权限
 * @param fields
 */
const handleUpdateRole = async (fields: RoleParams) => {
  const hide = message.loading('正在更新权限');
  try {
    await updateAuthRole(fields);
    hide();

    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};


const TableList: React.FC = () => {

  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [updateMenuModalVisible, handleUpdateMenuModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<RoleInfo>();

  const [mode, setMode] = useState<TabPosition>('left');
  const [initPage, setInitPage] = useState<boolean>(false);
  const [initRolePage, setInitRolePage] = useState<boolean>(false);

  const [activeKey, setActiveKey] = useState("超级管理员");
  // const [items, setItems] = useState(defaultPanes);
  const [items, setItems] = useState<RoleInfo[]>([]);
  const [menuItem, setMenuItem] = useState<MenuItem[]>([]);
  const [menuItemCache, setMenuItemCache] = useState<MenuItem[]>([]);


  const [newRole, setNewRole] = useState<string[]>([]);

  const [newState, setNewState] = useState<StateType>();


  const newTabIndex = useRef(0);

  const initFunc = async () => {
    let res = await queryAllRelations({ pageSize: 100, current: 0 })

    console.log("--queryAllRelations---->", res)

    setInitPage(true)

    let newRes = res.data



    for (let _index = 0; _index < newRes.length; _index++) {
      const _item: RoleInfo = newRes[_index];
      newRes[_index] = {
        ...newRes[_index],
        label: `${_item.role_name}`,
        children: `Content of Tab Pane ${_index + 1}`,
        key: _item.id,

      }
    }
    setItems(newRes)

    return new Promise(resolve => {
      resolve(getTreeFunc(newRes));
    });
  }

  const getTreeFunc = async (e: RoleInfo[]) => {
    getPrivilegeTree().then((res) => {
      console.log("--getPrivilegeTree---->", res)


      let newRes = res.data as MenuItem[]
      if (newRes.length == 0) return

      console.log("--getPrivilegeTree: items---->", e, items)

      // for (let index = 0; index < newRes.length; index++) {
      //   const _item: MenuItem = newRes[index];


      //   if (_item.children == null) return
      //   const childrenRes: MenuItem[] = _item.children
      //   for (let i = 0; i < childrenRes.length; i++) {
      //     const x: MenuItem = childrenRes[i];


      //     for (let y = 0; y < e.length; y++) {
      //       const v = e[y];
      //       console.log("-----v-----", _item.label)
      //       if (v.role_name == _item.label) {



      //         const privileges = v.privileges
      //         if (childrenRes == null) return
      //         console.log("-=-=-=-=-=-=-=-=", x, privileges, privileges.includes(x.name))
      //         childrenRes[y] = {
      //           ...childrenRes[y],
      //           disabled: privileges.includes(x.name)
      //         }
      //       }

      //     }

      //   }

      //   newRes[index] = {
      //     ...newRes[index],
      //     children: childrenRes

      //   }
      // }

      setMenuItem(newRes)
      // setMenuItemCache(newRes)

      setInitRolePage(true)
      return

    });
  }


  useEffect(() => {
    let isMounted = true
    const fetchPost = async () => {
      if (isMounted) {

        await initFunc()


      }
    }

    fetchPost()

    return () => {
      isMounted = false

    }
  }, [])




  const showDeleteConfirm = (item: string) => {
    confirm({
      title: '是否删除记录?',
      icon: <ExclamationCircleOutlined />,
      content: '删除的记录不能恢复,请确认!',
      onOk() {
        handleRemove(item).then(() => {
          initFunc()
        });


      },
      onCancel() {
      },
    });
  };


  const onChange = (key: string) => {
    const activeItem = items.find(i => {
      if (i.role_name == key) {
        return i
      }

    })
    // console.log(key, activeItem, items)
    setActiveKey(key);

    if (activeItem?.privileges != undefined) {
      setNewRole(activeItem?.privileges)
    }

  };

  // const add = () => {
  //   handleModalVisible(true)
  //   const newActiveKey = `newTab${newTabIndex.current++}`;
  //   setItems([...items, { label: 'New Tab', children: 'New Tab Pane', key: newActiveKey }]);
  //   setActiveKey(newActiveKey);
  // };

  // const remove = (targetKey: TargetKey) => {
  //   const targetIndex = items.findIndex((pane) => pane.key === targetKey);
  //   const newPanes = items.filter((pane) => pane.key !== targetKey);
  //   if (newPanes.length && targetKey === activeKey) {
  //     const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex];
  //     setActiveKey(key);
  //   }
  //   setItems(newPanes);
  // };

  // const onEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {
  //   if (action === 'add') {
  //     add();
  //   } else {
  //     remove(targetKey);
  //   }
  // };




  return (
    <PageContainer>
      {
        !(initPage && initRolePage) ? <PageLoading />
          : <div>
            <div style={{ marginBottom: 16 }}>
              <Tooltip title="权限组">
                权限组
                <Button type="link" onClick={() => handleModalVisible(true)} icon={<PlusCircleOutlined />} />
              </Tooltip>
            </div>


            <Tabs
              hideAdd
              defaultActiveKey="1"
              tabPosition={mode}
              addIcon={<PlusCircleOutlined />}
              onChange={onChange}
              activeKey={activeKey}
              // type="editable-card"
              type="card"
              // onEdit={onEdit}
              items={items.map((r: RoleInfo, i) => {

                // 进行组装
                const newKey = r.role_name
                console.log("=============>", newKey, r.role_alias, r.privileges)

                // setNewState(prevState => ({
                //   ...prevState,
                //   [newKey]: ["newValue1", "newValue2"]
                // }));

                const newMeunItem = menuItem
                const storeName = `Role-${r.role_name}`

                console.log("========newMeunItem=====>", newMeunItem)

                for (let index = 0; index < newMeunItem.length; index++) {
                  const element = newMeunItem[index];
                  if (element.children == null) continue

                  for (let x = 0; x < element.children.length; x++) {
                    const ele = element.children[x];


                    if (ele && r.privileges.includes(ele.name)) {

                      ele.is_inherent = true
                    } else {
                      ele.is_inherent = false
                    }

                    element.children[x] = ele

                  }

                  newMeunItem[index] = element

                }

                window.localStorage.setItem(storeName, JSON.stringify(menuItem))


                return {
                  label: (
                    <Space key={r.role_name + i} wrap size={30}>
                      {r.role_name}
                      {!r.is_inherent && <Button
                        type="text"
                        icon={<EditOutlined />}
                        onClick={() => {
                          console.log(i, r.role_name)
                          setCurrentRow(r);
                          handleUpdateModalVisible(true)
                        }}

                      />}
                    </Space>
                  ),
                  key: r.role_name,
                  children: <div
                    key={i}
                    style={{
                      // display: "flex",
                      // alignItems: "center",
                      // justifyContent: "space-between",
                      // fontSize: "12px",
                    }}
                  >
                    {/* <Title level={3}>权限配置</Title> */}
                    <Divider orientation="left">权限配置</Divider>

                    {menuItem.map((x, y) => {

                      // setMenuItem(prevState => {
                      //   const index = prevState.findIndex(item => item.label === x.label);

                      //   console.log("index", index)
                      //   if (index !== -1) {
                      //     const updatedMenuItem = { ...prevState[index], disabled: true };
                      //     const newMenuItems = [...prevState];
                      //     newMenuItems[index] = updatedMenuItem;
                      //     return newMenuItems;
                      //   }
                      //   return prevState;
                      // });

                      return <div key={y} >

                        <Checkbox style={{ display: "none" }} disabled>Checkbox</Checkbox>

                        <CheckboxList
                          is_inherent={r.is_inherent}
                          currentMenuData={x}
                          currentRoleData={r}
                          setMenuItem={setMenuItem}
                          onSubmit={(v: any) => {
                            // const activeItem = items.find(i => {
                            //   if (i.role_name == x) {
                            //     return i
                            //   }

                            // })
                            const plainOptions: string[] = x.children ? x.children.map(item => item.name) : []

                            console.log("操作: ", x.label, plainOptions, v)
                            console.log("-----当前权限--------: ", r.privileges)

                            const currRoleData = JSON.parse(window.localStorage.getItem(storeName)!)

                            let privilege: string[] = []

                            console.log("-----currRoleData--------: ", currRoleData)

                            for (let index = 0; index < currRoleData.length; index++) {
                              const element = currRoleData[index];
                              if (element.children == null) continue

                              if (x.label == element.label) {
                                console.log("-----element.label--------: ", element)
                                for (let x = 0; x < element.children.length; x++) {
                                  const ele = element.children[x];


                                  if (ele && v.includes(ele.name)) {

                                    ele.is_inherent = true
                                  } else {
                                    ele.is_inherent = false
                                  }

                                  element.children[x] = ele

                                }
                              }

                              currRoleData[index] = element

                            }




                            window.localStorage.setItem(storeName, JSON.stringify(currRoleData))
                          }}
                        ></CheckboxList>


                      </div>
                    })}

                    {!r.is_inherent && <Button type="primary" disabled={r.is_inherent} block onClick={async () => {
                      console.log(r.role_name, r.privileges)
                      const currRoleData = JSON.parse(window.localStorage.getItem(storeName)!)
                      let privilege: string[] = []

                      console.log("-----currRoleData--------: ", currRoleData)

                      for (let index = 0; index < currRoleData.length; index++) {
                        const element = currRoleData[index];
                        if (element.children == null) continue

                        for (let x = 0; x < element.children.length; x++) {
                          const ele = element.children[x];

                          if (ele.is_inherent) {
                            console.log("-----ele--------: ", ele.label, ele.name)
                            privilege.push(ele.name)
                          }

                        }


                      }
                      if (await handleUpdateRole({
                        role_name: newKey,
                        privilege
                      } as RoleParams)) {
                        await initFunc()
                      }

                    }}>提交</Button>}

                  </div>
                }
              })
              }
            />
          </div>
      }
      <CreateRoleForm
        key={'CreateRoleForm'}
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);
            // if (actionRef.current) {
            //   actionRef.current.reload();
            // }
            initFunc()
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        createModalVisible={createModalVisible}
      />

      <UpdateRoleForm
        key={'UpdateRoleForm'}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            // if (actionRef.current) {
            //   actionRef.current.reload();
            // }
            initFunc()
          }
        }}
        onDelete={async (value) => {
          await showDeleteConfirm(value);

          handleUpdateModalVisible(false);
          setCurrentRow(undefined);

        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalVisible={updateModalVisible}
        currentData={currentRow || {}}
      />

    </PageContainer>
  );
};

export default TableList;
